The use of java sprintboot JAP criteriabuilder (and or)

134 Views Asked by At

I have a question about CriteriaBuilder API. I am new in JPA, I would like to creates (and or)combination。

predicates.add(cb.equal(root.get("title"),title));
predicates.add( 
            cb.or(cb.between(root.get("startedAt"),startTime,endTime),
                  cb.between(root.get("endedAt"),startTime,endTime),
                  cb.and(
                        cb.greaterThanOrEqualTo(root.get("endedAt").as(Date.class),endTime),
                        cb.lessThanOrEqualTo(root.get("startedAt").as(Date.class),startTime))
                    ));

output results

where title = ? and (started_at between ? and ? or started_at between ? and ?  or
 ended_at>=? and started_at <=?)

What I want is a result

where title = ? and (started_at between ? and ? or started_at between ? and ?  or
 (ended_at>=? and started_at <=?)
)

How can one achive this using CriteriaBuilder? Thank you for your advice!!!

1

There are 1 best solutions below

2
On

Have you tried this?

predicates.add(cb.and(cb.equal(root.get("title"),title),
                      cb.or(cb.or(cb.between(root.get("startedAt"),startTime,endTime),
                                  cb.between(root.get("endedAt"),startTime,endTime)),
                            cb.and(cb.greaterThanOrEqualTo(root.get("endedAt").as(Date.class),endTime),
                                   cb.lessThanOrEqualTo(root.get("startedAt").as(Date.class),startTime)))
                      ));