Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist Joda-time's DateTime via Hibernate

I'm using Jodatime in my Play app, but currently having to do a bunch of converting back and forth from/to java.util.Date and java.sql.Time.

Since jodatime is included in the Play distribution, I'm thinking there's probably a better way to do this. Is there any way I can make my Model fields DateTimes instead of java.util.Date and java.sql.Time so the conversion is done automatically? Is there another way of streamlining this?

like image 368
Brad Mace Avatar asked Jun 08 '11 19:06

Brad Mace


People also ask

What is the replacement of Joda-time?

Correct Option: D. In java 8,we are asked to migrate to java. time (JSR-310) which is a core part of the JDK which replaces joda library project.

Is Joda-time deprecated?

So the short answer to your question is: YES (deprecated).

Is Joda-time followed in Java 8?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.

What is timestamp in hibernate?

When you persist a new MyEntity, Hibernate will get the current time from the VM and store it as the creation and update timestamp. As you can see in the log output, Hibernate gets a new timestamp for each attribute. The creation and update timestamp will therefore not be the same even if the entity was never updated.


3 Answers

For Hibernate 3 add the following annotation to your date field:

@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")

Hibernate will now do the dirty work for you.

(Make sure you have joda-time-hibernate.jar in your classpath)

UPDATE:

For Hibernate 4 and 5 add the following annotation:

@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")

(Make sure you have jadira-usertype-core.jar in your classpath)

like image 92
Kees de Kooter Avatar answered Sep 30 '22 23:09

Kees de Kooter


  1. Joda recommends to use the UserType libraries with Hibernate 4.0, the version of Hibernate bundled with Play 1.2.x (see: http://joda-time.sourceforge.net/contrib/hibernate/index.html).

  2. The proper way to handle the dependency is using the dependencies.yml file, including a line like this:

    - org.jadira.usertype -> usertype.jodatime 2.0.1
    
like image 28
Samuel Avatar answered Sep 30 '22 23:09

Samuel


Instead of putting the @Type annotation at each of your Joda properties you can add this in your jpa properties

#Hibernate config
jadira.usertype.autoRegisterUserTypes=true

and it should work just fine.

ps. jadira-usertype-core.jar should be in your classpath.

like image 29
naXa Avatar answered Sep 27 '22 23:09

naXa