I am making a search module that will be able to filter data according to some criteria.
I already made the following:
public class SearchModuleBean implements Serializable{
@PersistenceContext
EntityManager entityManager;
private Date departureDate;
private Date returnDate;
public List<Flight> search(){
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Flight> criteriaQuery = cb.createQuery(Flight.class);
Root<Flight> c = criteriaQuery.from(Flight.class);
criteriaQuery.select(c).where(getPredicates(cb, c).toArray(new Predicate[0]));
TypedQuery<Flight> query = entityManager.createQuery(criteriaQuery);
System.out.println(query.getResultList());
return query.getResultList();
}
private List<Predicate> getPredicates(CriteriaBuilder cb, Root<Flight> c) {
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(c.get(Flight_.departureDate), departureDate));
return predicates;
}
}
Getters/Setters/Annotations and imports are not displayed here.
I have a JSF page which fills in the departure- and arrivalDates. In the getPredicates method I then check for the departureDate if it is equal to Dates in our database. The issue is that they have a different format so he never finds anything.
答案 0 :(得分:0)
我不倾向于使用Criteria API,并且可能有另一种方法,但是您可以按以下方式使用between运算符:
private List<Predicate> getPredicates(CriteriaBuilder cb, Root<Flight> c,
Date departureDate) {
List<Predicate> predicates = new ArrayList<>();
//remove time portion from specified date: now dd/mm/yy 00:00
Date startDate = DateUtils.truncate(departureDate, Calendar.DATE);
//new date with time initialized to 23:59:59
Date endDate = DateUtils.addSeconds(DateUtils.addDays(startDate, 1), - 1);
predicates.add(cb.between(c.get(Flight_.departureDate), startDate, endDate));
return predicates;
}
DateUtils是Commons Lang中的一类:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>