0

How can I use Date library for my POJO?

I can use this my code:

@Data
@Entity
@Table(name = "PERSON")
public class Person implements Serializable {

    private static final long serialVersionUID = -8041031461422721556L;

    @Id
    @Column(name = "PERSON_ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "DOB")
    private LocalDate dob;

}

I'm using java.time.LocalDate type.

Paco
  • 43
  • 3
  • 1
    errm, its part of JPA 2.2. Doesnt your provider support JPA 2.2 yet? –  Oct 10 '17 at 17:00
  • For Hibernate, see [second answer](https://stackoverflow.com/a/33001846/5221149) of duplicate link. – Andreas Oct 10 '17 at 17:19

1 Answers1

1

Right now Hibernate/JPA doesn't have a compatibility with Java 8 Date library, but you only need make a AttributeConverter to use this library:

For type TIMESTAMP you can use this converter:

@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime datetime) {
        return datetime == null ? null : Timestamp.valueOf(datetime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
        return timestamp == null ? null : timestamp.toLocalDateTime();
    }

}

For type DATE you can use this converter:

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

    @Override
    public Date convertToDatabaseColumn(LocalDate date) {
        return date == null ? null : Date.valueOf(date);
    }

    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return date == null ? null : date.toLocalDate();
    }

}

For type TIME you can use this converter:

@Converter(autoApply = true)
public class LocalTimeAttributeConverter implements AttributeConverter<LocalTime, Time> {

    @Override
    public Time convertToDatabaseColumn(LocalTime time) {
        return time == null ? null : Time.valueOf(time);
    }

    @Override
    public LocalTime convertToEntityAttribute(Time time) {
        return time == null ? null : time.toLocalTime();
    }

}
Paco
  • 43
  • 3