如果是一对多,多对一,甚至是多对多那效率就差别大了!!如果一对多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=?