springboot使用Mybatis(xml和注解)全解析

2021/5/7 10:28:14

本文主要是介绍springboot使用Mybatis(xml和注解)全解析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

刚毕业的第一份工作是 java 开发,项目中需要用到 mybatis,特此记录学习过程,这只是一个简单 demo,mybatis 用法很多不可能全部写出来,有更复杂的需求建议查看 mybatis 的官方中文文档,地址:

http://www.mybatis.org/mybatis-3/zh/index.html

。下面时项目环境/版本。

  • 开发工具:IDEA

  • jdk 版本:1.8

  • springboot 版本:2.03

其他依赖版本见下面 pom.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  3.         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  4.    <modelVersion>4.0.0</modelVersion>


  5.    <groupId>com.example</groupId>

  6.    <artifactId>mybatis-test</artifactId>

  7.    <version>0.0.1-SNAPSHOT</version>

  8.    <packaging>jar</packaging>


  9.    <name>mybatis-test</name>

  10.    <description>Demo project for Spring Boot</description>


  11.    <parent>

  12.        <groupId>org.springframework.boot</groupId>

  13.        <artifactId>spring-boot-starter-parent</artifactId>

  14.        <version>2.0.3.RELEASE</version>

  15.        <relativePath/> <!-- lookup parent from repository -->

  16.    </parent>


  17.    <properties>

  18.        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  19.        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

  20.        <java.version>1.8</java.version>

  21.    </properties>


  22.    <dependencies>

  23.        <dependency>

  24.            <groupId>org.springframework.boot</groupId>

  25.            <artifactId>spring-boot-starter-web</artifactId>

  26.        </dependency>

  27.        <dependency>

  28.            <groupId>mysql</groupId>

  29.            <artifactId>mysql-connector-java</artifactId>

  30.            <scope>runtime</scope>

  31.        </dependency>

  32.        <!--mybatis依赖 -->

  33.        <dependency>

  34.            <groupId>org.mybatis.spring.boot</groupId>

  35.            <artifactId>mybatis-spring-boot-starter</artifactId>

  36.            <version>1.3.2</version>

  37.        </dependency>

  38.        <!--alibaba连接池依赖-->

  39.        <dependency>

  40.            <groupId>com.alibaba</groupId>

  41.            <artifactId>druid-spring-boot-starter</artifactId>

  42.            <version>1.1.9</version>

  43.        </dependency>

  44.        <!--分页依赖-->

  45.        <dependency>

  46.            <groupId>com.github.pagehelper</groupId>

  47.            <artifactId>pagehelper-spring-boot-starter</artifactId>

  48.            <version>1.2.5</version>

  49.        </dependency>

  50.        <dependency>

  51.            <groupId>org.springframework.boot</groupId>

  52.            <artifactId>spring-boot-starter-test</artifactId>

  53.            <scope>test</scope>

  54.        </dependency>

  55.    </dependencies>


  56.    <build>

  57.        <plugins>

  58.            <plugin>

  59.                <groupId>org.springframework.boot</groupId>

  60.                <artifactId>spring-boot-maven-plugin</artifactId>

  61.            </plugin>

  62.        </plugins>

  63.    </build>

  64. </project>

1.创建项目

使用 idea 中的 spring initializr 生成 maven 项目,项目命令为 mybatis-test,选择 web,mysql,mybatis 依赖,即可成功。(详细过程不赘述,如有需要学习 springboot 创建过程,可参考这篇文章,地址:

http://tapme.top/blog/detail/2018-08-13-10-38


然后依照上面的 pom 文件,补齐缺少的依赖。接着创建包 entity,service 和 mybatis 映射文件夹 mapper,创建。为了方便配置将 application.properties 改成 application.yml。由于我们时 REST 接口,故不需要 static 和 templates 目录。修改完毕后的项目结构如下:

  修改启动类,增加 @MapperScan("com.example.mybatistest.dao"),以自动扫描 dao 目录,避免每个 dao 都手动加 @Mapper注解。代码如下:

@SpringBootApplication@MapperScan("com.example.mybatistest.dao")public class MybatisTestApplication {    public static void main(String[] args) {        SpringApplication.run(MybatisTestApplication.class, args);    }}

修改 application.yml,配置项目,代码如下:

  1. mybatis:

  2.  #对应实体类路径

  3.  type-aliases-package: com.example.mybatistest.entity

  4.  #对应mapper映射文件路径

  5.  mapper-locations: classpath:mapper/*.xml


  6. #pagehelper物理分页配置

  7. pagehelper:

  8.  helper-dialect: mysql

  9.  reasonable: true

  10.  support-methods-arguments: true

  11.  params: count=countSql

  12.  returnPageInfo: check


  13. server:

  14.  port: 8081


  15. spring:

  16.  datasource:

  17.    name: mysqlTest

  18.    type: com.alibaba.druid.pool.DruidDataSource

  19.    #druid连接池相关配置

  20.    druid:

  21.      #监控拦截统计的filters

  22.      filters: stat

  23.      driver-class-name: com.mysql.jdbc.Driver

  24.      url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true

  25.      username: root

  26.      password: 123456

  27.      #配置初始化大小,最小,最大

  28.      initial-size: 1

  29.      min-idle: 1

  30.      max-active: 20

  31.      #获取连接等待超时时间

  32.      max-wait: 6000

  33.      #间隔多久检测一次需要关闭的空闲连接

  34.      time-between-eviction-runs-millis: 60000

  35.      #一个连接在池中的最小生存时间

  36.      min-evictable-idle-time-millis: 300000

  37.      #打开PSCache,并指定每个连接上PSCache的大小。oracle设置为true,mysql设置为false。分库分表设置较多推荐设置

  38.      pool-prepared-statements: false

  39.      max-pool-prepared-statement-per-connection-size: 20

  40.  http:

  41.    encoding:

  42.      charset: utf-8

  43.      enabled: true

2.编写代码

首先创建数据表,sql 语句如下:

CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `name` varchar(255) NOT NULL,  `age` tinyint(4) NOT NULL DEFAULT '0',  `password` varchar(255) NOT NULL DEFAULT '123456',  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

然后在 entity 包中创建实体类 User.java

  1. public class User {

  2.    private int id;

  3.    private String name;

  4.    private int age;

  5.    private String password;


  6.    public User(int id, String name, int age, String password) {

  7.        this.id = id;

  8.        this.name = name;

  9.        this.age = age;

  10.        this.password = password;

  11.    }

  12.    public User(){}

  13.    //getter setter自行添加

  14. }

在 dao 包下创建 UserDao.java

public interface UserDao {    //插入用户    int insert(User user);    //根据id查询    User selectById(String id);    //查询所有    List<User> selectAll();}

在 mapper 文件夹下创建 UserMapper.xml,具体的 xml 编写方法查看文首的官方文档。

  1. <?xml version="1.0" encoding="utf-8" ?>

  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

  3. <mapper namespace="com.example.mybatistest.dao.UserDao">

  4.    <sql id="BASE_TABLE">

  5.        user

  6.    </sql>

  7.    <sql id="BASE_COLUMN">

  8.        id,name,age,password

  9.    </sql>


  10.    <insert id="insert" parameterType="com.example.mybatistest.entity.User" useGeneratedKeys="true" keyProperty="id">

  11.        INSERT INTO <include refid="BASE_TABLE"/>

  12.        <trim prefix="(" suffix=")" suffixOverrides=",">

  13.            name,password,

  14.            <if test="age!=null">

  15.                age

  16.            </if>

  17.        </trim>

  18.        <trim prefix=" VALUE(" suffix=")" suffixOverrides=",">

  19.            #{name,jdbcType=VARCHAR},#{password},

  20.            <if test="age!=null">

  21.                #{age}

  22.            </if>

  23.        </trim>

  24.    </insert>


  25.    <select id="selectById" resultType="com.example.mybatistest.entity.User">

  26.        select

  27.          <include refid="BASE_COLUMN"/>

  28.        from

  29.          <include refid="BASE_TABLE"/>

  30.        where id=#{id}

  31.    </select>


  32.    <select id="selectAll" resultType="com.example.mybatistest.entity.User">

  33.        select

  34.          <include refid="BASE_COLUMN"/>

  35.        from

  36.          <include refid="BASE_TABLE"/>

  37.    </select>

  38. </mapper>

至此使用 mybatis 的代码编写完了,之后要用时调用 dao 接口中的方法即可。

3.测试

我们通过编写 service,controller 然后使用 postman 进行测试。

首先编写 UserService.java,代码如下:

  1. @Component

  2. public class UserService {


  3.    @Autowired

  4.    private UserDao userDao;


  5.    public User getByUserId(String id){

  6.        return userDao.selectById(id);

  7.    }

  8.    //获取全部用户

  9.    public List<User> getAll(){

  10.        return userDao.selectAll();

  11.    }

  12.    //测试分页

  13.    public PageInfo<User> getAll(int pageNum,int pageSize){

  14.        PageHelper.startPage(pageNum,pageSize);

  15.        List<User> users = userDao.selectAll();

  16.        System.out.println(users.size());

  17.        PageInfo<User> result = new PageInfo<>(users);

  18.        return result;

  19.    }


  20.    public int insert(User user){

  21.        return userDao.insert(user);

  22.    }


  23. }

编写 UserController.java

  1. @RestController

  2. public class UserController {


  3.    @Autowired

  4.    private UserService userService;


  5.    @GetMapping("/user/{userId}")

  6.    public User getUser(@PathVariable String userId){

  7.        return userService.getByUserId(userId);

  8.    }


  9.    @GetMapping("/user")

  10.    public List<User> getAll(){

  11.        return userService.getAll();

  12.    }


  13.    @GetMapping("/user/page/{pageNum}")

  14.    public Object getPage(@PathVariable int pageNum,

  15.                          @RequestParam(name = "pageSize",required = false,defaultValue = "10") int pageSize){

  16.        return userService.getAll(pageNum,pageSize);

  17.    }


  18.    @PostMapping("/user")

  19.    public Object addOne(User user){

  20.        userService.insert(user);

  21.        return user;

  22.    }

  23. }

启动项目,通过 postman 进行请求测试,测试结果如下:

  • 插入数据:

图片

  • 查询数据

图片

  • 分页查询

图片

4.注解编写 sql

上面使用的是 xml 方式编写 sql 代码,其实 mybatis 也支持在注解中编写 sql,这样可以避免编写复杂的 xml 查询文件,但同时也将 sql 语句耦合到了代码中,也不易实现复杂查询,因此多用于简单 sql 语句的编写。

要使用注解首先将 applicaton.yml 配置文件中的 mapper-locations:classpath:mapper/*.xml注释掉。然后在 UserDao.java 中加入 sql 注解,代码如下:

public interface UserDao {    //插入用户    @Insert("insert into user(name,age,password) value(#{name},#{age},#{password})")    @Options(useGeneratedKeys=true,keyColumn="id",keyProperty="id")    int insert(User user);    //根据id查询    @Select("select * from user where id=#{id}")    User selectById(String id);    //查询所有    @Select("select * from user")    List<User> selectAll();}

然后重新启动项目测试,测试结果跟上面完全一样。




这篇关于springboot使用Mybatis(xml和注解)全解析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程