SSM事务

问题描述:查询用户信息时想级联查出用户订单以及订单详情,在查询用户的时候JDBC是will be managed by Spring,但懒加载用户订单以及订单详情时就will not be managed by Spring

Spring配置

<?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:tx
="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd"
> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="com.dsy.service"/> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>

service层代码,添加 事务注解

//一定要加上否则下面的方法不会被事务控制
@Transactional(value = "transactionManager")
public abstract class BaseServiceImpl<T> implements BaseService<T> {
 
    public abstract BaseMapper<T> getMapper();
 
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return getMapper().deleteByPrimaryKey(id);
    }
@Service
@Transactional(value = "transactionManager")
public class UserServiceImpl extends BaseServiceImpl implements UserService {
 
    @Autowired
    private UserMapper userMapper;
 
    @Override
    public BaseMapper<User> getMapper() {
        return userMapper;
    } 
 
}
原文地址:https://www.cnblogs.com/moonsoft/p/10084069.html