Hibernate discriminator force ='true'不适用于更新查询

时间:2015-03-18 07:25:26

标签: java hibernate

我使用了discriminator force = 'true',但它不适用于更新查询。 对于在SELECT条件中使用DiscriminatorColumn的{​​{1}}查询,这种方式可以正常工作,但同样的事情不适用于更新查询。

让我用示例解释一下这个场景:

WHERE

员工表:

class Employee {
    private int id;
    private Department department;

    //other fields and setters/getters

}
class RegularEmployee extends Employee {

    //other fields and setters/getters
}
class ContractEmployee extends Employee {

    //other fields and setters/getters
}

class Department {
    private Set<RegularEmployee> regularEmployees = new HashSet<RegularEmployee>();
    private Set<ContractEmployee> contractEmployees = new HashSet<ContractEmployee>();

    //other fields and setters/getters
}

<hibernate-mapping>  
<class name="Employee" table="employee" discriminator-value="Employee">  
    <id name="id">  
        <generator class="increment"></generator>  
    </id>  

    <discriminator column="class" type="string" force="true" />
    <many-to-one name="department" column="department_id" lazy="false" class="Department" />

    <subclass name="RegularEmployee" discriminator-value="RegularEmployee">  
    </subclass>  

    <subclass name="ContractEmployee" discriminator-value="ContractEmployee">  
    </subclass>  
</class>  
</hibernate-mapping>  


<hibernate-mapping>  
<class name="Department" table="department">  
    <id name="id">  
        <generator class="increment"></generator>  
    </id>  

    <set name="regularEmployees" cascade="all-delete-orphan">
            <key column="department_id" />
            <one-to-many class="RegularEmployee" />
        </set>

        <set name="contractEmployees" cascade="all-delete-orphan">
            <key column="department_id" />
            <one-to-many class="ContractEmployee" />
        </set>
</class>  
</hibernate-mapping>

假设我说我正在加载一个id为1的部门对象,该对象有2名常规员工和2名合同员工。但是,当我删除所有合同员工并更新部门对象时:

id      department_id   class
---------------------------------------
1       1               RegularEmployee
2       1               RegularEmployee
3       1               ContractEmployee
4       1               ContractEmployee

在这种情况下,hibernate更新查询不在条件:

中添加descriminator值
Department department = session.load(Department.class, new Long(1L));
department.getContractEmployees.clear();
session.update(department);

将NULL值设置为常规员工记录以及合同员工记录,这不是预期的行为。以后的合同员工记录将通过以下hibernate查询删除。

UPDATE employee SET department_id = NULL WHERE department_id = ?

更新了员工表:

DELETE FROM employee WHERE id = ?

在这里,普通员工记录成为孤儿,因为在更新查询条件的地方缺少判别列。

有没有解决办法来实现这个目标?

0 个答案:

没有答案