简体   繁体   English

由于'org.hibernate.HibernateException所需的@Transactional注释:找不到当前线程的异常'异常

[英]@Transactional annotation required due to 'org.hibernate.HibernateException: No Session found for current thread' exception

So, I read that the best place to put the @Transactional annotation was outside the DAO classes which contains the db access methods, like in a service class which use those methods. 因此,我读到放置@Transactional注释的最佳位置是在包含db访问方法的DAO类之外,就像在使用这些方法的服务类中一样。

Now, the problem is, once I've already remove this annotations from the DAO classes, I launch the DAO test methods and the aforementioned exception raised. 现在,问题是,一旦我已经从DAO类中删除了这个注释,我就会启动DAO测试方法并引发上述异常。 I put back the annotations in the DAO classes and this exception doesn't raises anymore. 我在DAO类中放回了注释,这个异常不会再引发了。

Then my question is: how can I clear my DAOs of this annotations and still have my tests working? 然后我的问题是:我如何清除这些注释的DAO并仍然让我的测试工作?

Let's add some code: 我们添加一些代码:

DAO class DAO班

public class UserDAO  extends IDAO implements IUserDAO {


    @Override
    //@Transactional(readOnly=true)
    public User get(int idUser) {
        return (User) currentSession().get(User.class,idUser);
    }}

IDAO Class IDAO课程

public abstract class IDAO {

    protected SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Session currentSession()
    {
        return sessionFactory.getCurrentSession();
    }

}

Test class 考试班

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:META-INF/spring/app-context.xml" })
public class UserDAOTest extends AbstractJUnit4SpringContextTests {

    @Autowired
    private IUserDAO userDAO;

    @Test
    public void testGetUser() throws Exception {
        User user = userDAO.get(2);
        assertNotNull(user);
    }
}

app-config APP-配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"
            value="jdbc:mysql://localhost:3306/waldb" />
        <property name="username" value="user" />
        <property name="password" value="password" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.wal.serverside.persistence.domain.User</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="userDAO" class="com.wal.serverside.persistence.DAO.UserDAO">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <context:component-scan base-package="com.wal.serverside.persistence" />

</beans>

Gosh, how much stupid can I be? 天哪,我有多愚蠢?

My test class didn't extend from AbstractTransactionalJUnit4SpringContextTests , so there were nor transaction nor session inside my tests. 我的测试类没有从AbstractTransactionalJUnit4SpringContextTests扩展,因此我的测试中也没有事务或会话。

This fixed it all: 这解决了所有问题:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:META-INF/spring/app-context.xml" })
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
@Transactional
public class UserDAOTest extends AbstractTransactionalJUnit4SpringContextTests  {

    @Autowired
    private IUserDAO userDAO;

    public void setUserDAO(IUserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @Test
    public void testGetUser() throws Exception {
        User user = userDAO.get(2);
        assertNotNull(user);
    }
}

Try to put not only @Transactional annotaition on your test class but also @TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false) . 尝试不仅将@Transactional注释放在您的测试类上,还要放置@TransactionConfiguration(transactionManager =“transactionManager”,defaultRollback = false) Where you explicitly set the name of the transaction manager that you have defined in xml. 您在哪里显式设置已在xml中定义的事务管理器的名称。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:META-INF/spring/app-context.xml" })
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
public class UserDAOTest {
     ...
}

Also transaction will not work if you explicitly create the application context in your test method and then get the bean from it: 如果您在测试方法中显式创建应用程序上下文然后从中获取bean,那么事务也将无效:

ApplicationContext appContext = new ClassPathXmlApplicationContext(...);
SomeDAO someDAO = (SomeDAO) appContext.getBean(...);

instad of inhjecting it. 注意它的instad。

But I see this is not your case. 但我发现这不是你的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Hibernate 4:org.hibernate.HibernateException:当前会话找不到会话 - Hibernate 4 : org.hibernate.HibernateException: No Session found for current thread org.hibernate.HibernateException:使用tx:advise找不到当前线程的会话 - org.hibernate.HibernateException: No Session found for current thread with tx:advise org.hibernate.HibernateException: 没有找到当前线程 5 的会话 - org.hibernate.HibernateException: No Session found for current thread 5 请求处理失败; 嵌套的异常是org.hibernate.HibernateException:当前会话找不到会话 - Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread Estado HTTP 500-请求处理失败; 嵌套的异常是org.hibernate.HibernateException:当前会话找不到会话 - Estado HTTP 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread 嵌套的异常是org.hibernate.HibernateException:当前会话addDepartment控制器找不到会话 - nested exception is org.hibernate.HibernateException: No Session found for current thread addDepartment controller Spring + Hibernate应用程序中的问题:org.hibernate.HibernateException:找不到当前线程的Session - Problems in Spring + Hibernate application: org.hibernate.HibernateException: No Session found for current thread Spring Security authenticationFailure:错误org.hibernate.HibernateException:没有找到当前线程的会话 - Spring Security authenticationFailure : error org.hibernate.HibernateException: No Session found for current thread Micronaut MySQL删除记录org.hibernate.HibernateException:当前会话找不到会话 - Micronaut MySQL delete record org.hibernate.HibernateException: No Session found for current thread 线程“ main” org.hibernate.HibernateException中的异常: - Exception in thread “main” org.hibernate.HibernateException:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM