Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

java - Count number of days between 2 dates in JPA

I need to count the number of days between 2 dates in JPA.

For example :

CriteriaBuilder.construct(
  MyCustomBean.class
  myBean.get(MyBean_.beginDate), //Expression<Date>
  myBean.get(MyBean_.endDate), //Expression<Date>
  myDiffExpr(myBean) //How to write this expression from the 2 Expression<Date>?
);

So far, I tried :

1) CriteriaBuilder.diff(). but it does not compile because this method expects some N extends Number and the Date does not extend Number.

2) I tried to extend the PostgreSQL82Dialect (as my target database is PostgreSQL) :

public class MyDialect extends PostgreSQL82Dialect {

  public MyDialect() {
    super();
    registerFunction("datediff", 
    //In PostgreSQL, date2 - date1 returns the number of days between them.
    new SQLFunctionTemplate(StandardBasicTypes.LONG, " (?2 - ?1) "));
  }
}

This compiles and the request succeeds but the returned result is not consistent (78 days between today and tomorrow).

How would you do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like you are looking for a solution with JPQL to perform queries like SELECT p FROM Period p WHERE datediff(p.to, p.from) > 10.

I'm afraid there is no such functionality in JPQL so I recommend using native SQL. Your idea if extending Dialect with Hibernate's SQLFunctionTemplate was very clever. I'd rather change it to use DATE_PART('day', end - start) as this is the way to achieve days difference between dates with PostgreSQL.

You might also define your function in PostgreSQL and using it with criteria function().

'CREATE OR REPLACE FUNCTION "datediff"(TIMESTAMP,TIMESTAMP) RETURNS integer AS 'DATE_PART('day', $1 - $2);' LANGUAGE sql;'

cb.function("datediff", Integer.class, end, start);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...