Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

spring - Java 8 LocalDate in hibernate wrongly mapped to TIMESTAMP

I use Spring boot 1.4.2, which brings hibernate 5.0.11 (JPA 2.1). I want to use the Java 8 time classes in my entities, and so included hibernate-java8.

My entity defines a LocalDate field.

@Entity
@Table(name = "my_alarms_timeline", indexes = {...})
public class MyAlarm {
    ...
    @Column(name = "validity_date")
    @NotNull
    private LocalDate validityDate;
}

I expect this to be mapped to a DATE in my H2 database.

In my DB I declare this as validity_date DATE NOT NULL,.

When I try to run tests, I get the following error:

[INFO] Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: 
    Schema-validation: wrong column type encountered in column [validity_date] in table [my_alarms_timeline]; 
    found [date (Types#DATE)], but expecting [timestamp (Types#TIMESTAMP)]

To my surprise, if I change the DB definition to validity_date TIMESTAMP NOT NULL, I get the error

Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: 
    Schema-validation: wrong column type encountered in column [validity_date] in table [my_alarms_timeline]; 
    found [timestamp (Types#TIMESTAMP)], but expecting [date (Types#DATE)]

This is just the reverse message of the previous one.

I also tried, instead of including hibernate-java8, to use an AttributeConverter<LocalDate, java.sql.Date> but this produces the same error result.

What must I do, so that my LocalDate is mapped correctly to a DATE in the DB?

I also tried with a LocalDateTime field mapped to a TIMESTAMP, and this works without problems...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So I got it to run, by adding a columnDefinition="DATE" to the @Columnannotation.

@Entity
@Table(name = "my_alarms_timeline", indexes = {...})
public class MyAlarm {
    ...
    @Column(name = "validity_date", columnDefinition = "DATE")
    @NotNull
    private LocalDate validityDate;
}

Not sure why nobody else is seeing this issue...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...