Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Date Time api in JPA

What is the best way how to integrate Java 8 Date Time api in jpa?

I have added converters:

@Converter(autoApply = true)
public class LocalDatePersistenceConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate localDate) {
        return Date.valueOf(localDate);
    }

    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return date.toLocalDate();
    }
}

and

@Converter(autoApply = true)
public class LocalDateTimePersistenceConverter implements AttributeConverter<LocalDateTime, Timestamp> {
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime entityValue) {
        return Timestamp.valueOf(entityValue);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp databaseValue) {
        return databaseValue.toLocalDateTime();
    }
}

Everything seems fine, but how should I use JPQL for querying? I am using Spring JPARepository, and goal is to select all entities where date is the same as date given, only difference is that it is saved in entity as LocalDateTime.

So:

public class Entity  {

    private LocalDateTime dateTime;

    ...
}

And:

@Query("select case when (count(e) > 0) then true else false end from Entity e where e.dateTime = :date")
public boolean check(@Param("date") LocalDate date);

When executing it just gives me exception, which is correct.

Caused by: java.lang.IllegalArgumentException: Parameter value [2014-01-01] did not match expected type [java.time.LocalDateTime (n/a)]

I have tried many ways, but it seems that none is working, is that even possible?

like image 997
sandris Avatar asked Sep 14 '14 15:09

sandris


1 Answers

Hibernate has an extension library, hibernate-java8 I believe, which natively supports many of the time types.

You should use it before writing converters.

in hibernate 5.2 you won't need this additional library, it is part of core.

like image 50
xenoterracide Avatar answered Oct 01 '22 21:10

xenoterracide