Bootstrap

实验报告4-MyBatis与Spring的整合

资料下载链接

实验报告4-MyBatis与Spring的整合

一、需求分析

        实现Spring和MyBatis整合,使用基于XML方式实现声明式事务,完成service层批量插入数据功能并验证事物管理。

二、编码实现

1、数据库环境

        mybatis数据库,t_employee表

2、新建项目

        引入pom.xml文件,导入applicationContext.xml、db.properties、log4j.properties、mybatisConfig.xml

3、数据封装类

        com.sw.pojo包,Employee类

@Data
public class Employee {
    private int id;
    private String name;
    private int age;
    private String position;
}
4、mapper层

        com.sw.mapper包,EmployeeMapper接口

public interface EmployeeMapper {
    int insertOne(Employee employee);
}

        com/sw/mapper目录,EmployeeMapper.xml文件

    <insert id="insertOne" parameterType="com.sw.pojo.Employee">
        insert into t_employee set name=#{name},age=#{age},position=#{position}
    </insert>
5、配置Spring

        resources目录,applicationContext.xml

1)配置数据源
    <!--引入属性文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${mysql.driver}"/>
        <property name="url" value="${mysql.url}"/>
        <property name="username" value="${mysql.username}"/>
        <property name="password" value="${mysql.password}"/>
    </bean>
2)配置SqlSessionFactory
    <!--配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--加载MyBatis配置文件-->
        <property name="configLocation" value="classpath:mybatisConfig.xml"/>
    </bean>
3)配置Mapper扫描器
    <!--配置Mapper扫描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定要扫描的mapper的包-->
        <property name="basePackage" value="com.sw.mapper"/>
    </bean>
4)配置Spring IOC容器的注解扫描
    <!--配置Spring IOC容器的注解扫描-->
    <context:component-scan base-package="com.sw"/>
6、测试Spring和MyBatis整合

        com.sw.mapper包,EmployeeMapper类的insertOne方法,右键→Generate→Test

    private EmployeeMapper employeeMapper;
​
    @Before
    public void setUp() throws Exception {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        employeeMapper = applicationContext.getBean("employeeMapper", EmployeeMapper.class);
    }
​
    @Test
    public void insertOne() {
        Employee employee = new Employee();
        employee.setName("a1");
        employee.setAge(11);
        employee.setPosition("员工");
        int res = employeeService.insertOne(employee);
        if (res>0){
            System.out.println("新增一条数据成功");
        }else {
            System.out.println("新增一条数据失败");
        }
    }
7、service层

        com.sw.service包,EmployeeService接口

public interface EmployeeService {
    int insertList(List<Employee> employeeList);
}

        com.sw.service.impl包,EmployeeServiceImpl类

@Service
public class EmployeeServiceImpl implements EmployeeService {
​
    @Resource
    private EmployeeMapper employeeMapper;

    public int insertList(List<Employee> employeeList) {
        if (employeeList==null){
            return 0;
        }
        if (employeeList.size()==0){
            return 0;
        }
        for (int i = 0; i < employeeList.size(); i++) {
            if (i==1){
                throw new RuntimeException("模拟运行时异常");
            }
            employeeMapper.insertOne(employeeList.get(i));
        }
        return employeeList.size();
    }
}
8、配置Spring

        resources目录,applicationContext.xml

1)配置事务管理器
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
2)配置事务通知
    <!--配置事务通知-->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
3)配置AOP
    <!--配置AOP-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.sw.service.*.insert*(..))
        ||execution(* com.sw.service.*.update*(..))
        ||execution(* com.sw.service.*.delete*(..))
        ||execution(* com.sw.service.*.tx*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
9、测试事物管理

        com.sw.service.impl包,EmployeeServiceImpl类的insertList方法,右键→Generate→Test

    private EmployeeService employeeService;

    @Before
    public void setUp() throws Exception {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        employeeService = applicationContext.getBean("employeeServiceImpl", EmployeeService.class);
    }

    @Test
    public void insertList() {
        List<Employee> employeeList = new ArrayList<Employee>();
        Employee employee1 = new Employee();
        employee1.setName("a1");
        employee1.setAge(11);
        employee1.setPosition("员工");
        Employee employee2 = new Employee();
        employee2.setName("a2");
        employee2.setAge(22);
        employee2.setPosition("员工");
        Employee employee3 = new Employee();
        employee3.setName("a3");
        employee3.setAge(33);
        employee3.setPosition("员工");
        employeeList.add(employee1);
        employeeList.add(employee2);
        employeeList.add(employee3);
        int res = employeeService.insertList(employeeList);
        if (res>0){
            System.out.println("批量插入成功,共插入"+res+"条数据");
        }else {
            System.out.println("批量插入失败");
        }
    }

;