有人说Query更强大,但我人个比较喜欢用criteria,觉得使用criteria才符合Java开发的规范。
但criteria在使用example进行关联的对象查询时,会得到非预期的结果。
举个例子:
两个简单实体类Department:(部门)
以及另一个类Employee:(员工)
这两个表的关联关系我就不多说了,这行都应该都懂,呵呵。。。
此时,我需要通过一些特定的条件去查找employee,当然分页什么的就不说了,因为查询条件会根据客户需求不同而不同,所以直接使用Example进行操作
[code=java]
Criteria criteria = getSession().createCriteria(Employee.class);
if (empoyee != null) {
criteria.add(Example.create(empoyee ));//这里会忽略关联
}
//.....中间是分页等处理
List<?> result = criteria.list();
[/code]
注意上面的注释,Example进行查询是会忽略所有的null值以及关联的对象,故,如果我想根据empoyee 的department来查询empoyee 的话,就会将所有的empoyee 都查询出来,因为department被忽略了。
遇到这个问题有两种解决方法:
一、我的做法如下:
[code=java]
Criteria criteria = getSession().createCriteria(Employee.class);
if (empoyee != null) {
criteria.add(Example.create(empoyee ));//这里会忽略关联
//加强后的Example查寻,不再忽略关联对象
criteria.createCriteria("dpartment").add(Restrictions.eq("id",empoyee .getDepartment.getId()));
}
//.....中间是分页等处理
List<?> result = criteria.list();
[/code]
二、下面是我在网上看到别人的做法,个人感觉有点麻烦:
(转)那么这个问题怎么解决呢,查看了Example类的源码后,我决定动手修改——当然不能直接去改它的源码,在参考了hibernate官方论坛后,新建了类:
[code=java]
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.hibernate.engine.TypedValue;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.AbstractComponentType;
import org.hibernate.type.Type;
import org.hibernate.util.StringHelper;
/**
* A copy of Hibernate's Example class, with modifications that allow you to
* include many-to-one and one-to-one associations in Query By Example (QBE)
* queries.
* association class </a>
*/
public class Assoc