简单的HIbernate数据检索

时间:2016-05-03 19:38:55

标签: hibernate

我有一个表格如下

  • 整数ID(PK)
  • 字符串名称

地址

  • 整数addrs_Id(PK)
  • 整数person_Id(FK) - onetomany映射到人
  • 字符串地址

Hibernate Mapping:

<hibernate-mapping>
    <class name="com.mypackage.Person" table="PERSON">
        <id name="id">
            <column name="ID"/>
            <generator class="increment"></generator>
        </id>

        <property name="name"></property>
        <bag name="address" table="ADDRESS" inverse="true" lazy="false" fetch="select" cascade="all">
            <key>
                <column name="PERSON_ID" not-null="false"/>
            </key>
            <one-to-many class="Address"/>
        </bag>

    </class>


    <class name="Address" table="ADDRESS">
        <id name="id">
            <column name="ADD_ID"/>
            <generator class="increment"></generator>
        </id>
        <property name="type" type="string" not-null="true" column="TYPE" length="1"/>
        <many-to-one name="person" class="Person" lazy="false" fetch="select">
            <column name="PERSON_ID" not-null="true"/>
        </many-to-one>
    </class>

</hibernate-mapping>

的POJO:

public class Person {

private int id;
private String name;
private List<Address> addresses;
....
// getters and setters defined
}

public class Address {

private int add_id;
private int person;
private String address;
....
// getters and setters defined
}

我需要检索2种不同内容的数据

  • 当从DB中检索Person时,应该预先填充地址 - 这适用于上面完成的映射
  • 检索没有加载地址的人,但想分别加载地址并附加到人(没有延迟加载)。如何通过简单的Hibernate映射实现这一目标?

1 个答案:

答案 0 :(得分:0)

尝试以下代码 -

Person p = sess.createCriteria(Person.class, id);
Hibernate.initialize(p.getAddresses());

refernce