• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar

Thoughts on Java

  • Tutorials ▼
    • Hibernate & JPA Tutorials
    • Hibernate Tips
    • Tutorials on YouTube
  • Books & Training ▼
    • Hibernate Tips Book
    • Online Training
    • On-Site Training
  • Consulting ▼
    • Consulting Call
    • Project Coaching
  • About ▼
    • About Thoughts on Java
    • Support Thoughts on Java
    • Resources
  • Member Library
You are here: Home / Hibernate / Hibernate Tips / Hibernate Tips: How to Map java.time.Year with JPA and Hibernate
Special thanks to all Thoughts on Java Supporters for supporting this article!

Hibernate Tips: How to Map java.time.Year with JPA and Hibernate

By Thorben Janssen Leave a Comment

  • tweet 
  • share 
  • share 
  • share 
  • share 
  • share 
  • e-mail 


Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question for a future Hibernate Tip, please post a comment below.

 

Question:

How can I map a java.time.Year attribute with Hibernate?
 

Solution:

JPA 2.2 and Hibernate support several classes of the Date and Time API. Unfortunately, the java.time.Year class isn’t one of them. If you want to use it as an attribute type, you need to provide a custom mapping for it.

But don’t worry, you can do that easily with an AttributeConverter, and it only requires a few lines of code.

An AttributeConverter provides a portable way to create custom type mappings. The only thing you need to do is to implement the AttributeConverter interface and annotate your class with the @Converter annotation.

 

Implementing the YearConverter

Here you can see an example of an AttributeConverter that maps a java.time.Year object to a Short.

@Converter(autoApply = true)
public class YearConverter implements AttributeConverter<Year, Short> {
	
	Logger log = Logger.getLogger(YearConverter.class.getSimpleName());

	@Override
	public Short convertToDatabaseColumn(Year attribute) {
		short year = (short) attribute.getValue();
		log.info("Convert Year ["+attribute+"] to short ["+year+"]");
		return year;
	}

	@Override
	public Year convertToEntityAttribute(Short dbValue) {
		Year year = Year.of(dbValue);
		log.info("Convert Short ["+dbValue+"] to Year ["+year+"]");
		return year;
	}
}

As you can see, the implementation of a converter is very simple. The interface only defines a method to convert the entity attribute to its database representation and another one for the inverse operation.

In this example, the implementation of these 2 methods is pretty simple because the Year class already provides methods to get the Integer value of a give Year object and to create a Year object from an Integer. You can then either persist the Integer or you can try to save some space and cast it to a Short.

When you annotate your AttributeConverter with the @Converter annotation, you should ask yourself if you want to use it for all attributes of the converted type. If you want to do that, you should set the autoApply attribute to true. Hibernate will then use the converter automatically, and you don’t need to use any additional mapping annotation. In this case, the decision is easy. Hibernate doesn’t support java.time.Year as a type and you should use it for all entity attributes of that type.

 

Using the YearConverter

After you implemented the YearConverter and added it to your project, you can use java.time.Year as an attribute type. And because you set the autoApply attribute to true, you can do that without any additional mapping annotations.

@Entity
public class OnlineCourse {

	@Id
	@GeneratedValue
	private Long id;

	private String title;

	private Year publishingYear;

	@Version
	private long version;

	...
}

Get this Hibernate Tip as a printable PDF!

Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
Join Now!

Already a member? Login here.

Learn more:

If you liked this article, you might also be interested in:

  • JPA Tips: How to map a Duration attribute
  • How to implement a JPA Attribute Converter
  • JPA 2.1 Attribute Converter – The better way to persist enums
 

Hibernate Tips Book


Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.

Get it now as a paperback, ebook or PDF.
  • tweet 
  • share 
  • share 
  • share 
  • share 
  • share 
  • e-mail 
Become a Thoughts on Java Supporter to claim your member perks and to help me write more articles like this.

Filed Under: Hibernate Tips

Implement Your Persistence Layer with Ease

Learn More About Hibernate

Need Some Help with Your Project?

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Join over 10.000 developers
in the
Thoughts on Java Library

Ebooks Sidebar Get free access to ebooks, cheat sheets and training videos.
Join Now!
Don't like ads?
Become a Thoughts on Java Supporter.
Special Launch Price

Let’s Connect


Thorben Janssen
Independent consultant, trainer and author
  • Facebook
  • GitHub
  • Google+
  • LinkedIn
  • Twitter
  • xing
  • YouTube

Speaking at

7th February 2019
JUG Ostfalen (Germany):
Hibernate Tips 'n' Tricks: Typische Probleme schnell gelöst (Talk - German)

19th March 2019
JavaLand 2019 (Germany):
Hibernate Tips 'n' Tricks: Typische Probleme schnell gelöst (Talk - German)

21st March 2019
JavaLand 2019 (Germany):
Hibernate + jOOQ + Flyway = Die besten Frameworks in einem Stack (1-day Workshop - German)

6th-10th May 2019
JAX 2019 (Germany):
Hibernate Workshop: Komplexe Lösungen jenseits von CRUD (2-day Workshop - German)

6th-10th May 2019
JAX 2019 (Germany):
Spring Data JDBC vs. Spring Data JPA – Wer macht das Rennen? (Talk - German)

6th-10th May 2019
JAX 2019 (Germany):
Microservices mit Hibernate – typische Probleme und Lösungen (Talk - German)

Looking for an on-site training?

Featured Post

14 YouTube Channels You Should Follow in 2019

Getting Started With Hibernate

Entities or DTOs – When should you use which projection?

Ultimate Guide – Association Mappings with JPA and Hibernate

Ultimate Guide to JPQL Queries with JPA and Hibernate

Recent Posts

  • Hibernate Tips: How to Customize a Constructor Expression for Different Subclasses
  • Hibernate Tips: How to Map java.time.Year with JPA and Hibernate
  • Why, When and How to Use DTO Projections with JPA and Hibernate
  • Hibernate Tip: Map a bidirectional one-to-one association with shared composite primary key
  • Implementing the Repository pattern with JPA and Hibernate
  • Hibernate Tips: How to Handle NULL Values while Ordering Query Results in a CriteriaQuery
  • 6 Hibernate Best Practices for Readable and Maintainable Code
  • Can you use Hibernate/EclipseLink/JPA for your microservice?
  • 14 YouTube Channels You Should Follow in 2019
  • Hibernate Tips: How To Map an Entity to a Query
Don't like ads?
Become a Thoughts on Java Supporter.

Copyright © 2019 Thoughts on Java

  • Impressum
  • Disclaimer
  • Privacy Policy