我对hibernate很新,我正在尝试在PersonDAO中设置一个新方法。
我的hibernate映射文件如下所示:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.foo.bar.domain">
<class name="Person" table="person">
<meta attribute="class-description">A Person</meta>
<id name="id" type="java.lang.Long" column="rid" unsaved-value="null">
<generator class="native" />
</id>
<version name="version" type="integer" column="rversion" unsaved-value="null" />
<property name="UID" type="string" column="UID" length="16" not-null="true" unique="true"/>
<property name="lastName" type="string" column="last_name" not-null="true" />
<property name="firstName" type="string" column="first_name" not-null="true" />
<property name="ownDepartment" type="string" column="own_department"/>
<!-- a person has many responsibilities and a responsibility can can assigned to many person -->
<set name="responsibilities" table="person_responsibility">
<key column="person_id"/>
<many-to-many column="responsibility_id" class="Responsibility"/>
</set>
<set name="additionalDepartments" table="PERSON_TO_ADDL_DEPARTMENT">
<key column="person_id"/>
<element column="ADDITIONAL_DEPARTMENT" type="string"/>
</set>
</class>
我在java中编写了一个这样的方法来获取给定部门的所有管理器:
public List<Person> getManagerByDepartment(final String givenDepartment){
List<Person> l = (List<Person>) this.getHibernateTemplate().executeFind(new HibernateCallback<List<Person>>() {
public List<Person> doInHibernate(Session session) throws HibernateException, SQLException {
String query = "select p from Person p join p.responsibilities responsibilities join p.additionalDepartments additionalDepartments where responsibilities.name = 'manager' and (p.ownDepartment = :givenDepartment or additionalDepartments = :givenDepartment)";
List<Person> result = (List<Person>) session.createQuery(query).setString("givenDepartment", givenDepartment).list();
return result;
}
});
return l;
}
现在我在SQL中进行手动查询,我可以看到,对于给定的部门,肯定不止一个人有额外的责任'经理'...为什么我的方法只返回一个人,而不是全部?
我强烈怀疑我的方法,特别是我的查询,而不是映射,是问题,但我看不出它有什么问题......
我已经跳到了这里的深处,所以任何帮助都会非常感激。
编辑:注意,我正在处理数百条记录,而不是数百万条记录,这不是一个瓶颈操作,所以我不太担心性能...如果我正在做的话一些毫无意义的浪费,指出来
答案 0 :(得分:1)
如果没有示例数据,很难确定,但是当您在HQL中执行join
时,它会在SQL中转换为inner join
。因此,如果您知道应该有多个具有给定责任的结果,则问题可能是join p.additionalDepartments
。
对于其他部门,请使用left join
尝试此查询并查看其是否有效
String query = "select p from Person p join p.responsibilities responsibilities left join p.additionalDepartments additionalDepartments where responsibilities.name = 'manager' and (p.ownDepartment = :givenDepartment or additionalDepartments = :givenDepartment)";
答案 1 :(得分:1)
您可以通过启用showsql选项打印hibernate查询并检查创建的查询,然后针对数据库对其进行测试。