Hibernate 的延迟加载

hibernate中的延迟加载(lazyload)分属性的延迟加载关系的延迟加载 

属性的延迟加载: 

当使用load的方式来获取对象的时候,只有访问了这个对象的属性,hibernate才会到数据库中进行查询。否则不会访问数据库。

package com.how2java.test; 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.how2java.pojo.Product;
 
public class TestHibernate {
    public static void main(String[] args) {
        SessionFactory sf = new Configuration().configure().buildSessionFactory(); 
        Session s = sf.openSession();
        s.beginTransaction();
        //核心代码:在打印log1之前,是不会打印出sql语句的,只有在访问属性“getName()"的时候,才会访问数据库
        Product p = (Product)s.load(Product.class, 1);
        System.out.println("log1");
        System.out.println(p.getName());
        System.out.println("log2");

        s.getTransaction().commit();
        s.close();
        sf.close();
    }
}

延迟加载又叫lazyload,在one-many many-many的时候都可以使用关系的延迟加载

修改配置文件 Category.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.how2java.pojo">
	<class name="Category" table="category_">
		<id name="id" column="id">
			<generator class="native">
			</generator>
		</id>
		<property name="name" />
                <!-- 这里将lazy="false"改为true,表示通过Category获取产品是延迟加载的-->
		<set name="products" lazy="true">
			<key column="cid" not-null="false" />
			<one-to-many class="Product" />
		</set>
				
	</class>
	
</hibernate-mapping>

测试代码:

package com.how2java.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.how2java.pojo.Category;

public class TestHibernate {
	public static void main(String[] args) {
		SessionFactory sf = new Configuration().configure().buildSessionFactory();
		Session s = sf.openSession();
		s.beginTransaction();
		Category c = (Category) s.get(Category.class, 1);//只会查询Category表的信息,不会查询product_表
		System.out.println("log1");
		System.out.println(c.getProducts());//通过category取products的时候,才会进行对product_表的查询
		System.out.println("log1");

		s.getTransaction().commit();
		s.close();
		sf.close();
	}
}

为什么要使用关系延迟?

比如有的页面只需要显示分类信息,这个时候倘若没有开启延迟加载,那么就会把分类下的产品也查询出来了,增加了不必要的开销。

hibernate 延迟加载问题

01-24

数据库rn表 assetrnidrnnamernpricernstatusrndepartmentId外键rntypeId外键rnremarkrn表 assettypernid rnnamernremarkrnrn用MyEceplisernAction中rn // 从数据库读取当前所有的新闻信息rn List list = AssetUtil.findAll();rn if (list == null) rn return new ActionForward(mapping.getInput());rn rnrn // 获得HttpSession缓存rn HttpSession httpSession = request.getSession();rn // 将所有的新闻信息存入缓存rn httpSession.setAttribute("assetlist", list);rn rn return mapping.findForward(SUCCESS);rnrnAssetUtil.findAllrnrn public static List findAll() rn List list = null;rn list = HibernateService.execQuery("from Asset");rn return list;rn rnrnHibernateServicernrn public static List execQuery(String hql) rn List list = null;rn Transaction transaction = null;rn Session session = null;rn try rn session = HibernateService.getSession();rn transaction = session.beginTransaction();rn list = session.createQuery(hql).list();rn System.out.println(hql + " 找到行数:" + list.size());rn transaction.commit();rn catch (HibernateException he) rn he.printStackTrace();rn HibernateService.rollbackTransaction(transaction);rn list = null;rn catch (Exception e) rn e.printStackTrace();rn list = null;rn finally rn HibernateService.closeSession(session);rn rn return list;rn rnrn当jsp页面出错rnrn <%=asset.getAssettype().getName()%>rn出错rnrn 说session已经关闭rn 这个我该如何做啊? 还望大家多多指教rn没有用到Spring 所以那个方面不太行rn

Hibernate延迟加载的怪问题

12-05

写了一个映射文件,里面有一个一对多的集合。rnrn在service调用dao方法如下:rntry rn Vendor vendor=vendorDao.get(HibernateSessionFactory.currentSession(), id);rn //Hibernate.initialize(vendor);rn return vendor;rn catch (Exception e) rn // TODO: handle exceptionrn throw new ServiceException("自定义异常 " + e);rn finally rn HibernateSessionFactory.closeSession();rnrnrnrn然后写了一个测试方法调用service类中此方法。rn系统抛出了异常:rn[eMarket] ERROR 2008-12-05 15:25:44,203 could not initialize proxy - the owning Session was closed | org.hibernate.LazyInitializationException.(19)rnorg.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closedrn at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:53)rn at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:84)rn at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:134)rnrnrnrn问题就是,我在测试方法中只是print了这个类中的基本信息,并没有访问关联类的信息,但是仍然抛出了session关闭的异常。rn而且我将hbm中一对多映射注释后,仍然会抛出异常。rn调用Hibernate.initialize(vendor);强制初始化后,程序正常执行。rnhbm class级别显示设置laze="false"后,程序也能正常执行。但是类级别(非关联类)的lazy默认不就是false的吗。rnrnrn

hibernate和proxool,如何实现延迟加载

10-12

根据项目需求,我们有个web系统在tomcat中启动时,连接的oracle方案是不存在的,它是由一个web管理系统创建的。为了防止后台报连接数据库错误,把spring中所有的bean都设置为延迟加载,但是还是会出现连接数据库错误提示,难道proxool不支持延迟加载吗? rnrnrnat oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:111)rn at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:145)rn at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:254)rn at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:386)rn at oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:413)rn at oracle.jdbc.driver.T4CConnection.(T4CConnection.java:164)rn at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:34)rn at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:752)rn at java.sql.DriverManager.getConnection(DriverManager.java:525)rn at java.sql.DriverManager.getConnection(DriverManager.java:140)rn at org.logicalcobwebs.proxool.DefaultConnectionBuilder.buildConnection(DefaultConnectionBuilder.java:39)rn at org.logicalcobwebs.proxool.Prototyper.buildConnection(Prototyper.java:159)rn at org.logicalcobwebs.proxool.ConnectionPool.getConnection(ConnectionPool.java:211)rn at org.logicalcobwebs.proxool.ProxoolDataSource.getConnection(ProxoolDataSource.java:97)rn at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81)rn at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:84)rn at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)rn at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)rn at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:805)rn at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:745)

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试