Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store Joda Time (any) in Spring JPA with some SQL-compatible column type?

I am learning how to access databases with Spring Boot JPA.

I wrote an application with some entity, containing Instant field:

@Entity
@Table(
   name = "MEAL",
   uniqueConstraints=@UniqueConstraint(columnNames = {"USER_ID", "TIMESTAMP_FIELD"}))
public class Meal {

   //private static DateTimeZone defaultTimeZone = DateTimeZone.UTC;

   @Id
   @GeneratedValue(strategy= GenerationType.AUTO)
   @Column(name = "ID")
   private long id;

   @ManyToOne//(fetch=FetchType.LAZY)
   @JoinColumn(name="USER_ID")
   private User user;

   // @Temporal(TemporalType.TIMESTAMP) if non-Joda time
   //@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") 
   @Column(name = "TIMESTAMP_FIELD")
   private Instant timestampField;

I was unable to compile / run with @Temporal or @Type annotations, so they are commented out.

Also, I was unable to run with the setting of spring.jpa.properties.jadira.usertype.autoRegisterUserTypes in application.properties

It was causing an error

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.Configuration.registerTypeOverride(Lorg/hibernate/usertype/UserType;[Ljava/lang/String;)Lorg/hibernate/cfg/Configuration;

So, this line is also commented out.

spring.datasource.url=jdbc:h2:tcp://localhost/~/pdk
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

# Jadira requirement
#spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true

Unfortunately, at final state I got some serialized/binary data in field content

enter image description here

Is it possible to have some SQL-compatible column type here?

UPDATE

I found, that the following annotation was working fine:

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

But why setting in application.properties does not work?

like image 253
Dims Avatar asked Dec 24 '15 14:12

Dims


1 Answers

Stumbled upon the very same issue, and it turned out that the version of Jadira usertype.core I was using (5.0.0.GA) was binary incompatible with Hibernate 4.x SPI.

Switching to 4.0.0.GA did the trick and registering Jadira's types using jadira.usertype.autoRegisterUserTypes=true started to work.

like image 154
David Siro Avatar answered Sep 28 '22 01:09

David Siro