我有幾個類,Student
和Address
。爲了獲得一對多的關係,假設一個學生可以有很多地址。我爲這個結構創建了.hbm文件,但我想爲一個學生懶惰地加載地址。但它總是加載學生對象中的地址。我可以看到一些疑問被解僱了。就像從學生表和地址表中獲取信息一樣。Hibernate的一個一對多延遲加載與HBM
lazy=true
或lazy=false
沒有任何影響,2個查詢始終點火(學生和地址)。
Student.hbm:
<?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>
<class name="hibernate.s4.Student" table="STUDENT">
<id name="studentId" column="stdid">
<generator class="increment" />
</id>
<property name="studentName" column="stdname" length="10"/>
<property name="phoneno" column="phno" length="10"/>
<property name="degree" column="degree" length="10"/>
<set name="addresses" cascade="save-update" lazy="false">
<key column="studentId"></key>
<one-to-many class="hibernate.s4.Address"/>
</set>
</class>
</hibernate-mapping>
Address.hbm:
<?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>
<class name="hibernate.s4.Address" table="ADDRESS">
<id name="addressid" column="addrid">
<generator class="increment" />
</id>
<property name="location" column="location" length="10"/>
<property name="area" column="area" length="10"/>
<property name="pin" column="pin" length="6"/>
</class>
</hibernate-mapping>
客戶端類來保存數據,並獲取學生對象:
Transaction tx = session.beginTransaction();
Student std1 = new Student();
std1.setStudentName("balaji");
std1.setDegree("MCA");
std1.setPhoneno("XXX777CXCC");
session.save(std1);
Address adr1 = new Address();
adr1.setArea("chirala");
adr1.setLocation("AP");
adr1.setPin(523155);
adr1.setStudent(std1);
Address adr3 = new Address();
adr3.setArea("pune");
adr3.setLocation("MH");
adr3.setPin(411028);
adr3.setStudent(std1);
std1.getAddresses().add(adr1);
std1.getAddresses().add(adr3);
System.out.println("Object saved successfully.....!!");
tx.commit();
Query query = session.createQuery("from Student where studentId = :studentId");
query.setParameter("studentId", 1);
List list = query.list();
Student student = (Student)list.get(0);
System.out.println((student.getAddresses() != null ? student.getAddresses().size() : 0));
'student.getAddresses()'不會爲空,因爲即使對於未獲取的集合,Hibernate也使用代理對象。 – Durandal