org.hibernate.HibernateException:没有Hibernate会话绑定到线程

时间:2015-01-21 09:13:34

标签: java spring hibernate

我想打电话给下一个声明:

public List<User> getList(int master_id) {
        Session session = sessionFactory.getCurrentSession();
        try {
            List<User> result = (List<User>) sessionFactory.getCurrentSession()
                    .createQuery("from User WHERE master_id=:master_id")
                    .setInteger("master_id", master_id).list();
            return result;
        } finally {
            session.close();
        }
    }

然后我抓住了

  

没有Hibernate会话绑定到线程,并且配置不允许   在这里创建非交易的

有人说我必须为此添加@Transactional注释,但正如您所看到的那样,没有必要这样做,因为它是SELECT查询。怎么办?

hibernate.cfg:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="ru.tenet.smsc.domain.User" />   
        <mapping class="ru.tenet.smsc.domain.UserRoles" />
        <mapping class="ru.tenet.smsc.domain.WhiteList" />
        <mapping class="ru.tenet.smsc.domain.BlackList" />
        <mapping class="ru.tenet.smsc.domain.Distribution" />
        <mapping class="ru.tenet.smsc.domain.Range" />
        <mapping class="ru.tenet.smsc.domain.SmsEntity" />
        <mapping class="ru.tenet.smsc.domain.Archive" />
        <mapping class="ru.tenet.smsc.domain.Priority" />
    </session-factory>

</hibernate-configuration>

会话工厂:

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>/WEB-INF/db/hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect</prop>
                <prop key="hibernate.connection.useUnicode">true</prop>
                <prop key="hibernate.connection.characterEncoding">UTF-8</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
            </props>
        </property>
    </bean>

2 个答案:

答案 0 :(得分:0)

@Transactional 不仅适用于插入/更新,也适用于SELECT。您可以看到这一点,因为注释的其中一个参数可以是 readOnly = true (这意味着您的事务不会提交任何内容)

答案 1 :(得分:0)

您必须将当前会话绑定到当前线程

Session session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, 
new SessionHolder(session));
try {
 do your work ...
}
finally {
  TransactionSynchronizationManager.unbindResource(sessionFactory);
  SessionFactoryUtils.closeSessionIfNecessary(session, sessionFactory);
}  

如果您有网络应用,则应添加Spring OpenEntityManagerInViewFilter过滤器