SSM-Spring-数据库事务管理-在Spring+MyBatis组合中使用事务

该博客详细介绍了如何在Spring+MyBatis环境中配置和使用数据库事务管理。通过创建spring配置文件、POJO实体类、Mybatis映射文件和服务类,实现了事务的配置和注解控制。同时,展示了日志配置和测试用例,确保事务的正确性和回滚机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SSM-Spring-数据库事务管理-在Spring+MyBatis组合中使用事务

目录图:

在这里插入图片描述

文件作用备注
Test.java程序入口从这里开始测试程序
RoleMapper.javaMybatis接口文件
Role.javaPOJO文件POJO实体类
RoleListService.java角色列表操作接口列表插入操作
RoleListServicelmpl.java角色列表操作接口实现类
RoleService.java角色服务接口
RoleServiceImpl.java角色服务接口实现类
RoleMapper.xmlMaybatis映射文件
sqlMapConfig.xmlMybatis配置文件
log4j.propertieslog4j配置文件
tm01.xmlspring配置文件

创建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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-beans.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!--启动扫描机制,并指定扫描对应的包-->
    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.ssm"></context:component-scan>

    <!--数据库连接-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <!--可能需要加时区-->
        <property name="url" value="jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="123456789"/>
        <property name="maxTotal" value="255"/>
        <property name="maxIdle" value="5"/>
        <property name="maxWaitMillis" value="10000"/>
    </bean>

    <!--集成Mybatis-->
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--指定Mybatis配置文件-->
        <property name="configLocation" value="classpath:/mybatis/sqlMapConfig.xml"/>
    </bean>

    <!--事务管理器配置数据源事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--使用注解定义事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--采用自动扫描方式创建mapper bean-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm"/>
        <property name="sqlSessionFactory" ref="SqlSessionFactory"/>
        <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
    </bean>
</beans>

创建POJO类

public class Role {
    private Long id;
    private String roleName;
    private String note;
    //set and get...
}

搭建mybatis映射文件

映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.mapper.RoleMapper">
    <insert id="insertRole" parameterType="com.ssm.pojo.Role">
        insert into role (roleName,note) values(#{roleName},#{note})
    </insert>
</mapper>

映射接口:

package com.ssm.mapper;

import com.ssm.pojo.Role;
import org.springframework.stereotype.Repository;

@Repository
public interface RoleMapper {
    public int insertRole(Role role);
}

创建Mybatis映射器

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <mapper resource="com/ssm/mapper/RoleMapper.xml"/>
    </mappers>
</configuration>

创建及配置服务类

创建两个接口:

import com.ssm.pojo.Role;

import java.util.List;

public interface RoleListService {
    public int insertRoleList(List<Role> roleList);
}
import com.ssm.pojo.Role;

//角色操作
public interface RoleService {
    public int insertRole(Role role);
}

实现类:

@Service
public class RoleListServiceimpl implements RoleListService {
    @Autowired
    private RoleService roleService=null;
    Logger log=Logger.getLogger(RoleListService.class);

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
    public int insertRoleList(List<Role> roleList)
    {
        int count=0;
        for (Role role : roleList) {
            try{
                count+=roleService.insertRole(role);
            }catch (Exception e){
                log.info(e);
            }
        }
        return count;
    }
}
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper=null;

    @Transactional(propagation = Propagation.REQUIRES_NEW,isolation = Isolation.READ_COMMITTED)
    public int insertRole(Role role) {
        return roleMapper.insertRole(role);
    }
}

在两个实现类方法中添加了@Transactional,设置了隔离等级和传播行为


设置日志配置文件

在resources下创建log4j.properties文件,且配置如下:

log4j.rootLogger=DEBUG , stdout
log4j.logger.org.springframework=DEBUG
log4j . appender.stdout=org . apache . log4j . ConsoleAppender
log4j.appender.stdout . layout=org . apache.log4j.PatternLayout
log4j.appender.stdout . layout.ConversionPattern=%5p %d %C: %m%n

测试

package com.ssm.main;

import com.ssm.pojo.Role;
import com.ssm.service.RoleListService;
import com.ssm.service.impl.RoleListServiceimpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {

        ApplicationContext ctx=new ClassPathXmlApplicationContext("spring/tm01.xml");

        RoleListService roleListService=ctx.getBean(RoleListService.class);
        List<Role> roleList=new ArrayList<Role>();
        for (int i = 1; i <= 2; i++) {
            Role role=new Role();
            role.setRoleName("role_name"+i);
            role.setNote("note_"+i);
            roleList.add(role);
        }
        int count=roleListService.insertRoleList(roleList);
        System.out.println(count);
    }
}
Role role=new Role();
            role.setRoleName("role_name"+i);
            role.setNote("note_"+i);
            roleList.add(role);
        }
        int count=roleListService.insertRoleList(roleList);
        System.out.println(count);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值