MyBatis框架(五)之在SpringBoot中集成MyBatis

##概述

SpringBoot依然是java項目的主流,下面以實際項目爲例說明在SpringBoot項目中使用MyBatis框架。

##準備工作

在使用JDBC連接數據庫之前,首先要有數據庫,數據庫要創建表。我的數據庫信息如下:

  1. 數據庫類型:MySql。
  2. 數據庫名字:xia。
  3. 用戶名:root。
  4. 密碼:root.
  5. 創建數據庫表student。
create table student(
       id int primary key auto_increment,
       name varchar(20),
       age int
);

##開發環境

  1. 操作系統:MACOS。
  2. 開發工具:IntelliJ IDEA。
  3. Java版本:jdk1.8。
  4. 使用maven管理jar包。

##正式開發

開發完成後的項目目錄結構如下:

從文件數量上看使用SpringBoot比使用Spring框架就簡單的多。

一,在pom.xml文件中引入需要jar的依賴

<!-- springboot依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.4.RELEASE</version>
        </dependency>

        <!-- mysql驅動依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <!-- 數據連接池,此時使用druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>

        <!-- mybatis數據庫依賴 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

二,創建application.yml文件

在resources目錄下創建application.yml文件,這是springBoot項目的全局配置文件,數據庫參數和mybatis配置都在這兒,如下:

# 服務器配置
server:
  port: 8081
  servlet:
    path: /

spring:
# mysql數據庫配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    #url,username,password動態配置
    url: jdbc:mysql://localhost:3306/xia?useUnicode=true&autoReconnect=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root


# mybatis配置
mybatis:
  #config-location
  type-aliases-package: com.honor.springbootmybatis.model
  mapper-locations: classpath:/mapper/*.xml

 

三,創建model類

在com.honor.springbootmybatis.model包中創建StudentModel類,字段與student表對應。代碼如下:

public class StudentModel {
    private int id;
    private String name;
    private int age;
 
    //get和set方法略
}

四,創建Dao接口

在SpringBoot項目中創建dao接口即可,在接口中聲明的方法名與mapper文件中sql的id保持一致,具體如下:

@Component
public interface StudentDao {
    // 新增
    int insert(StudentModel t);

    // 更新
    int update(StudentModel t);

    // 刪除
    int delete(int id);


    // 查詢一個
    StudentModel queryOne(int id);

    //查詢列表
    List<StudentModel> queryList(StudentModel t);

    // 查詢命中個數
    int queryCount(StudentModel t);

}

 

五,創建Mapper文件

在resources/mapper目錄下創建student表對應的mapper文件,起名爲studentMapper.xml。在該文件中寫sql語句,內容如下:

<?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">
<!--聲明命名空間,此時必須是dao類的全類名-->
<mapper namespace="com.honor.springbootmybatis.dao.StudentDao">

    <!--定義resultMap-->
    <resultMap id="BaseResultMap" type="studentModel">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="name" jdbcType="VARCHAR" property="name"/>
        <result column="age" jdbcType="VARCHAR" property="age"/>
    </resultMap>

    <!--將所有字段定義爲一個sql片段-->
    <sql id="Base_Column_List">
        id, name, age
    </sql>

    <!--所有字段的動態where,供查詢list和查詢數量使用。-->
    <sql id="Base_Where">
        <where>
            <if test="name!=null and name.length()>0">
                AND name=#{name}
            </if>
            <if test="age > 0">
                AND age=#{age}
            </if>
        </where>
    </sql>

    <!--插入數據,並返回id-->
    <insert id="insert" parameterType="studentModel" useGeneratedKeys="true" keyProperty="id">
        insert into student (name,age)
        values(#{name,jdbcType=VARCHAR},#{age,jdbcType=INTEGER})
    </insert>

    <!--根據id查找一條數據-->
    <select id="queryOne" parameterType="int" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from student WHERE id=#{id}
    </select>

    <!--根據name和age查找數據集合-->
    <select id="queryList" parameterType="studentModel" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from student
        <include refid="Base_Where"/>
    </select>

    <!--查詢梳理-->
    <select id="queryCount" parameterType="studentModel" resultType="int">
        SELECT COUNT(*) FROM student
        <include refid="Base_Where"/>
    </select>

    <!--根據id更新-->
    <update id="update" parameterType="studentModel">
        UPDATE student
        <set>
            <if test="name!=null and name.length()>0">
                name= #{name},
            </if>
            <if test="age>0">
                age = #{age},
            </if>
        </set>
        WHERE id = #{id}
    </update>
    <!--根據id刪除-->
    <delete id="delete" parameterType="studentModel">
        DELETE from student WHERE id = #{id}
    </delete>
</mapper>

六,在springBoot項目啓動類上添加MapperScan註解

dao類是接口,接口是不能創建對象的,所以必須將dao類指定爲Mapper類時才能被spring創建對象。

將dao類指定爲Mapper對象有兩種方法,一種是在dao接口上添加@Mapper註解,另外一種是在SpringBoot啓動類上添加Mapper類的掃描包。第二種方法如下:

@SpringBootApplication
@MapperScan("com.honor.springbootmybatis.dao")
public class SpringbootmybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootmybatisApplication.class, args);
    }
}

七,測試

此時使用controller提供接口測試,代碼如下:

@RestController
public class StudentController {

    @Autowired
    StudentDao studentDao;

    @RequestMapping("/get.do")
    public StudentModel get(){
        return studentDao.queryOne(5);
    }
}

測試結果如下:

大功告成!

##總結

SpringBoot簡化了很多Spring的配置,所以在SpringBoot項目中使用MyBatis也更加便捷。

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章