Basic usage of MyBatis framework


foreword

I have learned some excellent back-end program development frameworks such as Spring, Spring Boot, and Spring MVC before, but for complete back-end development, the database is essential, and the MyBatis I learned today is an excellent persistence layer framework. It is an easier tool to complete the interaction between the program and the database, and it is also an easier tool to operate and read the database.


1. What is MyBatis?

MyBatis is a persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. Primitive types, interfaces, etc. can be configured and mapped through simple XML or annotations.

2. Create a MyBatis project

1. Add dependencies

New or old projects need to add the following dependencies:
insert image description here

2. Configure database information

The program must be connected to the database in order to run without error.

insert image description here

3. Configure the xml path in mybatis

insert image description here

3. Add, delete, check and modify

1. Query operation

Query users by id.

(1) Create an entity class.
insert image description here

(2) Construct the code implementation of the Mapper layer (interface + XML)
a. Create an interface;
insert image description here

b. Create an XML implementation.

insert image description here
(3) Realize the service layer

@Service
public class UserService {
    
    
    @Autowired
    private UserMapper userMapper;
    public Userinfo getUserById(Integer id) {
    
    
        return userMapper.getUserById(id);
    }
}

(4) Realize the controller

@RestController
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private UserService userService;
    @RequestMapping("/get-user-id")
    public Userinfo getUserById(Integer id) {
    
    
        if (id == null) return null;
        return userService.getUserById(id);
    }
}

insert image description here

Perform unit tests:
generate unit tests directly in the mapper with shortcut keys (Alt+Insert).
insert image description here
Unit test code:

    @Autowired
    private UserMapper userMapper;
    @Test
    void getUserById() {
    
    
        Userinfo userinfo = userMapper.getUserById(1);
        System.out.println(userinfo);
    }

query all users

(1) Configuration in xml.

    <select id="getAll" resultType="com.example.demo.entity.Userinfo">
        select * from userinfo
    </select>

(2) TEST.

    //查询所有用户信息
    @Test
    void getAll() {
    
    
        List<Userinfo> list = userMapper.getAll();
        Assertions.assertEquals(3,list.size());
    }

2. Add operation

Add user

(1) Declare the method in the interface.

    //添加操作
    int add(Userinfo userinfo);

(2) Provide implementation in xxx.xml.

    <insert id="add">
        insert into userinfo(username,password,createtime,updatetime)
        values(#{
    
    username},#{
    
    password},#{
    
    createtime},#{
    
    updatetime})
    </insert>

(3) Detection (unit test).

    @Test
    void add() {
    
    
        //伪代码,构建一个对象
        Userinfo userinfo = new Userinfo();
        userinfo.setUsername("张三");
        userinfo.setPassword("123");
        userinfo.setCreatetime(LocalDateTime.now());
        userinfo.setUpdatetime(LocalDateTime.now());
        //执行添加操作
        int result = userMapper.add(userinfo);
        System.out.println(result);
        Assertions.assertEquals(1,result);
    }

Add and return the user's auto-increment id

useGeneratedKey, keyProperty: the attributes of the entity class in the program, not the fields of the database.
The key is the implementation in xml.

    <insert id="addGetId" useGeneratedKeys="true" keyProperty="id">
        insert into userinfo(username,password,createtime,updatetime)
        values(#{
    
    username},#{
    
    password},#{
    
    createtime},#{
    
    updatetime})
    </insert>

3. Modify operation

(1) Modify the interface.

    //修改用户
    int upUserName(Userinfo userinfo);

(2) xml configuration.

    <update id="upUserName">
        update userinfo set username=#{
    
    username} where id=#{
    
    id}
    </update>

(3) TEST.

@Test
    void upUserName() {
    
    
        Userinfo userinfo = new Userinfo();
        userinfo.setId(5);
        userinfo.setUsername("陈尔尔");
        int result = userMapper.upUserName(userinfo);
        System.out.println(result);
    }

4. Delete operation

(1) interface.

    //删除根据Id
    int delById(@Param("id") Integer id);

(2) xml configuration.

    <delete id="delById">
        delete from userinfo where id=#{
    
    id}
    </delete>

(3) TEST.

    @Test
    void delById() {
    
    
        Integer id = 6;
        int result = userMapper.delById(id);
        System.out.println(result);
    }

@Transactional

Test without actually modifying the values ​​in the database.

4. Precautions and common operations

1. The difference between # and ¥

#{}: Precompilation processing.
${}: character direct replacement.

Direct replacement may lead to unauthorized query and operation of the database. But there are some aspects that are needed, such as using ¥{sort} to implement sorting, fuzzy query and other scenarios that require direct injection.

    <select id="getUserByDesc" resultType="com.example.demo.entity.Userinfo">
        select * from userinfo order by id ${
    
    order}
    </select>

Differences:
(1) ¥ has the problem of SQL injection, but # does not exist;
(2) ¥ is a direct replacement, # is preprocessing.

2. SQI injection problem

SQL injection can query the database information by modifying the SQL statement, for example, as long as the condition after where (1=1) is true, the database information can be queried.

3. resultMap usage

Usage scenario: Realize the function of mapping the attributes in the program and the fields in the table (when the attributes in the program and the fields in the table are inconsistent, they can be forcibly mapped together).

    <resultMap id="baseMap" type="com.example.demo.entity.Userinfo">
        <id column="id" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="photo" property="photo"></result>
        <result column="createtime" property="createtime"></result>
        <result column="updatetime" property="updatetime"></result>
        <result column="state" property="state"></result>
    </resultMap>

The solution when the attributes in the program and the field names in the database are inconsistent:
(1) Use the resultMap tag (defined in mapper.xml);
(2) Use the database alias as to rename.

4. Fuzzy query

The most important thing is to configure xml.
There are two ways to write SQL.

    <select id="findUserByName" resultType="com.example.demo.entity.Userinfo">
    <!-- 模糊查询有两种写法 -->
    <!--        select * from userinfo where username like '%${
    
    username}%'-->
        select * from userinfo where username like concat('%',#{
    
    username},'%')
    </select>

5. Multi-table joint query

(1) One-to-one
user article information and user name with id 1.

    <select id="getArticleById" resultType="com.example.demo.entity.vo.ArticleinfoVO">
        select a.*,u.username from articleinfo as a left join userinfo as u on a.id = u.id where a.id=#{
    
    id}
    </select>

(2) One-to-many.
All articles of user with id 1.

    <select id="getArticleById" resultType="com.example.demo.entity.vo.Articleinfo">
        select * from articleinfo where id=#{
    
    id}
    </select>

The final implementation: join table query statement (left join/inner join) + XXXVO

6. Dynamic SQL

(1) label

    <!-- 使用if标签添加  -->
    <insert id="add2">
        insert into userinfo(username,
        <if test="photo!=null">
            photo,
        </if>
        password)
        values(#{
    
    username},
        <if test="photo!=null">
            #{
    
    photo},
        </if>
        #{
    
    password})
    </insert>

(2) label

prefix: the first fixed value;
suffix: the last fixed value;
suffixOverrides: the last value to be overridden.

    <!-- 使用if trim标签添加  -->
    <insert id="add2">
        insert into userinfo
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null">
                username,
            </if>
            <if test="password!=null">
                password,
            </if>
            <if test="photo!=null">
                photo
            </if>
        </trim>
        <trim prefix="values(" suffix=")" suffixOverrides=",">
            <if test="username!=null">
                #{
    
    username},
            </if>
            <if test="password!=null">
                #{
    
    password},
            </if>
            <if test="photo!=null">
                #{
    
    photo}
            </if>
        </trim>
    </insert>

(3) label

Features:
1. where tags are usually used together with if tags;
2. where tags will delete the first and keywords (note that the last will not be deleted);
3. if there is no content in where tags, then it will not be generated where sql keyword.

    <!-- <where>标签 -->
    <select id="getListByParam" resultType="com.example.demo.entity.Userinfo">
        select * from userinfo
        <where>
            <if test="username!=null">
                username=#{
    
    username}
            </if>
            <if test="password!=null">
                and password=#{
    
    password}
            </if>
        </where>
    </select>

(4), label

    <update id="setById">
        update userinfo
        <set>
            <if test="username!=null">
                username=#{
    
    username}
            </if>
        </set>
        <where>
            <if test="id!=null">
                id=#{
    
    id}
            </if>
        </where>

(6)

collection is the collection of settings. (data to be deleted)
open is the start.
close is the end.
item is the data in the collection.
separator is the separator of the data in the collection.

    <!-- <foreach>标签   -->
    <delete id="dels">
        delete from userinfo where id in
        <foreach collection="ids" open="(" close=")" item="id" separator=",">
            #{
    
    id}
        </foreach>
    </delete>

Guess you like

Origin blog.csdn.net/qq_45283185/article/details/129460572