Criteria 查询条件如果是子对象中的非主键字段会报 could not resolve property
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("product.id", product.getProductName(), MatchMode.ANYWHERE));
}
return criteria;
}
以上运行正常。
然而....
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("product.productName", product.getProductName(), MatchMode.ANYWHERE));
}
return criteria;
}
这么写就会报错。
最后... ,查了相关资料发现:
如果是非主键字段必须要给父对象的字段取别名。
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;
}
完美运行!