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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fightingXia/article/details/82534664

##概述

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也更加便捷。

猜你喜欢

转载自blog.csdn.net/fightingXia/article/details/82534664