0

我有超类 Person 和两个子类 - Parent 和 Child。它们使用 JOINED_TABLE 继承类型进行映射。

Parent 和 Child 具有双向的一对多关系。

Person.hbm.xml 包含所有配置:

<hibernate-mapping>
    <class name="com.masterhibernate.SimpleHibernateDemo.Person"
        table="Person">
        <cache usage="read-write" />

        <id name="id" column="id">
            <generator class="assigned" />
        </id>

        <property name="name">
            <column name="name" length="16" not-null="true" />
        </property>
        <property name="surname">
            <column name="surname" length="36"></column>
        </property>
        <property name="address">
            <column name="address" length="22"></column>
        </property>
        <joined-subclass name="com.masterhibernate.SimpleHibernateDemo.Parent"
            table="Parent">
            <key column="person_id" foreign-key="parent_person" />
            <property name="job" column="WorkPlace" length="22" type="string" />
            <set name="children" inverse="true" cascade="save-update" lazy="true">
                <cache usage="read-write" />
                <!-- specifies foreign key column of child table -->
                <key column="ParentPK" />
                <one-to-many class="com.masterhibernate.SimpleHibernateDemo.Child" />
            </set>
        </joined-subclass>
        <joined-subclass name="com.masterhibernate.SimpleHibernateDemo.Child"
            table="Child">
            <key column="person_id" foreign-key="child_person" />
            <property name="toy" column="toy" length="55" type="string" />
            <many-to-one name="parent"
                class="com.masterhibernate.SimpleHibernateDemo.Parent" column="ParentPK"
                foreign-key="child_parent" />
        </joined-subclass>
    </class>
</hibernate-mapping>

当我坚持 Parent 和关联的 Child 实体休眠时,在插入之前会发出 select 语句。这些选择语句从子表和人员表中查询子实体的数据。

每次运行时都会重新创建数据库,并且没有可供选择的内容。

以下是保留 Parent 和关联的 Child 实体的 main 方法的摘录:

Parent parent = new Parent("Volodia", "Levytskyi", "Mykolaiv");
        parent.setId((long) 1);
        Set<Child> children = new HashSet<>();
        children.add(new Child((long) 2, "Ivan", "McGregor", "Odessa"));
        children.add(new Child((long) 3, "Borys", "McRobin", "Donetsk"));
        children.add(new Child((long) 4, "Nazar", "McCrespo", "Teernopil"));
        parent.setChildren(children);

        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

        session.save(parent);
        // Criteria criteria = session.createCriteria(Person.class);
        // List<Person> list = criteria.list();
        // System.out.println("list1=" + list);
        transaction.commit();
        session.close();

为什么那些 select 语句在 insert 语句之前?

4

1 回答 1

0

问题出在父子实体的 id 生成器策略中:

<generator class="assigned" />

Hibernate 无法确定具有分配 id 的实体是否存在于数据库中。这就是为什么它发出选择语句以确保没有插入重复的 id。在我转向 id 生成器策略后native,它在插入之前停止选择:

<generator class="native" />
于 2014-06-11T05:42:29.847 回答