我的数据结构是这样的
Department
-> Employees
-> Gender
-> CityID -> Cities
->CityID
->CountryID -> Countries
-> CountryID
部门类:
public class Department {
@OneToMany(mappedBy = "departmentid", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Employee> employees = new HashSet<>();
}
我这样构建 Crteria:
DetachedCriteria criteria = DetachedCriteria.forClass(Department.class);
DetachedCriteria detlCrit = criteria.createCriteria("employees");
detlCrit.add(Restrictions.eq("gender", "MALE"));
detlCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
表中有 1 个部门和 2 名员工(1 名男性,1 名女性)。 当我执行此标准时,我期望 Hibernate 构建一个“部门” 对象、一个“员工”对象以及城市、国家/地区等,
但我得到的是 1 个部门,2 个员工。
当我在日志中看到 Hibernate 执行的查询时,它显示了两个查询
第一个查询:
Select * from Department, Employee
Left outer join City on Employee.cityID = City.cityID
Left outer join Country on City.countryID = City.countryID
Where Employee.DeptID = Department.DeptID
AND Employee.Gender = 'MALE';
第二个查询:
Select * from Employee
Left outer join City on Employee.cityID = City.cityID
Left outer join Country on City.countryID = City.countryID
Where Employee.DeptID = Department.DeptID;
第二个查询错误,没有对 Gender='MALE' 应用限制;
我做错了什么?有什么建议么?如何解决这个问题?
抱歉,查询可能不完全正确,但您明白了。 需要更多详细信息,请询问,我可以提供。
提前致谢..
最佳答案
试试这个,使用 SessionFactory。
@Autowired
private SessionFactory sessionFactory;
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Department.class);
criteria.add(Restrictions.eq("gender", "MALE"));
希望我有用。
关于java - Hibernate DetachedQuery 和 Spring 的 HibernateTemplate with Restriction 给出了错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29023994/