cguzel
cguzel

Reputation: 1735

To Use java.util.Date object as Primary Key

I want to use Date object as primary key. But I have an error. How can I use java.util.Date object as primary key ?

MyEntity:

@Entity
public class MyEntity implements Serializable {

    @Id
    private Date date;
...

Error log:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myService': Unsatisfied dependency expressed through field 'myEntityRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'routeMeetingDayRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: This class [class com.MyEntity] does not define an IdClass

So, I have added @IdClass in my entity:

MyEntity:

@Entity
@IdClass(Date.class)
public class MyEntity implements Serializable {

    @Id
    private Date date;
...

New Error log:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2017-12-28 11:49:00.859 ERROR 23518 --- [ main] o.s.boot.SpringApplication : Application startup failed

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 org.hibernate.AnnotationException: java.util.Date has no persistent id property
...
...

Caused by: org.hibernate.AnnotationException: java.util.Date has no persistent id property ...

Upvotes: 1

Views: 2820

Answers (1)

AlexG
AlexG

Reputation: 11

I had the same problem, and it was easy to solve it.

Just add this @Temporal(TemporalType.DATE) before your PK. Application will need to add a value into this field, because it is not auto-generated.

@Id
@Temporal(TemporalType.DATE)
private Date date;

Upvotes: 1

Related Questions