1. 程式人生 > >spring boot整合mybatis以及事務的管理

spring boot整合mybatis以及事務的管理

1、整合mybatis。

2、事務管理

一、整合mybatis   

        備註:通過mapper.xml檔案來進行與資料庫的操作(sql語句靈活,較常使用)

一、整合mybatis

        1、引入jar包

<!-- mysql 資料庫驅動. -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- spring-boot 與 mybatis配置 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version><!-- 最新版本 -->
		</dependency>

        2、新建表 t_student,t_teacher

        

    3、建表格對應的實體類(set和get方法就不累述)

        

      4、建mapper介面對映xml。      

@Repository("stuDao")
public interface StudentMappper {
	
	public List<StudentEbo> listStu(@Param("name") String name);
	
	public StudentEbo getStuById(@Param("id") int id);
	
	public void addStu(StudentEbo stu);
	
}

    5、src/main/resources下新建mappers資料夾,新建studentMapper.xml檔案

<?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.hunqian.mapper.dao.StudentMappper">
	
	<resultMap type="com.hunqian.model.StudentEbo" id="StudentMap">
		<result property="id" column="id" jdbcType="INTEGER" javaType="Integer" />
		<result property="name" column="name" jdbcType="VARCHAR" javaType="String" />
		<result property="createTime" column="create_time" jdbcType="TIMESTAMP" javaType="java.sql.Timestamp" />
	</resultMap>
     
    <sql id="studentEboMap">
    	SELECT
			s.id,s.name,s.create_time
		FROM
			t_student AS s
    </sql> 
        
   <select id="getStuById" resultMap="StudentMap">
    	<include refid="studentEboMap"/>
    	<where>
    	1=1
    		<if test=" id > 0">
    			AND s.id = ${id}
    		</if>
    	</where>
    </select> 
        
	<select id="listStu" resultMap="StudentMap">
    	<include refid="studentEboMap"/>
    	<where>
    	1=1
    		<if test=" name != null and name != '' ">
    			AND s.name LIKE '%${name}%'
    		</if>
    	</where>
    </select> 
    
    <insert id="addStu" parameterType="com.hunqian.model.StudentEbo" useGeneratedKeys="true" keyProperty="id">
    	insert into t_student
    		(id,name,create_time)
    	value
    		(null,#{name},#{createTime})
    </insert>
	        
</mapper>

備註:此處注意mapper介面與實體類的路徑,必須與xml檔案中的一致。

6、配置application.properties檔案中新增資料庫連線的配置資訊。

spring.datasource.url = jdbc\:mysql\://localhost\:3306/******
spring.datasource.username = ****
spring.datasource.password = ******
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#spring.datasource.max-active=20
#spring.datasource.max-idle=8
#spring.datasource.min-idle=8
#spring.datasource.initial-size=10

mybatis.mapper-locations=classpath\:mappers/*.xml   

注意:資料庫的連線要與自己的意志

7、寫關於mapper介面的呼叫(注意此步也可省略,直接呼叫mapper介面,但本文按實際開發大致流程走,所以寫業務介面與實現)

    IStudentService.java

package com.hunqian.service;

import java.util.List;

import com.hunqian.model.StudentEbo;
import com.hunqian.model.TeacherEbo;

public interface IStudentService {

	public List<StudentEbo> listStu(String name);

	public StudentEbo getStuById(int id);
	
	public StudentEbo addStu(StudentEbo stu);

}

StudentService.java

package com.hunqian.service.impl;


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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hunqian.mapper.dao.StudentMappper;
import com.hunqian.model.StudentEbo;
import com.hunqian.model.TeacherEbo;
import com.hunqian.service.IStudentService;
import com.hunqian.service.ITeacherService;


@Service("stuService")
public class StudentService implements IStudentService {

	@Autowired
	private StudentMappper stuDao;
	@Autowired
	private ITeacherService tchServcie;
	
	public List<StudentEbo> listStu(String name){
		if(name == null || name.trim().length() == 0)
			return new ArrayList<StudentEbo>();
		return stuDao.listStu(name);
	}

	public StudentEbo getStuById(int id){
		if(id < 0)
			return null;
		return stuDao.getStuById(id);
	}
	
	public StudentEbo addStu(StudentEbo stu){
		stuDao.addStu(stu);
		return stu;
	}

}

8、啟動類啟動關於介面和mapper介面掃描

備註:關於註解@ComponentScan、@MapperScan的意思本文就不做累述,請自行查閱

@ComponentScan(basePackages="com.hunqian")
@MapperScan("com.hunqian.mapper")

9、啟動類新增測試

    1>bean注入StudentService類

@Autowired
	private IStudentService stuServcie;

    2>新增測試 

	@RequestMapping("addstu")
	public String addstu(){
		StudentEbo stu = new StudentEbo();
		stu.setName("魂牽");
		stu.setCreateTime(new Timestamp(System.currentTimeMillis()));
		StudentEbo s = stuServcie.addStu(stu);
		return s.toString();
	}
@RequestMapping("teststu")
	public String stu(){
		StudentEbo stu = stuServcie.getStuById(11);
		return stu.getName();
	}

10、執行結果

    


備註:這樣關於spring boot與mybatis的基本整合已經成功。

二、關於事務配置

        備註:測試事務標準 ,同時向兩張表中新增資料,若未配置事務,一張表資料添加出錯,另一張表仍然可新增成功。若配置事務,則會發生事務回滾,兩條資料均新增不成功。

       1、未配置事務

        按t_student的方式新增一張新表的對映操作(就不做累述)。

        本文新增t_teacher 表,以及相關的xml、mapper、service等

        

    IStudentServcie.java中新增

public String testTrans(StudentEbo stu,TeacherEbo tch);

    實現類StudentService.java中:

    注入TeacherService類

@Autowired
	private ITeacherService tchServcie;
實現方法testTrans
public String testTrans(StudentEbo stu,TeacherEbo tch){
		//新增老師
		tchServcie.addTch(tch);
		//新增學生
		stuDao.addStu(stu);
		return "新增成功";
	}

啟動類中新增測試:

@RequestMapping("addtran")
	public String addtran(){
		TeacherEbo t = new TeacherEbo();
		t.setName("與1111");
		t.setCreateTime(new Date());
		StudentEbo stu = new StudentEbo();
		stu.setCreateTime(new Timestamp(System.currentTimeMillis()));
		try {
			tchServcie.addTch(t);
			stuServcie.addStu(stu);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "新增tran";
	}

執行結果:雖然報錯,但t_teacher仍然新增資料成功。



2、配置事務

業務層方法上新增事務註解

備註:關於事務的詳細配置,請根據個人業務需要自行設定。

       

    啟動類中開啟事務  

@EnableTransactionManagement //開啟事務

    再次測試發現報錯兩條資料均不能新增成功。說明事務配置成功,發生的事務回滾。

github地址:https://github.com/hunqian/spring-boot-more-mybatis.git

本文僅限關於mybatis和事務的基本配置,詳細配置請根據自身框架和業務需要進一步完善。