java - 组织.hibernate.LazyInitializationException : How to properly use Hibernate's lazy loading feature

标签 java hibernate

我在使用 Hibernate 和 lazy=true 模式从我的数据库加载对象列表时遇到了一些问题。 希望有人能在这里帮助我。

我这里有一个名为 UserAccount 的简单类,如下所示:

public class UserAccount {
    long id;
    String username;
    List<MailAccount> mailAccounts = new Vector<MailAccount>();

    public UserAccount(){
        super();
    }

    public long getId(){
        return id;
    }

    public void setId(long id){
        this.id = id;
    }

    public String getUsername(){
        return username;
    }

    public void setUsername(String username){
        this.username = username;
    }

    public List<MailAccount> getMailAccounts() {
        if (mailAccounts == null) {
            mailAccounts = new Vector<MailAccount>();
        }
        return mailAccounts;
    }

    public void setMailAccounts(List<MailAccount> mailAccounts) {
        this.mailAccounts = mailAccounts;
    }
}

我通过以下映射文件在 Hibernate 中映射此类:

<?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>
    <class name="test.account.UserAccount" table="USERACCOUNT">

        <id name="id" type="long" access="field">
            <column name="USER_ACCOUNT_ID" />
            <generator class="native" />
        </id>

        <property name="username" />

        <bag name="mailAccounts" table="MAILACCOUNTS" lazy="true" inverse="true" cascade="all">
            <key column="USER_ACCOUNT_ID"></key>
            <one-to-many class="test.account.MailAccount" />
        </bag>

    </class>
</hibernate-mapping>

如您所见,lazy 在 bag 映射元素中设置为“true”。

将数据保存到数据库工作正常:

加载也可以通过调用 loadUserAccount(String username) 来实现(见下面的代码):

public class HibernateController implements DatabaseController {
    private Session                 session         = null;
    private final SessionFactory    sessionFactory  = buildSessionFactory();

    public HibernateController() {
        super();
    }

    private SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public UserAccount loadUserAccount(String username) throws FailedDatabaseOperationException {
        UserAccount account = null;
        Session session = null;
        Transaction transaction = null;
        try {
            session = getSession();
            transaction = session.beginTransaction();
            Query query = session.createQuery("FROM UserAccount WHERE username = :uname").setParameter("uname", username));
            account = (UserAccount) query.uniqueResult();
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            throw new FailedDatabaseOperationException(e);
        } finally {
            if (session.isOpen()) {
                // session.close();
            }
        }

        return account;
    }

    private Session getSession() {
        if (session == null){
            session = getSessionFactory().getCurrentSession();
        }
        return session;
    }
}

问题只是:当我访问列表“mailAccounts”中的元素时,出现以下异常:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: test.account.UserAccount.mailAccounts, no session or session was closed

我假设此异常的原因是 session 已关闭(不知道为什么以及如何),因此 Hibernate 无法加载列表。 如您所见,我什至从 loadUserAccount() 方法中删除了 session.close() 调用,但 session 似乎仍然被关闭或被另一个实例替换. 如果我设置 lazy=false,那么一切都会顺利进行,但这不是我想要的,因为由于性能问题,我需要“按需”加载数据的功能。

因此,如果我不能确定我的 session 在方法 loadUserAccount(String username) 终止后仍然有效,那么拥有该功能的意义何在?我该如何解决这个问题?

感谢您的帮助!

Ps:本人是Hibernate初学者,请见谅。

更新:这是我的 hibernate config.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">foo</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mytable</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

        <!-- Auto create tables -->
<!--        <property name="hbm2ddl.auto">create</property>-->

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Mappings -->
        <mapping resource="test/account/SmampiAccount.hbm.xml"/>
        <mapping resource="test/account/MailAccount.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

最佳答案

延迟加载工作与否与事务边界无关。它只需要 Session 是打开的。

但是, session 何时打开取决于您实际设置 SessionFactory 的方式,您没有告诉我们! SessionFactory.getCurrentSession() 实际执行的操作背后有配置!如果您让它与 ThreadLocalSessionContext 的默认版本一起使用并且不做任何事情来管理生命周期,它实际上确实默认为在您提交时关闭 session 。 (因此,普遍认为扩大事务边界是延迟加载异常的“修复”。)

如果您使用 sessionFactory.openSession()session.close() 管理您自己的 session 生命周期,您将能够在 session 生命周期内很好地延迟加载,交易边界外。或者,您可以提供 ThreadLocalSessionContext 的子类,以您想要的边界管理 session 生命周期。还有现成的替代方法,例如 OpenSessionInView 过滤器,可用于 Web 应用程序以将 session 生命周期绑定(bind)到 Web 请求生命周期。

编辑:如果适合您,您当然也可以只在交易中初始化列表。我只是认为,当您需要为实体的每个水合作用级别使用某种“标志”参数的新方法签名时,这会导致真正笨拙的 API。 dao.getUser() dao.getUserWithMailAccounts() dao.getUserWIthMailAccountsAndHistoricalIds() 等等。

编辑 2:您可能会发现这对于 session 保持打开多长时间/ session 范围和事务范围之间的关系的不同方法很有帮助。 (特别是 session-per-request-with-detached-objects 与 session-per-conversation 的想法。)

对话的实际规模取决于您的要求和架构。

关于java - 组织.hibernate.LazyInitializationException : How to properly use Hibernate's lazy loading feature,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5837169/

相关文章:

java - 并行事务如何产生OptimistickLockException?

java - 如何向 cxf soap 请求添加自定义 header ?

java - 在 Spring 批处理中重复作业(并停止、开始)

java - 如何解决 Spring Data JPA 中的 LazyInitializationException?

java - 在 NetBeans 7.1 中通过 clean-build 将 java jar lib 分发到多个目标

java - 能够在 Seam 3 中 @Inject EntityManager 的配置

Hibernate 抛出 SQLException 无法重置阅读器

nhibernate - HQL:查询动态组件属性

java - Hibernate::意外的 token :FOR

java - 将集合设置为 'new ArrayList()' 时级联 hibernate 删除