我建议使用Criteria Query来构建带有自定义WHERE
子句的语句。
根据您的示例,它可能如下所示(取决于您的数据类型):
public List<CapacityMonitor> getFlights(String carrierCode, String flightNumber, String departureAirport, String arrivalAirport) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<CapacityMonitor> query = builder.createQuery(CapacityMonitor.class);
Root<CapacityMonitor> root = query.from(CapacityMonitor.class);
query.select(root);
// Carrier code is mandatory
query.where(builder.equals(root.get("carrierCode"), carrierCode));
// Other properties are optional
if (null != flightNumber && flightNumber.length() > 0) {
query.where(builder.equals(root.get("flightNumber"), flightNumber));
}
// Use LIKE expression to match partially
if (null != departureAirport && departureAirport.length() > 0) {
query.where(builder.like(root.get("departureAirport"), "%" + departureAirport + "%"));
}
if (null != arrivalAirport && arrivalAirport.length() > 0) {
query.where(builder.like(root.get("arrivalAirport"), "%" + arrivalAirport + "%"));
}
return em.createQuery(query).getResultList();
}