QueryDSL日期算术

时间:2016-01-26 18:40:44

标签: java jpa querydsl

我有一张这样的表:

CREATE  TABLE IF NOT EXISTS `sma`.`MIGRation` (
`MIGR_ID` BIGINT NOT NULL AUTO_INCREMENT ,
`MIGR_From` VARCHAR(1024) NOT NULL ,
`MIGR_To` VARCHAR(1024) NOT NULL ,
`MIGR_Validity_Days` INT NOT NULL ,
`MIGR_CreationDate` DATETIME NOT NULL ,
PRIMARY KEY (`MIGR_ID`) );

如何在QueryDSL中编写表达式以查找仍然有效的条目(creationDate + validity_Days)?

SELECT * FROM MIGRation WHERE DATE_ADD(MIGR_CreationDate, INTERVAL MIGR_Validity_Days DAY) > now()

1 个答案:

答案 0 :(得分:5)

对于算术查询,请查看com.querydsl.core.types.dsl.Expressions类。在这种情况下,可以使用Expressions::dateTimeOperation

import com.querydsl.core.types.Ops;
import com.querydsl.core.types.dsl.*;
import com.querydsl.sql.SQLQuery;
...
    @Transactional
    public List<MIGRationEntity> getMigration() {
        SQLQuery<MIGRationEntity> query = selectFrom(QMIGRation.MIGRation)
            .where(
                Expressions.dateTimeOperation(
                    Date.class, Ops.DateTimeOps.ADD_DAYS,
                    QMIGRation.MIGRation.mIGRCreationDate,
                    QMIGRation.MIGRation.mIGRValidityDays)
                .gt(DateTimeExpression.currentTimestamp()));
        String sql = query.getSQL().getSQL();
        System.out.print(sql);
        return query.fetch();
    }
...

创建的SQL:

select MIGRation.MIGR_CreationDate, MIGRation.MIGR_From, MIGRation.MIGR_ID, MIGRation.MIGR_To, MIGRation.MIGR_Validity_Days
from MIGRation MIGRation
where date_add(MIGRation.MIGR_CreationDate, interval MIGRation.MIGR_Validity_Days day) > current_timestamp