1. 程式人生 > >one-to-many的懶載入及原理分析

one-to-many的懶載入及原理分析

如果是一對多,多對一,甚至是多對多那效率就差別大了!!如果一對多lazy=”false”或者fetch=”join”會同時查詢出所有關聯的物件,對資料庫和對網路影響將是很大地。(lazy=”false” 採用多條查詢語句,比如,一對100:會有可能101條select查詢語句;fetch=”join” 會同時訪問兩個表的)

但是代理物件呼叫getClass()和getId()方法的時候不會立刻載入,.class和id的資訊是隨物件的!


domain物件
public class User {

private Integer id;
private String name;
private Float wage;
private Set<Book> bookSet = new HashSet<Book>();


public class Book {

private Integer id;
private String bookname;
private User user;


對映檔案

<?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="cn.itcast.hibernate.lazyOneToOne">

<class name="User" table="user" lazy="false">
<id name="id" unsaved-value="-1">
<generator class="native" />
</id>
<property name="name" />
<property name="wage"/>
<set name="bookSet" lazy="false" fetch="select">
<key column="u_id"/>
<one-to-many class="Book"/>
</set>

</class>
</hibernate-mapping>


<?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="cn.itcast.hibernate.lazyOneToOne">

<class name="Book" table="book">
<id name="id" unsaved-value="-1">
<generator class="native" />
</id>
<property name="bookname" />

<many-to-one name="user" column="u_id"/>

</class>
</hibernate-mapping>



測試程式碼:

User user = (User)session.get(User.class, 1);


此時的sql語句為:
Hibernate: 
select
user0_.id as id0_0_,
user0_.name as name0_0_,
user0_.wage as wage0_0_
from
user user0_
where
user0_.id=?
Hibernate:
select
bookset0_.u_id as u3_1_,
bookset0_.id as id1_,
bookset0_.id as id1_0_,
bookset0_.bookname as bookname1_0_,
bookset0_.u_id as u3_1_0_
from
book bookset0_
where
bookset0_.u_id=?


如果對映檔案改為:

<set name="bookSet"  lazy="false" fetch="join">
<key column="u_id"/>
<one-to-many class="Book"/>
</set>


sql語句為:

Hibernate: 
select
user0_.id as id0_1_,
user0_.name as name0_1_,
user0_.wage as wage0_1_,
bookset1_.u_id as u3_3_,
bookset1_.id as id3_,
bookset1_.id as id1_0_,
bookset1_.bookname as bookname1_0_,
bookset1_.u_id as u3_1_0_
from
user user0_
left outer join
book bookset1_
on user0_.id=bookset1_.u_id
where
user0_.id=?


如果對映檔案為:

		<set name="bookSet"  lazy="true">
<key column="u_id"/>
<one-to-many class="Book"/>
</set>



只是訪問一個表了:
Hibernate: 
select
user0_.id as id0_0_,
user0_.name as name0_0_,
user0_.wage as wage0_0_
from
user user0_
where
user0_.id=?