Springboot整合Mybatis

在項(xiàng)目的技術(shù)選型中,持久層框架常用的有Hibernate/JPA,Mybatis,JDBC等等,雖然之前特別喜歡JPA的簡(jiǎn)潔強(qiáng)大,但是在一些項(xiàng)目上還是必須得使用Mybatis這個(gè)小巧,面向SQL的持久層框架,結(jié)合Springboot,將之前的技術(shù)融合到新技術(shù)中,所以寫(xiě)了這個(gè)測(cè)試demo,該測(cè)試只單獨(dú)寫(xiě)了持久層,不包含web和業(yè)務(wù)層代碼,即整合了springboot和mybatis后,再加一個(gè)單元測(cè)試。

測(cè)試一 「完全注解形式」

1.pom.xml 配置文件中引入 mybatis-spring-boot-starter ,支持mybatis相關(guān)

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.1</version>
</dependency>

2.項(xiàng)目的父工程為 spring-boot-starter-parent , 這是springboot項(xiàng)目必須的。

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/>
</parent>

3.該測(cè)試數(shù)據(jù)庫(kù)使用Mysql,因此也需要引入mysql驅(qū)動(dòng)jar包。

 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

4.創(chuàng)建Mapper接口,使用注解配置SQL和方法之間的關(guān)系,接口如下:

public interface UserMapper {
    
    @Select( "select * from user" )
    @Results( {
              @Result( property = "uid", column = "id" ),
              @Result( property = "username", column = "name" )
          } )
    /**查找全部用戶(hù)信息*/
    public List<User> findAll();

    
    @Insert( "insert into user values (null,#{username},#{age})" )
    /**添加用戶(hù)信息*/
    public void inser( User user );


    @Delete( "delete from user where id = #{value}" )
    /**根據(jù) id 刪除用戶(hù)信息*/
    public void delete( Integer uid );
}

說(shuō)明:

  • @Result : 為了測(cè)試使用,我的實(shí)體類(lèi)User與數(shù)據(jù)庫(kù)user表列不一樣,即當(dāng)屬性和列名不一致時(shí),需要指明property和 column之間的映射關(guān)系,根據(jù)業(yè)務(wù)需要還可以配置所對(duì)應(yīng)的javaType,jdbcType(數(shù)據(jù)庫(kù)對(duì)應(yīng)類(lèi)型),多對(duì)一和一對(duì) 一等其他復(fù)雜映射,具體可參見(jiàn)XML配置中的ResultMap,它們其實(shí)本質(zhì)相同。
  • 其他配置項(xiàng)可根據(jù)XML配置等推測(cè)該注解的所能表示的功能,不細(xì)述。

5.編寫(xiě)單元測(cè)試

@RunWith( SpringRunner.class )
@SpringBootTest
/* 這里是在Spring初始化是提供Mapper所在包,該注解放在程序入口即可 */
@MapperScan( "cn.myxinge.mapper" )
public class BootDemoMybatisApplicationTests {
    /* 注入mapper */
    @Autowired
    private UserMapper userMapper;


    /**測(cè)試mybatis配置是否完成*/
    @Test
    public void contextLoads()
    {
        List<User> users = userMapper.findAll();
        System.out.println( users );
        /* ---------------------------- */
        User user = new User();
        user.setUsername( "這是測(cè)試數(shù)據(jù) Name" );
        user.setAge( 100 );
        /* userMapper.inser(user); */

        /* ------------ */
        userMapper.delete( 10 );
    }
}

6.測(cè)試結(jié)束,此時(shí)可以進(jìn)行簡(jiǎn)單增刪改查。

測(cè)試二 「XML配置文件形式」

1.使用XML配置文件形式整合Mybatis和Springboot,思路和注解方式基本一致,結(jié)合之前Spring+Mybatis配置的方式,我們需要思考的點(diǎn)在于:

a. 告訴spring mybatis的config配置文件位置;

b. 告訴spring mybatis的mappper配置文件位置;

c. 寫(xiě)接口mapper

d. 注入,使用。

現(xiàn)在開(kāi)始相關(guān)配置

2.在 application.propertis 中添加配置

mybatis.config-location=classpath:mybatis/sqlMapConfig.xml
mybatis.mapper-locations=classpath:mapper/*.xml

3.編寫(xiě) sqlMapConfig.xml

<?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>
</configuration>

4.編寫(xiě)Mapper接口

/**使用xml配置的Mapper*/
public interface UserMapperByXML {
    /**查找全部用戶(hù)信息*/
    public List<User> findAll();


    /**添加用戶(hù)信息*/
    public void inser( User user );


    /**根據(jù) id 刪除用戶(hù)信息*/
    public void delete( Integer uid );
}

5.編寫(xiě)UserMapper.xml

 
<?xml version="1.0" encoding="utf8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.myxinge.mapper.UserMapperByXML">
        
     <resultMap id="userMap" type="cn.myxinge.pojo.User">
         <id property="uid" column="id" jdbcType="BIGINT"></id>
         <result property="username" column="name" jdbcType="VARCHAR"></result>
         <result property="age" column="age" jdbcType="BIGINT"></result>
     </resultMap>
        
     <select id="findAll" resultMap="userMap">
          SELECT * FROM user
     </select>
            
     <insert id="inser" parameterType="cn.myxinge.pojo.User">
          insert into user values (null,#{username},#{age})
     </insert>
        
     <delete id="delete" parameterType="java.lang.Integer">
          delete from user where id = #{value}
     </delete>
</mapper>

6.開(kāi)始測(cè)試,測(cè)試代碼和上述的注解形式開(kāi)發(fā)無(wú)多少區(qū)別,這里就不貼出來(lái)了,如需源碼,下面會(huì)有該項(xiàng)目的GitHub地址。


總結(jié):

該demo結(jié)合了Springboot和Mybatis,使用注解形式和xml配置形式搭建了最簡(jiǎn)易的持久層代碼實(shí)現(xiàn),出于本人也在 學(xué)習(xí)中,該測(cè)試也是自己做的筆記,所以將很多東西都簡(jiǎn)單化,沒(méi)有真正深入,比如Mybatis的一些配置細(xì)節(jié),數(shù)據(jù)庫(kù)連接池的配置,緩存等等,如果哪里有錯(cuò)誤或需要修改地方,可以留言給我,感謝。

name.png

Demo源代碼地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 摘要: 原創(chuàng)出處:www.bysocket.com 泥瓦匠BYSocket 希望轉(zhuǎn)載,保留摘要,謝謝! 推薦一本書(shū)...
    子木聊出海閱讀 5,237評(píng)論 6 66
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評(píng)論 19 139
  • 在spring中,構(gòu)建一個(gè)項(xiàng)目,最麻煩也最容易出錯(cuò)的莫過(guò)于各種xml文件的配置,即使是一個(gè)簡(jiǎn)單的demo也需要花費(fèi)...
    竹凳子閱讀 12,637評(píng)論 0 8
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,272評(píng)論 6 342
  • 平凡我是不甘于如此的。在許川遇見(jiàn)最美的臺(tái)灣的邂逅中,我看到了平凡是最快樂(lè)的生活態(tài)度。他們并沒(méi)有追著宏大的事業(yè)跑,卻...
    云中君的風(fēng)閱讀 246評(píng)論 0 1

友情鏈接更多精彩內(nèi)容