How to perform date operations in hibernate

前端 未结 8 1076
既然无缘
既然无缘 2020-12-10 03:00

I want to perform data time operations using hibernate HQL.

I want to add and subtract two dates as well as I want to subtract 1 year or 1 month from a particular da

8条回答
  •  情深已故
    2020-12-10 03:48

    Usage sample of approach with dialect for JPA + Hibernate 4.3.1 + MySQL 5

    public class SampleMySQL5InnoDBDialect extends org.hibernate.dialect.MySQL5InnoDBDialect {

    public SampleMySQL5InnoDBDialect() {
        super();
        registerFunction("date_sub_days", new SQLFunctionTemplate(StandardBasicTypes.DATE, "date_sub(?1, interval ?2 day)"));
    }
    

    then for your class with mapping annotation:

    @NamedQuery(name = "SampleEntity.getSampleEntitiesForGapOverlapCalculations", query = "from SampleEntity as se where "
        + "((se.toDate between :startDate and :endDate) or (date_sub_days(se.toDate, se.duration) between :startDate and :endDate)) order by se.toDate asc, se.duration desc")
    

    SampleEntity has toDate field of type java.sql.Date and duration integer field (duration in days) and we are calculating fromDate = toDate - duration and selecting all entities which have fromDate or toDate inside interval [startDate, endDate].

提交回复
热议问题