我正在学习 Jpa 标准查询,但不知道如何实现:
我有一个名为 Restaurant 的实体:
@Entity
@Table(name = "t_f2g_restaurant",
uniqueConstraints = @UniqueConstraint(columnNames = { "NAME" }))
public class Restaurant {
@EmbeddedId
@AttributeOverrides(
{ @AttributeOverride(name = "value", column = @Column(name = "ID")) })
private RestaurantIdentity id;
@Column(name = "name")
private String name;
@ElementCollection
@CollectionTable(name = "t_f2g_restaurant_srv_area",
joinColumns = @JoinColumn(name = "RESTAURANT_ID"))
@Column(name = "zip_code")
private List<String> serviceAreas = new ArrayList<String>();
}
现在我想统计按 serviceAreas 过滤的餐馆,下面是我的原生 sql 实现:
private boolean delegateToNativeQuery(Address deliveryAddress {
String sqlString = "select count(*) from t_f2g_restaurant r "
+ "where exists (select * from t_f2g_restaurant_srv_area sa "
+ "where sa.zip_code = ? and r.id = sa.restaurant_id) ";
Query query = entityManager.createNativeQuery(sqlString);
query.setParameter(1, deliveryAddress.getZipCode());
return ((Number) query.getSingleResult()).longValue() > 0;
}
但是如何使用标准查询来实现它?
以下是我的尝试:
private boolean delegateToCriteriaQuery(Address deliveryAddress) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
Root<Restaurant> restaurant = query.from(Restaurant.class);
Subquery<Long> serviceAreaSubquery = query.subquery(Long.class);
/* This causes an extra t_f2g_restaurant, t_f2g_restaurant_srv_area join
Root<Restaurant> serviceAreaRoot = serviceAreaSubquery
.from(Restaurant.class);
ListJoin<Restaurant, String> serviceAreas = serviceAreaRoot
.joinList("serviceAreas");
serviceAreaSubquery.select(criteriaBuilder.count(serviceAreaRoot))
.where(criteriaBuilder.
//serviceArea is represented by String, so what's the attribute name?
equal(serviceAreas.get("serviceArea"), deliveryAddress.getZipcode()));
query.select(criteriaBuilder.count(restaurant)).
where(criteriaBuilder.exists(serviceAreaSubquery));
return entityManager.createQuery(query).getSingleResult() > 0;
}