SpringBoot 集成MyBatis、事務管理


 

集成MyBatis

(1)在pom.xml中添加依賴

        <!-- mybatis的起步依賴。包含了mybatis、mybatis-spring、spring-jdbc(事務要用到)的坐標 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <!--這個必須要加版本號-->
            <version>2.1.1</version>
        </dependency>
        
        <!--mysql驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

 

 

(2)編寫實體類,包名常用model、domain

不需要在實體類上標@Component。

 

 

(3)新建包com.chy.mapper,編寫mapper接口。

@Mapper
public interface UserMapper{
    public User queryUserById(Integer id);
}

 在接口上標注@Mapper,不用標注@Repository。

 

 

(4)在resource下新建文件夾mapper,編寫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.chy.mapper.UserMapper">
    <select id="queryUserById" parameterType="Integer" resultType="user">
        select * from user_tb where id=#{id}
    </select>
</mapper>

注意namespace要和mapper接口對應。

springboot的src/java下只放java源文件,配置文件、靜態資源、映射文件都放到src/resources下。

 

 

sql語句也可以直接寫在mapper接口中:

@Mapper
public interface UserMapper{
    @Select("select * from user_tb where id=#{id}")
    public User queryUserById(@Param("id") Integer id);
}

@Param綁定占位符#{ }、${ }中的變量

@Select、@Update、@Insert、@Delete 、@Mapper 都是mabatis的注解,在普通mybatis中也可以用

只能寫簡單的sql語句,如果要使用resultmap映射結果集、關聯映射等復雜一點的,還是需要xml映射文件。

注解方式有點雞肋,現在主流還是xml映射文件方式

 

 

每次都需要在Mapper接口上標注@Mapper,很麻煩,可以直接在引導類上標注@MapperScan("com.chy.dao"),會自動把這個包下的接口都加上@Mapper注解。

如果要掃描|添加多個包,寫成String[ ],@MapperScan( { "包1" , "包2" } )。

注意是@MapperScan,不是@MapperScans,末尾沒有s。

 

 

 

(5)編寫service、controller

在service中使用@Autowired注入Mapper時,會報紅,實際上沒問題。

有強迫症不喜歡看紅色的,可以將@Autowired換為@Resource。

Spring官方推薦把@Autowired用來設值注入(寫在方法上),不推薦把@Autowired用來字段注入(直接寫在成員變量上)。

 

 

(6)在springboot的配置文件中配置數據庫、mybatis

#配置數據源,此處使用jdbc數據源、mysql數據庫
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/my_db?serverTimezone=GMT
spring.datasource.username=chy
spring.datasource.password=abcd
        
#配置mybatis
#配置實體類的別名
mybatis.type-aliases-package=com.chy.model
#指定映射文件的位置
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

注意:jdbc數據源、dbcp數據源、tomcat數據源使用的key是不同的。

 

 

 


 

 

 

集成Spring的事務管理

集成mybatis導入的依賴中已經包含了事務管理需要的依賴,所以不需要在pom.xml中再添加依賴,直接在service層要加事務的業務方法上標注@Transactional即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM