您的位置:时时app平台注册网站 > 编程知识 > hibernate延迟加载org.hibernate.LazyInitializationExceptio

hibernate延迟加载org.hibernate.LazyInitializationExceptio

2019-10-12 09:19

集合延迟加载开始化失利,无法起先化三个代理。便是集结在非一对一对象关系中,为了省去财富是暗许延迟加载,而get方法又是非延迟加载,所以在实行完壹遍数据库查询后就施行session.close();关闭了session,而集合是延迟加载,在选取集合时再加载,此时session已经关闭,所以得不到代办。消除方法:能够在主表的hbm配置文件中,在<set>标签里安装lazy="false",集结就不延迟加载了,由此在实施get方法时,集合也赢获得了,就不会产出延迟加载难点了。

撤回延迟加载:

  • Configures and provides access to Hibernate sessions, tied to the
  • current thread of execution. Follows the Thread Local Session
  • pattern, see {@link }.
    */
    public class HibernateSessionFactory {

    /**

    • Location of hibernate.cfg.xml file.
    • Location should be on the classpath as Hibernate uses
    • #resourceAsStream style lookup for its configuration file.
    • The default classpath location of the hibernate config file is
    • in the default package. Use #setConfigFile() to update
    • the location of the configuration file for the current session.
      */private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";private static final ThreadLocal threadLocal = new ThreadLocal();private static Configuration configuration = new Configuration();private static org.hibernate.SessionFactory sessionFactory;private static String configFile = CONFIG_FILE_LOCATION;

    static {
    try {
    configuration.configure(configFile);
    sessionFactory = configuration.buildSessionFactory();
    } catch (Exception e) {
    System.err
    .println("%%%% Error Creating SessionFactory %%%%");
    e.printStackTrace();
    }
    }
    private HibernateSessionFactory() {
    }

    /**

    • Returns the ThreadLocal Session instance. Lazy initialize
    • the SessionFactory if needed.*
    • @return Session
    • @throws HibernateException
      */
      public static Session getSession() throws HibernateException {
      Session session = threadLocal.get();

      if (session == null || !session.isOpen {
      if (sessionFactory == null) {
      rebuildSessionFactory();
      }
      session = (sessionFactory != null) ? sessionFactory.openSession()
      : null;
      threadLocal.set;
      }

      return session;
      }

    /**

    • Rebuild hibernate session factory**/public static void rebuildSessionFactory() {try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory();} catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace();}}

    /**

    • Close the single hibernate session instance.*
    • @throws HibernateException
      */
      public static void closeSession() throws HibernateException {
      Session session = threadLocal.get();
      threadLocal.set;

      if (session != null) {
      session.close();
      }
      }

    /**

    • return session factory**/public static org.hibernate.SessionFactory getSessionFactory() {return sessionFactory;}

    /**

    • return session factory*
    • session factory will be rebuilded in the next call*/public static void setConfigFile(String configFile) {HibernateSessionFactory.configFile = configFile;sessionFactory = null;}

    /**

    • return hibernate configuration**/public static Configuration getConfiguration() {return configuration;}

 

日常意况下,Hibernate会私下认可给大家设置延迟加载。lazy="true" ,那样会进步我们的系统性子,所以日常情状下,我们不会去

 Session session = HibernateSessionFactory.getSession(); Transaction ta = session.beginTransaction(); Userinfo userinfo =  session.createCriteria(Userinfo.class) .add(Expression.eq("userinfoName", name)).add( Expression.eq("userinfoPassword", pwd)).uniqueResult(); ta.commit(); HibernateSessionFactory.closeSession(); return userinfo;}

Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.javakc.hibernate.onetomany.entity.DeptEntity.emp, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:326)
at java.lang.String.valueOf(String.java:2827)
at java.io.PrintStream.println(PrintStream.java:771)
at com.javakc.hibernate.onetomany.action.TestAction.main(TestAction.java:74)

代码:

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

}

import org.hibernate.Session;

}

private static DeptEntity getDept(String did){
  Session session = sessionFactory.openSession();
  DeptEntity dept = (DeptEntity)session.get(DeptEntity.class, did);
  session.close();
  return dept;
}

/**
 *
 * @author XHW
 *
 * @date 2011-7-18
 *
 */
public class HibernateTest {
 public static void main(String[] args) {
  new HibernateTest().update();
 }
 public void update(){
  Session session=HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();
  Category category=(Category)session.get(Category.class, 1);
  System.out.println("id:" category.getId() "  ,name:" category.getName() ", description:" category.getDescription());
  
  Set<Product> products=category.getProducts();
  
  session.getTransaction().commit();  
 }
 
 
}

我的的struts2 hibernate3

运行结果:

    where
        products0_.category_id=?
ID:  1  name:java SE应用程序设计 price: 78.00
此间能够一览无余的告诉大家,当大家要加载Set集结的时候,那时候才去加载,而地点的例证,表达的是大家不加载的时候

/**

  //dept.getEmp()获得子表的笔录集结
  System.out.println(dept.getEmp());

Category.hbm.xml

[b]标题补充:[/b]
package com.shop.hibernate.util;

 

/**
 *
 * @author XHW
 *
 * @date 2011-7-18
 *
 */
public class HibernateTest {
 public static void main(String[] args) {
  new HibernateTest().update();
 }
 public void update(){
  Session session=HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();
  Category category=(Category)session.get(Category.class, 1);
  System.out.println("id:" category.getId() "  ,name:" category.getName() ", description:" category.getDescription());
  
  Set<Product> products=category.getProducts();
   
  session.getTransaction().commit();  
 }
 
 
}

[b]主题素材补充:[/b]

Caused by: java.sql.SQLException: 关闭的延续
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:269)
at oracle.jdbc.driver.OracleConnection.privatePrepareStatement(OracleConnection.java:895)
at oracle.jdbc.driver.OracleConnection.prepareStatement(OracleConnection.java:802)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:396)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:334)
at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:88)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1162)
at org.hibernate.loader.Loader.doQuery(Loader.java:390)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:218)
at org.hibernate.loader.Loader.doList(Loader.java:1593)
... 122 more

public static void main(String[] args) {
 
  DeptEntity dept = getDept("402882e762ae888d0162ae888e420000");

Hibernate就延期加载

那是自动生成的

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    select
        category0_.id as id1_0_,
        category0_.name as name1_0_,
        category0_.description as descript3_1_0_
    from
        users.category category0_
    where
        category0_.id=?
Hibernate:
    select
        products0_.category_id as category2_1_,
        products0_.id as id1_,
        products0_.id as id0_0_,
        products0_.category_id as category2_0_0_,
        products0_.name as name0_0_,
        products0_.price as price0_0_,
        products0_.descripton as descripton0_0_
    from
        users.product products0_
    where
        products0_.category_id=?
id:1  ,name:java, description:java好啊
和测验代码一的运转结果相互比较,大家会开采,这一次运转结果用了两条select语句。不过大家会意识

SQL Error: 17008, SQLState: null
历次程序运维一段时间今后,就报此错
08-08-17 09:55:29 WARN JDBCExceptionReporter:71 - SQL Error: 17008, SQLState: null
08-08-17 09:55:29 EOdysseyROPAJERO JDBCExceptionReporter:72 - 关闭的连天
08-08-17 09:55:29 WARN JDBCExceptionReporter:71 - SQL Error: 17008, SQLState: null
08-08-17 09:55:29 E揽胜RO奥迪Q5 JDBCExceptionReporter:72 - 关闭的总是
org.hibernate.exception.GenericJDBCException: could not execute query
Caused by: java.sql.SQLException: 关闭的一连

安装lazy="false",当然在特殊的状态下,我们亟必要裁撤延迟加载的时候,大家就把lazy="false",就能够了

dao是
public Userinfo checkUserinfo(String name, String pwd) {

/**
 *
 */
package com.b510.examples;

延迟加载在Hibernate中是暗中同意延迟加载;

运转作效果果:

  System.out.println("id:" category.getId() "  ,name:" category.getName() ", description:" category.getDescription());
输出的是id,name和description属性值,其余的大家随意,所以Hibernate用了lazy loading(延迟加载),带来的补益正是大家不关切的

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    select
        category0_.id as id1_0_,
        category0_.name as name1_0_,
        category0_.description as descript3_1_0_
    from
        users.category category0_
    where
        category0_.id=?
id:1  ,name:java, description:java好啊
Hibernate: 
    select
        products0_.category_id as category2_1_,
        products0_.id as id1_,
        products0_.id as id0_0_,
        products0_.category_id as category2_0_0_,
        products0_.name as name0_0_,
        products0_.price as price0_0_,
        products0_.descripton as descripton0_0_
    from
        users.product products0_

HIbernateTest.java

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    select
        category0_.id as id1_0_,
        category0_.name as name1_0_,
        category0_.description as descript3_时时app平台注册网站,1_0_
    from
        users.category category0_
    where
        category0_.id=?
id:1  ,name:java, description:java好啊

代码:

代码:

import java.util.Set;

/**
 *
 * @author XHW
 *
 * @date 2011-7-18
 *
 */
public class HibernateTest {
 public static void main(String[] args) {
  new HibernateTest().update();
 }
 public void update(){
  Session session=HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();
  Category category=(Category)session.get(Category.class, 1);
  System.out.println("id:" category.getId() "  ,name:" category.getName() ", description:" category.getDescription());
  
  Set<Product> products=category.getProducts();
  for(Product product:products){
   System.out.println("ID:  " product.getId() "  name:" product.getName() " price: " product.getPrice());
  }  
  session.getTransaction().commit();  
 }
 
 
}

/**
 *
 */
package com.b510.examples;

HibernateTest.java

第二条select语句,对于我们的急需是从未要求的,他唯有多个用处便是据有大家的程序实施时间。当然,

运行效果:

测验代码:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.b510.examples.Category" table="category" catalog="users">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="500" />
        </property>
        <property name="description" type="java.lang.String">
            <column name="description" length="500" />
        </property>
        <set name="products" inverse="true" lazy="false">
            <key>
                <column name="category_id" />
            </key>
            <one-to-many class="com.b510.examples.Product" />
        </set>
    </class>
</hibernate-mapping>

代码:

import org.hibernate.Session;

此处我们见到大家关切的是id,name和description属性,

import java.util.Set;

HibernateTest.java

运维结果:

纵然有:  Set<Product> products=category.getProducts(); 代码,即:不管理集合对象。然则大家固然的是:

import org.hibernate.Session;

数量,不用今后加载,当我们要用的时候,才去加载

测试代码一:

import java.util.Set;

那是我们不愿意看到的结果。

测量检验代码二:

/**
 *
 */
package com.b510.examples;

本文由时时app平台注册网站发布于编程知识,转载请注明出处:hibernate延迟加载org.hibernate.LazyInitializationExceptio

关键词: