我正在构建一个Spring 4 + Hibernate 4应用程序。我的配置是这样的:
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(packagesDaoAnotaciones);
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
// Configuración del DataSource por el Servidor.
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource(environment.getRequiredProperty("jndi.datasource"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.put("hibernate.generate_statistics", "true");
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
我有这种方法的服务:
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void processThis() throws Exception {
List<String> myList = new ArrayList<>();
myList.add("1234567890");
myDao.update(myList,'01', "1234567890");
LOGGER.info("buahhhhhhhhhhhhhhhhhhhhhhh");
}
Dao执行如下的HQL查询:
@Override
public int update(List<String> data, String data1, String data2) {
StringBuffer hql = new StringBuffer();
hql.append("UPDATE MyTablenp SET np.field1 = :d1, field2= sysdate, field3= :d2, field4= sysdate, field5= null,field6= null WHERE np.data IN (:num)");
this.getSession().getTransaction().isActive();
Query query = this.getSession().createQuery(hql.toString());
query.setParameterList("num", data);
query.setParameter("d1", data1);
query.setParameter("d2", data2);
return query.executeUpdate();
}
当我执行此操作时,我可以看到在dao方法结束后刚刚在BBDD中修改的数据,但是服务方法还没有完成,所以它在没有完成事务方法的情况下提交HQL。有人知道如何避免该提交并仅在服务方法结束时提交吗?
答案 0 :(得分:0)
您应该使用带注释的方法proccessThis()
开始时由hibernate打开的现有会话。
在您的DAO中执行以下操作:
删除此:this.getSession().getTransaction().isActive();
,而是从会话工厂获取当前会话(假设您已扩展HibernateDaoSupport
):
Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();