Search code examples
mysqlquerydsl

How to use mysql now() function in querydsl?


Lets say I have a mySQL table artifact as follows:

artifact_id varchar(50)
locked_status char(1)
valid_till datetime

 Select artifact_id from artifact where locked_status='Y'

For the above query, I have the querydsl representation as:

SQLTemplates templates = new MySQLTemplates();
Configuration configuration = new Configuration(templates);
QArtifact artifact = new QArtifact("a");
SQLQuery<?> query = new SQLQuery<Void>(con, templates);
List<String> artifactIds = query.select(artifact.artifact_id)
            .from(artifact)
            .where(artifact.locked_status.eq("Y"))
            .fetch();

How can I represent the below query in querydsl?

Select artifact_id from artifact where locked_status='Y' and valid_till > now()

Solution

  • The simplest way is to add

    .and(artifact.valid_till.after(new Date()))
    

    But if you are picky about the NOW function to be called on the server you might go with this:

    .and(artifact.valid_till.after(Expressions.currentTimestamp()))
    

    You can browse the code to see how the DateTimeExpression returned by this helper is generated.