当前位置: 代码迷 >> J2EE >> spring与hibernate整合,当手动抛出runtimeException时,spring无论怎么都不能让事务回滚,请前辈指教
  详细解决方案

spring与hibernate整合,当手动抛出runtimeException时,spring无论怎么都不能让事务回滚,请前辈指教

热度:10871   发布时间:2013-02-25 21:39:00.0
spring与hibernate整合,当手动抛出runtimeException时,spring无论如何都不能让事务回滚,请前辈指教
第一个类
package spring.dao;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import spring.entity.Log;


@Component("logDAO")
public class LogDAOImpl implements LogDAO {

private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public void addLog(Log log)  {
Session session = sessionFactory.getCurrentSession();
session.save(log);
throw new RuntimeException("运行异常");
}
}
第二个类
package spring.dao;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import spring.entity.User;
@Component("userDAO")
public class UserDAOImpl implements UserDAO {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public void addUser(User user)  {
Session session = sessionFactory.getCurrentSession();
session.save(user);
}
}
第3个类
package spring.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import spring.dao.LogDAO;
import spring.dao.UserDAO;
import spring.entity.Log;
import spring.entity.User;
@Component("userService")
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
private LogDAO logDAO;
public LogDAO getLogDAO() {
return logDAO;
}
@Resource(name="logDAO")
public void setLogDAO(LogDAO logDAO) {
this.logDAO = logDAO;
}
public UserDAO getUserDAO() {
return userDAO;
}
@Resource(name="userDAO")
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
@Transactional
public void addUser(User user) {

userDAO.addUser(user);
logDAO.addLog(new Log());
}
}
测试:
package spring.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import spring.entity.User;
import spring.service.UserService;
public class TestInvocationAOP {
@Test
public void testAspect()
{
ApplicationContext ctx = new FileSystemXmlApplicationContext("src\\applicationContext.xml");
//ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)ctx.getBean("userService");
userService.addUser(new User());
  相关解决方案