Spring Boot Mybatis Tutorial

Mybatis in the moment of Internet development environment is very important. This chapter focuses on how to use Mybatis.

From the start of this series, we need to use mysql database and other reference databases. Please prepare the relevant links. This chapter requires the following environment support:

  • mysql 5.6+
  • jdk1.8 +
  • spring boot 2.1.6
  • idea 2018.1

The project source code download

1 Prepare the database

Database tutorial series are using the same data as in the tutorial Spring Boot JDBC as the use of

Field Types of Primary key Explanation
id int Yes auto numbering
user_name varchar(100) no username
password varchar(255) no password
last_login_time date no Recently logged time
sex tinyint no Sex 0 male and 1 female 2 Other

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `last_login_time` datetime DEFAULT NULL,
  `sex` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=armscii8;

-- ----------------------------
-- Records of t_user
-- ----------------------------
BEGIN;
INSERT INTO `t_user` VALUES (1, 'json', '123', '2019-07-27 16:01:21', 1);
INSERT INTO `t_user` VALUES (2, 'jack jo', '123', '2019-07-24 16:01:37', 1);
INSERT INTO `t_user` VALUES (3, 'manistal', '123', '2019-07-24 16:01:37', 1);
INSERT INTO `t_user` VALUES (4, 'landengdeng', '123', '2019-07-24 16:01:37', 1);
INSERT INTO `t_user` VALUES (5, 'max', '123', '2019-07-24 16:01:37', 1);
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

2 New Spring Boot project

  1. File> New> Project, select the figure below Spring Initializrand then click [Next] Next
  2. Fill GroupId(package name), Artifact(project name) can be. Click Next
    groupId = com.fishpro
    artifactId = the mybatis
  3. The choice depends Spring Web Starterin front of the tick, tick SQL options mybatis, mysql.
  4. Project name is set spring-boot-study-mybatis.

3 configuration dependent incorporated Pom.xml

In the new construction of the time, if you choose Mybatisdepend on, you do not need to be configured separately, the following are all dependent on the project.

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3 Mybatis project configuration application.yml

Whether it is jdbcor mybatisneeds to be configured for the data source, and configuration items is the same. In addition to basic data source configuration, we also need to configure mybatisthe mapping of the * .xml file path, mybatisindependent of config.xmlfile paths.

  • mapper-locationsConfigure the entity with the database table mapping xml file location, we configured /src/main/resource/mybatis/**maper.xmlunder
  • map-underscore-to-camel-case Open mybatis hump naming
  • type-aliases-packageDesignated entity domainclass, which is com.fishproall to domainthe entity classes ending.
server:
  port: 8086
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: mybatis/**/*Mapper.xml
  type-aliases-package: com.fishpro.**.domain

For mybatis configuration, we can put all mybatis Configuration to a separate config file.

5 writing sample code

Here we first use the three-layer structure of this project to demonstrate that the controller-service-dao-mapper-mybatis

mybatis three-tier structure example

This example includes a new page

  1. src/main/java/com/fishpro/mybatis/controller/UserController.java 控制层 rest api
  2. src / main / java / com / fishpro / mybatis / domain / UserDO.java entity object
  3. src / main / java / com / fishpro / mybatis / dao / UserDao.java Dao database access layer
  4. src / main / java / com / fishpro / mybatis / service / UserService.java service layer interface comprises interface +
  5. src / main / java / com / fishpro / mybatis / service / impl / UserServiceImpl.java service layer interface comprises interface +
  6. src / main / resources / mybatis / UserMapper.xml mapping xml file

5.1 mapping file UserMapper.xml

UserMapper.xml is a xml mapping file to mybatis syntax to write.

+ mapper 节点是根节点 具有属性 namespace 表示 mapper 对应的 java 的 Dao 接口类
  |--select 查询节点
    |--where
    |--choose
        |--when
        |--otherwise
  |--insert 插入节点
  |--update 更新节点
  |--delete 删除节点

Following detailed code

<?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.fishpro.mybatis.dao.UserDao">
    <select id="get" resultType="com.fishpro.mybatis.domain.UserDO">
        select `id`,`user_name`,`password`,`last_login_time`,`sex` from t_user where id = #{value}
    </select>
    <select id="list" resultType="com.fishpro.mybatis.domain.UserDO">
        select `id`,`user_name`,`password`,`last_login_time`,`sex` from t_user
        <where>
            <if test="id != null   and id != '-1' " > and id = #{id} </if>
            <if test="userName != null  and userName != '' " > and user_name = #{userName} </if>
            <if test="password != null  and password != '' " > and password = #{password} </if>
            <if test="lastLoginTime != null  and lastLoginTime != '' " > and last_login_time = #{lastLoginTime} </if>
            <if test="sex != null   and sex != '-1' " > and sex = #{sex} </if>
        </where>
        <choose>
            <when test="sort != null and sort.trim() != ''">
                order by ${sort} ${order}
            </when>
            <otherwise>
                order by id desc
            </otherwise>
        </choose>
        <if test="offset != null and limit != null">
            limit #{offset}, #{limit}
        </if>
    </select>
    <select id="count" resultType="int">
        select count(*) from t_user
        <where>
            <if test="id != null   and id != '-1'  " > and id = #{id} </if>
            <if test="userName != null  and userName != ''  " > and user_name = #{userName} </if>
            <if test="password != null  and password != ''  " > and password = #{password} </if>
            <if test="lastLoginTime != null  and lastLoginTime != ''  " > and last_login_time = #{lastLoginTime} </if>
            <if test="sex != null   and sex != '-1'  " > and sex = #{sex} </if>
        </where>
    </select>
    <insert id="save" parameterType="com.fishpro.mybatis.domain.UserDO" useGeneratedKeys="true" keyProperty="id">
        insert into t_user
        (
            `user_name`,
            `password`,
            `last_login_time`,
            `sex`
        )
        values
        (
            #{userName},
            #{password},
            #{lastLoginTime},
            #{sex}
        )
    </insert>
    <update id="update" parameterType="com.fishpro.mybatis.domain.UserDO">
        update t_user
        <set>
            <if test="userName != null">`user_name` = #{userName}, </if>
            <if test="password != null">`password` = #{password}, </if>
            <if test="lastLoginTime != null">`last_login_time` = #{lastLoginTime}, </if>
            <if test="sex != null">`sex` = #{sex}</if>
        </set>
        where id = #{id}
    </update>
    <delete id="remove">
        delete from t_user where id = #{value}
    </delete>

    <delete id="batchRemove">
        delete from t_user where id in
        <foreach item="id" collection="array" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>
</mapper>

5.2 entity object UserDO

With the corresponding database table (customizable) class object entity


public class UserDO {
    private Integer id;
    private String userName;
    private String password;
    private Integer sex;
    private Date lastLoginTime;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getLastLoginTime() {
        return lastLoginTime;
    }

    public void setLastLoginTime(Date lastLoginTime) {
        this.lastLoginTime = lastLoginTime;
    }
}

5.3 database access layer UserDao

Dao is an interface layer, the interface method corresponding to mybatis / id value at node Mapper.xml in Mapper **. The above example <select id="get" resultType="com.fishpro.mybatis.domain.UserDO">then the corresponding interface methodUserDO get(Integer id)

Dao must use @Mappger notes, in order to achieve the mapping from Dao to Mapper.xml


/**
 * 数据库访问层 用户Dao t_user
 * @author fishpro
 */
@Mapper
public interface UserDao {
    /**
     * 对应节点 select id="get" resultType="com.fishpro.mybatis.domain.UserDO"
     * */
    UserDO get(Integer id);
    /**
     * 对应节点 select id="list" resultType="com.fishpro.mybatis.domain.UserDO"
     * */
    List<UserDO> list(Map<String, Object> map);
    /**
     * 对应节点 select id="count" resultType="int"
     * */
    int count(Map<String, Object> map);
    /**
     * 对应节点 insert id="save" parameterType="com.fishpro.mybatis.domain.UserDO" useGeneratedKeys="true" keyProperty="id"
     * */
    int save(UserDO user);
    /**
     * 对应节点 update id="update" parameterType="com.fishpro.mybatis.domain.UserDO"
     * */
    int update(UserDO user);
    /**
     * 对应节点 delete id="remove"
     * */
    int remove(Integer id);
    /**
     * 对应节点 delete id="batchRemove"
     * */
    int batchRemove(Integer[] ids);
}

5.4 Service class UseService

Note UserServiceImpl @Service annotations must use in order to achieve UserService type of automatic injection function
in the present example simply CRUD function
UserService Interfaces

public interface UserService {

    UserDO get(Integer id);

    List<UserDO> list(Map<String, Object> map);

    int count(Map<String, Object> map);

    int save(UserDO user);

    int update(UserDO user);

    int remove(Integer id);

    int batchRemove(Integer[] ids);
}

UserServiceImpl implementation class


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    
    @Override
    public UserDO get(Integer id){
        return userDao.get(id);
    }
    
    @Override
    public List<UserDO> list(Map<String, Object> map){
        return userDao.list(map);
    }
    
    @Override
    public int count(Map<String, Object> map){
        return userDao.count(map);
    }
    
    @Override
    public int save(UserDO user){
        return userDao.save(user);
    }
    
    @Override
    public int update(UserDO user){
        return userDao.update(user);
    }
    
    @Override
    public int remove(Integer id){
        return userDao.remove(id);
    }
    
    @Override
    public int batchRemove(Integer[] ids){
        return userDao.batchRemove(ids);
    }
    
}

5.5 Control Frame Rest Api CRUD interfaces UserController

Write This code uses the standard style Restful specific code is as follows:


/**
 * RESTful API + Mybatis 风格示例 对资源 user 进行操作
 * 本示例没有使用数据库,也没有使用 service 类来辅助完成,所有操作在本类中完成
 * 请注意几天
 *    1.RESTful 风格使用 HttpStatus 状态返回 GET PUT PATCH DELETE 通常返回 201 Create ,DELETE 还有时候返回 204 No Content
 *    2.使用 RESTful 一定是要求具有幂等性,GET PUT PATCH DELETE 本身具有幂等性,但 POST 不具备,无论规则如何定义幂等性,需要根据业务来设计幂等性
 *    3.RESTful 不是神丹妙药,实际应根据实际情况来设计接口
 * */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 测试用 参数为 name
     * */
    @RequestMapping("/hello")
    public String hello(String name){
        return "Hello "+name;
    }

    /**
     * SELECT 查询操作,返回一个JSON数组
     * 具有幂等性
     * */
    @GetMapping("/users")
    @ResponseStatus(HttpStatus.OK)
    public Object getUsers(){

        return userService.list(new HashMap<>());
    }

    /**
     * SELECT 查询操作,返回一个新建的JSON对象
     * 具有幂等性
     * */
    @GetMapping("/users/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Object getUser(@PathVariable("id") String id){

        if(null==id){
            return  null;
        }
        return userService.get(Integer.valueOf(id));
    }

    /**
     * 新增一个用户对象
     * 非幂等
     * 返回 201 HttpStatus.CREATED 对创建新资源的 POST 操作进行响应。应该带着指向新资源地址的 Location 头
     * */
    @PostMapping("/users")
    @ResponseStatus(HttpStatus.CREATED)
    public Object addUser(@RequestBody UserDO user){
        if(user.getId()==0){
            return null;
        }
        userService.save(user);
        return user;
    }

    /**
     * 编辑一个用户对象
     * 幂等性
     * */
    @PutMapping("/users/{id}")
    @ResponseStatus(HttpStatus.CREATED)
    public Object editUser(@PathVariable("id") String id, @RequestBody UserDO user){

        userService.update(user);
        return user;
    }

    /**
     * 删除一个用户对象
     * 幂等性
     * 返回 HttpStatus.NO_CONTENT 表示无返回内容
     * */
    @DeleteMapping("/users/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@PathVariable("id") String id){
        userService.remove(Integer.valueOf(id));
    }
}

Example 6 runs

Right MybatisApplication> Run MybatisApplicationinput in the browserhttp://localhost:8086/api/user/users

Use PostMan testing tools to test GET \ POST \ PUT \ DELETE action Restful api

mybatis query for all users

Consideration about 7

  1. How to automatically generate code
  2. How to dynamically configure the data source
  3. How to divide the table and warehouses
  4. Xml detailed syntax by which pits
  5. xml good or comment
  6. How to solve the Transaction Processing
  7. How to deal with things expanding library

The next section uses annotations to achieve our demo

The project source code download

Guess you like

Origin www.cnblogs.com/fishpro/p/spring-boot-study-mybatis.html