0

I have a doubt in JPA query criteria builder with path or expression.

I want to find who are all entered first post comment with in an hour after their  account created

Path<Date> accountCreatedTime = root.<Date> get("AccountCreatedTime");
Path<Date> firstPostCreatedTime = root.<Date> get("FirstPostCreatedTime");

final Predicate timeInHourPredicate = criteriaBuilder
    .greaterThanOrEqualTo(accountCreatedTime, FirstPostCreatedTime);

Example:

  1. Account Created at: 2018-SEP-10 at 10am and First Post entered 2018-SEP-10 at 10.15 am  this recond should be fetched. (FALLS IN AN HOUR)

  2. Account Created at: 2018-SEP-10 at 10am and First Post entered 2018-SEP-10 at 3.50 pm  this SHOULD NOT  be fetched.

Is there any  way to add or separate hours from Path accountCreatedTime? or can we get difference between   Path accountCreatedTime  and Path FirstPostCreatedTime  in hours and in criteriaBuilder

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Ram
  • 37
  • 4

1 Answers1

0

Using DATEDIFF

The SQL would be like this:

select u
from users u
join posts p on p.user_id = u.id
where datediff('hour', u.account_created_time, p.first_post_created_time)

For more details about how you can register the DATEDIFF function with Criteria API, check out this article.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • Path accountCreatedTime = root. get("AccountCreatedTime"); Path FirstPostCreatedTime = root. get("FirstPostCreatedTime"), we are using path due to various other conditions and using criteria builder – Ram Jan 20 '19 at 14:12
  • Just translate the SQL query to Criteria API and it should work. If you want to do it with `greaterThanOrEqualTo`, you need to queries, and that's less efficient. – Vlad Mihalcea Jan 20 '19 at 14:14
  • Path accountCreatedTime = root. get("AccountCreatedTime"); Path FirstPostCreatedTime = root. get("FirstPostCreatedTime"), we are using path due to various other conditions and using criteria builder. Pls assume first post created time and account created time columns are in the same.table. – Ram Jan 20 '19 at 14:26
  • Yes, I tried, like this. MS Sql Server ' String functionName="Datediff" Predicate predicate=cb.greaterThan(builder.function(functionName,Integer.class,builder.literal("MINUTE"),PostEnteredDateTM, accountCreatedTM), 60 );' Error is : Invalid parameter 1 specified for datediff. – Ram Jan 21 '19 at 19:02