Skip to content

Instantly share code, notes, and snippets.

@thjanssen
Last active July 30, 2019 10:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save thjanssen/ae6ae10564285b791dca to your computer and use it in GitHub Desktop.
Save thjanssen/ae6ae10564285b791dca to your computer and use it in GitHub Desktop.
@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate locDate) {
return locDate == null ? null : Date.valueOf(locDate);
}
@Override
public LocalDate convertToEntityAttribute(Date sqlDate) {
return sqlDate == null ? null : sqlDate.toLocalDate();
}
}
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
return sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime();
}
}
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column
private LocalDate date;
@Column
private LocalDateTime dateTime;
...
}
LocalDate date = LocalDate.of(2015, 8, 11);
TypedQuery<MyEntity> query = this.em.createQuery("SELECT e FROM MyEntity e WHERE date BETWEEN :start AND :end", MyEntity.class);
query.setParameter("start", date.minusDays(2));
query.setParameter("end", date.plusDays(7));
MyEntity e = query.getSingleResult();
@PeterWippermann
Copy link

Would be nice to have the import statements as well. Especially since Date is ambiguous.

@riteshmaurya
Copy link

this is not working on spring boot 1.4.1

@Bourgeoisvalere
Copy link

this is not working on spring boot 2.0.2

@KevinKons
Copy link

Would be nice to have the import statements as well. Especially since Date is ambiguous.

yeeahh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment