hibernate加载策略之lazy

本文介绍了Hibernate的加载策略,包括即时加载与懒加载(lazy)。懒加载在提高效率的同时,可能导致LazyInitializationException异常。详细讨论了class、set/list、单端关联(many-to-one, one-to-one)以及property上的懒加载配置和行为,并通过项目案例进行解析。" 77916825,1429545,Ubuntu环境下配置Hadoop 2.7.3伪分布式教程,"['Hadoop', 'Ubuntu', '分布式系统', 'Linux系统管理', 'Java开发']
摘要由CSDN通过智能技术生成

一、hibernate的加载策略有两种:

1)即时加载--get加载数据

使用get获取数据,会立即查询,先到缓存中查找,找不到再到数据库中查找。

2)延迟加载(懒加载lazy)--load加载

不会立即查找,当需要的时候才会查找。

容易造成LazyInitializationException异常。如果出现这个异常,大部分是因为session被关闭了,还要从session中获取数据造成的。

但是懒加载也是有优势的,那就是效率高。因为我们查数据时不一定要把所有数据都查询出来。

注:load支持延迟加载,get不支持延迟加载。如果没有设置延迟加载,那么load也会立即加载对象。


二、class的lazy

class默认情况下是支持懒加载的(在*.hbm.xml中的class中有一个属性lazy="true"),所以在load方法时,是懒加载,但是当我们给成lazy="false"时,就不支持懒加载了,这里即使使用load方法,也会是即时加载。


我们来看项目案例:


Book实体类

public class Book {
	private int id;
	private String name;
	private double price;
	private String author;
	private Date pubDate;
	public Book() {
	}
	public Book(String name, double price) {
		super();
		this.name = name;
		this.price = price;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price
				+ ", author=" + author + ", pubDate=" + pubDate + "]";
	}
	//省略get/set
}

Book.hbm.xml配置文件

<hibernate-mapping package="com.test.pojo">  
    <class name="Book" table="book" lazy="false">  
        <id name="id">  
            <generator class="identity" />  
        </id>  
        <property name="author" />  
        <property name="name" column="book_name" />  
        <property name="price" />  
        <property name="pubDate" />  
    </class>  
</hibernate-mapping> 
HibernateUtil类

public class HibernateUtil {
	private static Configuration cfg=null;
	private static SessionFactory factory=null;
	private static Session session=null;
	static{
		cfg=new Configuration().configure();
		factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
		        .applySettings(cfg.getProperties()).build());
	}
	public static Session getSession(){
		if(factory!=null)
			return session=factory.openSession();
		factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
		        .applySettings(cfg.getProperties()).build());
		return session=factory.openSession();
	}
	public static void closeSession(){
		if(session!=null && session.isOpen())
			session.close();
	}
}
hibernate.cfg.xml配置文件

<hibernate-configuration>
	<session-factory>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="connection.url">
			jdbc:mysql:///hibernatetest
		</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<property name="hbm2ddl.auto">update</property>
		<mapping resource="com/test/pojo/Book.hbm.xml" />
	</session-factory>
</hibernate-configuration>
HibernateTest测试类

public class HibernateTest {
	@Test
	public void testCreateDB(){
		Configuration cfg=new Configuration().configure();
		SchemaExport se=new SchemaExport(cfg);
		se.create(true, true);
	}
	@Test
	public void testSave(){
		Session session=HibernateUtil.getSession();
		Transaction tx=session.beginTransaction();
		Book book=new Book();
		book.setName("读者");
		book.setPrice(21.5);
		book.setAuthor("读者出版传媒有限公司");
		book.setPubDate(new Date());
		Book book1=new Book();
		book1.setName("蓝血人");
		book1.setPrice(50);
		book1.setAuthor("卫斯理");
		book1.setPubDate(new Date());
		Book book2=new Book();
		book2.setName("傲慢与偏见");
		book2.setPrice(80);
		book2.setAuthor("简.奥斯丁");
		book2.setPubDate(new Date());
		Book book3=new Book();
		book3.setName("中国历史");
		book3.setPrice(21.5);
		book3.setAuthor("人民");
		book3.setPubDate(new Date());
		Book book4=new Book();
		book4.setName("七龙珠");
		book4.setPrice(21.5);
		book4.setAuthor("不知道");
		book4.setPubDate(new Date());
		Book book5=new Book();
		book5.setName("名侦探柯南");
		book5.setPrice(50);
		book5.setAuthor("宫崎骏");
		book5.setPubDate(new Date());
		
		
		session.save(book);
		session.save(book1);
		session.save(book2);
		session.save(book3);
		session.save(book4);
		session.save(book5);
		tx.commit();
		HibernateUtil.closeSession();
	}
	@Test
	public void testGet(){
		Session session=HibernateUtil.getSession();
		Transaction tx=session.beginTransaction();
		Book book=(Book) session.get(Book.class, 1);
		System.out.println("书名:"+book.getName());
		tx.commit();
		HibernateUtil.closeSession();
		System.out.println("书名:"+book.getName());
	}
	@Test
	public void testLoad(){
		Session session=HibernateUtil.getSession();
		Transaction tx=session.beginTransaction();
		Book book=(Book) session.load(Book.class, 1);
//		System.out.println("书名:"+book.getName());
		tx.commit();
		HibernateUtil.closeSession();
		//当Book.hbm.xml配置class中的lazy="true"时,以下操作会报错
		//open session in view
		System.out.println("书名:"+book.getName());
	}
}

===========================================================

三、现在我们再看另一种懒加载情况

项目结构如下:



Book实体类

public class Book {
	private int id;
	private String name;
	private double price;
	private String author;
	private Date pubDate;
	private Category category;
	public Book() {
	}
	public Book(String name, double price) {
		super();
		this.name = name;
		this.price = price;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price
				+ ", author=" + author + ", pubDate=" + pubDate + "]";
	}
	//省略get/set
}
Book.hbm.xml配置文件

<hibernate-mapping package="com.test.pojo">  
    <class name="Book" table="book">  
        <id name="id">  
            <generator class="identity" />  
        </id>  
        <many-to-one name="category" class="Category" column="category_id" 
           cascade="save-update"/>  
        <property name="author" />  
        <property name="name" column="book_name" />  
        <property name="price" />  
        <property name="pubDate" />  
    </class>  
</hibernate-mapping>

Category实体类

public class Category {
	private int id;
	private String name;
	private Set<Book> books=new HashSet<Book>();
	//省略get/set
}
Category.hbm.xml配置文件

<hibernate-mapping package="com.test.pojo">  
    <class name="Category" >  
        <id name="id" >  
            <generator class="identity" />  
        </id>  
        <property name="name" />  
        <set name="books" inverse="true" lazy="true">  
            <key>  
                <column name="category_id" />  
            </key>  
            <one-to-many class="Book" />  
        </set>  
    </class>  
  
</hibernate-mapping>

HibernateTest

public class HibernateTest {
	@Test
	public void testCreateDB(){
		Configuration cfg=new Configuration().configure();
		SchemaExport se=new SchemaExport(cfg);
		se.create(true, true);
	}
	@Test
	public void testSave(){
		Session session=HibernateUtil.getSession();
		Transaction tx=session.beginTransaction();
		Category category=new Category();
		category.setName("文学");
		Category category1=new Category();
		category1.setName("科幻");
		Category category2=new Category();
		category2.setName("历史");
		Category category3=new Category();
		category3.setName("言情");
		Category category4=new Category();
		category4.setName("漫画");
		Category category5=new Category();
		category5.setName("悬疑");
		Book book=new Book();
		book.setName("读者");
		book.setPrice(21.5);
		book.setAuthor("读者出版传媒有限公司");
		book.setPubDate(new Date());
		book.setCategory(category);
		Book book1=new Book();
		book1.setName("蓝血人");
		book1.setPrice(50);
		book1.setAuthor("卫斯理");
		book1.setPubDate(new Date());
		book1.setCategory(category1);
		Book book2=new Book();
		book2.setName("傲慢与偏见");
		book2.setPrice(80);
		book2.setAuthor("简.奥斯丁");
		book2.setPubDate(new Date());
		book2.setCategory(category3);
		Book book3=new Book();
		book3.setName("中国历史");
		book3.setPrice(21.5);
		book3.setAuthor("人民");
		book3.setPubDate(new Date());
		book3.setCategory(category2);
		Book book4=new Book();
		book4.setName("七龙珠");
		book4.setPrice(21.5);
		book4.setAuthor("不知道");
		book4.setPubDate(new Date());
		book4.setCategory(category4);
		Book book5=new Book();
		book5.setName("名侦探柯南");
		book5.setPrice(50);
		book5.setAuthor("宫崎骏");
		book5.setPubDate(new Date());
		book5.setCategory(category5);
		
		
		session.save(book);
		session.save(book1);
		session.save(book2);
		session.save(book3);
		session.save(book4);
		session.save(book5);
		tx.commit();
		HibernateUtil.closeSession();
	}
	@Test
	public void testGet(){
		Session session=HibernateUtil.getSession();
		Transaction tx=session.beginTransaction();
		/**
		 * 当Category.hbm.xml中的set中的lazy属性是true(默认为true)时,
		 * 先查询一端的Category,只会先查询Category数据;
		 * 
		 * 当执行下面for中的category.getBooks时才会去查询Book数据,这时就是懒加载
		 * 
		 * 但是当我们把Category.hbm.xml中的set中的lazy属性设为false时,
		 * 会在查询Category的时候,把Book也查询出来,这时就是即时加载
		 */
		
		Category category=(Category) session.get(Category.class, 1);
		System.out.println("分类名:"+category.getName());
		for(Iterator<Book> iter=category.getBooks().iterator();iter.hasNext();){
			System.out.println(iter.next().getName());
		}
		tx.commit();
		HibernateUtil.closeSession();
	}
	@Test
	public void testLoad(){
		Session session=HibernateUtil.getSession();
		Transaction tx=session.beginTransaction();
		Category category=(Category) session.get(Category.class, 1);
		System.out.println("分类名:"+category.getName());
		System.out.println("对应的书大小:"+category.getBooks().size());
		tx.commit();
		HibernateUtil.closeSession();
	}
}
断点运行testLoad,当运行到下面这句时,并没有查询数据的sql语句打印
Category category=(Category) session.get(Category.class, 1);
当执行到下面这句时,才会打印出sql语句

System.out.println("分类名:"+category.getName());
控制台打印sql语句如下:

Hibernate: 
    select
        category0_.id as id1_0_0_,
        category0_.name as name2_0_0_ 
    from
        Category category0_ 
    where
        category0_.id=?

继续运行

System.out.println("对应的书大小:"+category.getBooks().size());
执行这句后,打印sql语句如下:

Hibernate: 
    select
        books0_.category_id as category2_0_0_,
        books0_.id as id1_1_0_,
        books0_.id as id1_1_1_,
        books0_.category_id as category2_1_1_,
        books0_.author as author3_1_1_,
        books0_.book_name as book_nam4_1_1_,
        books0_.price as price5_1_1_,
        books0_.pubDate as pubDate6_1_1_ 
    from
        book books0_ 
    where
        books0_.category_id=?
当把Category.hbm.xml中set的lazy改为extra时,再执行

System.out.println("对应的书大小:"+category.getBooks().size());
打印sql语句如下:

Hibernate: 
    select
        count(id) 
    from
        book 
    where
        category_id =?

总结:

1、set/list默认下是lazy=true的。支持懒加载,但是当使用size()的时候依然要去查询整个set集合的内容。

2、lazy=false时,立即查询所有集合的内容。

3、lazy=extra时,比较智能,支持懒加载,当使用size()的时候不会查询整个集合,仅仅查询集合元素的个数。当需要使用集合元素的内容时,再去查询集合内容。


四、单端关联上的lazy:(many-to-one,one-to-one),默认是支持懒加载的lazy=proxy。


五、property上也有懒加载,默认lazy=false。如果property要去支持懒加载,需要用到第三方增强,且大部分情况下用不到property懒加载,只有当是大对象Blob、Clob时才会用到。















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值