春季hibernate – 无法获取当前线程的事务同步会话

我用spring + hibernate创build了一个应用程序,但是我总是得到这个错误。 这是我的第一个应用与hibernate,我读了一些指南,但我不能解决这个问题。 我在哪里做错了?

这是我的应用程序的代码

ott 05, 2014 4:03:06 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh Informazioni: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1eab16b: startup date [Sun Oct 05 16:03:06 CEST 2014]; root of context hierarchy ott 05, 2014 4:03:06 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions Informazioni: Loading XML bean definitions from class path resource [springConfig.xml] ott 05, 2014 4:03:08 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final} ott 05, 2014 4:03:08 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.3.6.Final} ott 05, 2014 4:03:08 PM org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found ott 05, 2014 4:03:08 PM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist ott 05, 2014 4:03:09 PM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect ott 05, 2014 4:03:09 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService INFO: HHH000399: Using default transaction strategy (direct JDBC transactions) ott 05, 2014 4:03:09 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init> INFO: HHH000397: Using ASTQueryTranslatorFactory Exception in thread "main" org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014) at coreservlets.StudentDAOImpl.create(StudentDAOImpl.java:19) at coreservlets.MainApp.main(MainApp.java:14) 

student.java

 package coreservlets; public class Student { private Integer id; private String name; private Integer age; public Integer getId(){return id;}//getId public void setId(Integer id){this.id=id;}//setId public String getName(){return name;}//getName public void setName(String name){this.name=name;}//setName public Integer getAge(){return age;}//getAge public void setAge(Integer age){this.age=age;}//setAge }//Student 

studentDAO.java

 package coreservlets; import org.hibernate.SessionFactory; public interface StudentDAO { public void setSessionFactory(SessionFactory sessionFactory); public void create(String name,Integer age); }//StudentDAO 

StudentDAOImpl.java

 package coreservlets; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class StudentDAOImpl implements StudentDAO { private SessionFactory sessionFactory; @Autowired public void setSessionFactory(SessionFactory sessionFactory){ this.sessionFactory=sessionFactory; }//setSessionFactory public void create(String name,Integer age){ Session session=sessionFactory.getCurrentSession(); Student student=new Student(); student.setName(name); student.setAge(age); session.save(student); }//create }//StudentDAOImpl 

MainApp.java

 package coreservlets; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("springConfig.xml"); StudentDAOImpl student=(StudentDAOImpl) context.getBean("studentDAOImpl"); student.create("Alessandro", new Integer(33)); }//main }//MainApp 

springConfig.xml

 <?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <context:annotation-config/> <context:component-scan base-package="coreservlets"/> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/spring_hibernate"/> <property name="username" value="root"/> <property name="password" value="password"/> <property name="initialSize" value="5"/> <property name="maxTotal" value="10"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect </value> </property> </bean> </beans> 

SQL

 create table student ( id integer not null auto_increment, name varchar(20) not null, age integer not null, primary key(id) ); 

您必须启用事务支持( <tx:annotation-driven>@EnableTransactionManagement )并声明 transactionManager并且它应该通过SessionFactory工作。

您必须将@Transactional添加到您的@Repository

在您的@Repository使用@Transactional Spring可以将事务支持应用到存储库中。

您的Student类没有@ javax.persistence。*注释如何@Entity ,我假设该类的映射configuration已通过XML定义。

我有同样的问题,但在一个不属于服务层的类中。 就我而言,事务pipe理器只是通过getBean()方法从上下文获得的,而类属于视图层 – 我的项目使用OpenSessionInView技术。

sessionFactory.getCurrentSession()方法一直导致与作者相同的exception。 对我来说,解决办法很简单。

 Session session; try { session = sessionFactory.getCurrentSession(); } catch (HibernateException e) { session = sessionFactory.openSession(); } 

如果getCurrentSession()方法失败,那么openSession()应该做到这一点。

在class级服务中添加spring的注解@Transactional

@Transactional = javax.transaction.Transactional把它放在@Repository旁边

在你的xyz.DAOImpl.java

执行以下步骤:

//步骤1:设置会话工厂

 @Resource(name="sessionFactory") private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sf) { this.sessionFactory = sf; } 

//第2步:尝试获取当前会话,并捕获HibernateExceptionexception。


//步骤3:如果有任何HibernateExceptionexception,则返回true以获得openSession。

 try { //Step-2: Implementation session = sessionFactory.getCurrentSession(); } catch (HibernateException e) { //Step-3: Implementation session = sessionFactory.openSession(); } 

@itachi不正确, sessionFactory.openSession()事务将被禁用。 因为他们不是同一届会议。

在class级服务中添加spring的注解@Transactional

@Patrikoko是正确的!

看到这个问题: 对于Web MVC的spring应用程序应@Transactional去控制器或服务?

例:
@Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = {java.lang.Exception.class})

我遇到了同样的问题,最后发现在[dispatcher] -servlet.xml中没有定义组件扫描元素启用@service注释类。

简单地把组件扫描元件放在一起,问题就消失了。

我的类似的问题得到了解决方法2以下方法。

  1. 通过手动处理交易。

    Session session = sessionFactory.getCurrentSession();

    Transaction tx = session.beginTransaction();

    UserInfo user =(UserInfo)session.get(UserInfo.class,1);

    tx.commit();

  2. 告诉Spring在您的web.xmlfilter中为您打开和pipe理事务,并确保使用@Repository @Transactional

    <filter> <filter-name> hibernateFilter </ filter-name> <filter-class> org.springframework.orm.hibernate5.support.OpenSessionInViewFilter </ filter-class> <init-param> <param-name> sessionFactory <param -value> session.factory </ init-param> </ filter> <filter-mapping> <filter-name> hibernateFilter </ filter-name> <url-pattern> / * </ url-pattern> </ filter-映射>

对不起,格式不正确。

我在web.xml中添加了这些configuration,对我来说效果很好!

 <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> <init-param> <param-name>flushMode</param-name> <param-value>AUTO</param-value> </init-param> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 

此外,排名最高的答案为我提供了线索,以防止应用程序在第一次运行时出现恐慌。