@Repository
public class Init {
public static void main(String[] args) {
Init init = new Init();
init.addUser(init.getSessionFactory());
}
private SessionFactory getSessionFactory() {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "Spring_Hibernate.xml" });
SessionFactory sf = (SessionFactory) context.getBean("sessionFactory");
return sf;
}
@Transactional
private void addUser(SessionFactory sf) {
Session session = sf.getCurrentSession();
User user = new User();
user.setName("123");
session.save(user);
session.close();
sf.close();
}
}
xml:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.warmmer.bean" />
<property name="hibernateProperties">
<!-- <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> -->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
错误: 信息:将 Hibernate SessionFactory 的 DataSource [org.apache.commons.dbcp.BasicDataSource@6098b14d] 用于 HibernateTransactionManager 线程“main”中的异常 org.hibernate.HibernateException:无法为当前线程获取事务同步 session
如果: hibernate.current_session_context_class 设置“线程”
然后 :save 在没有 Activity 事务的情况下无效
请问我该怎么办?
最佳答案
您不是在 spring 上下文中创建您的“Init”对象,因此 spring 永远不会有机会使用将管理事务的注释在方法周围包装代理
尝试将您的类(class)更改为...
package my.pkg;
// Imports etc
@Repository
public class Init {
@Autowired
private SessionFactory sessionFactory;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "Spring_Hibernate.xml" });
Init init = context.getBean(Init.class);
init.addUser();
}
@Transactional
private void addUser() {
Session session = sessionFactory.getCurrentSession();
User user = new User();
user.setName("123");
session.save(user);
// session.close(); DON'T NEED THESE!
// sf.close();
}
}
现在您可能需要将以下内容添加到您的 beans 文件中,以便它找到您的存储库...
<context:component-scan base-package="my.pkg"/>
关于java - Hibernate 4 Spring 4 无法获取当前线程的事务同步 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324778/