我正在创建简单的spring boot应用程序。我使用spring transaction management来处理事务。这是我的代码。
ServiceImpl类
@Service("orderService")
public class OrderServiceImpl implements OrderService {
@Autowired
private CustomerDao customerDao;
@Autowired
private OrderDao orderDao;
@Transactional(rollbackFor = Exception.class)
@Override
public Long placeOrder(OrderPlacementRequest request) {
customerDao.save(request.getCustomer());
return orderDao.placeOrder(request.getOrder());
}
}
OrderDaoImpl类,
@Repository("orderDao")
public class OrderDaoImpl extends AbstractHibernateDao implements OrderDao {
@Override
public Long placeOrder(Order order) {
throw new RuntimeException("Test Error Message");
}
}
配置类,
@Configuration
@EnableTransactionManagement
public class HibernateConfig {
//Other Configurations
@Autowired
private final Environment environment;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(environment.getRequiredProperty("spring.datasource.url"));
dataSource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
dataSource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
return dataSource;
}
@Bean
public DataSourceTransactionManager transactionManager() {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource());
return transactionManager;
}
}
application.properties
spring.aop.proxy-target-class=true
OrderController类
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@RequestMapping(value = "/place", method = RequestMethod.POST)
public Long placeOrder(@RequestBody OrderPlacementRequest request) {
return orderService.placeOrder(request);
}
}
在我的情况下即使第二种方法placeOrder
失败了。客户将保存在mysql数据库中。我想要的是回滚客户保存方法。我阅读了一些关于事务管理的文章,包括spring docs和stackoverflow。仍然找不到问题。
使用Controller类更新。