Criteria 查询条件如果是子对象中的非主键字段会报 could not resolve property
1 private Criteria getCriteria(Favorite favorite) {
2 Criteria criteria = importDaoService.favoriteDao.getCriteria();
3 if (favorite.getStatus() != null) {
4 criteria.add(Restrictions.eq("status", favorite.getStatus()));
5 }
6 Product product = favorite.getProduct();
7 if (product != null && product.getProductName() != null && !product.getProductName().isEmpty()) {
8 // criteria.createAlias("product", "p");
9 criteria.add(Restrictions.like("product.id", product.getProductName(), MatchMode.ANYWHERE));
10 }
11 return criteria;
12 }
以上运行正常。
然而....
1 private Criteria getCriteria(Favorite favorite) {
2 Criteria criteria = importDaoService.favoriteDao.getCriteria();
3 if (favorite.getStatus() != null) {
4 criteria.add(Restrictions.eq("status", favorite.getStatus()));
5 }
6 Product product = favorite.getProduct();
7 if (product != null && product.getProductName() != null && !product.getProductName().isEmpty()) {
8 // criteria.createAlias("product", "p");
9 criteria.add(Restrictions.like("product.productName", product.getProductName(), MatchMode.ANYWHERE));
10 }
11 return criteria;
12 }
这么写就会报错。
最后... ,查了相关资料发现:
如果是非主键字段必须要给父对象的字段取别名。
private Criteria getCriteria(Favorite favorite) {
Criteria criteria = importDaoService.favoriteDao.getCriteria();
if (favorite.getStatus() != null) {
criteria.add(Restrictions.eq("status", favorite.getStatus()));
}
Product product = favorite.getProduct();
if (product != null && product.getProductName() != null && !product.getProductName().isEmpty()) {
criteria.createAlias("product", "p");
criteria.add(Restrictions.like("p.productName", product.getProductName(), MatchMode.ANYWHERE));
}
return criteria;
}
完美运行!
|