Mybatis 注解方式使用动态SQL

Posted passerbywl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis 注解方式使用动态SQL相关的知识,希望对你有一定的参考价值。

Mybatis 使用注解方式使用动态 SQL 时。需要使用 <script></script> 将 SQL 语句包裹起来,否则无法使用。

引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.liyananbest</groupId>
    <artifactId>write-learn</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>write-learn</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <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.3</version>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

在主配置文件加上 mysql 和 mybatis 的配置

# 配置数据源
spring.datasource.url=jdbc:mysql://localhost:3306/write-learn?serverTimezone=GMT&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
# mysql 8.0 以上需要使用 com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# 配置 mybatis
# 配置驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true

创建表及数据

CREATE TABLE `account`
(
    `id` BIGINT COMMENT \'主键\' PRIMARY KEY auto_increment,
    `account_name` VARCHAR(90) COMMENT \'账户名\',
    `create_user` VARCHAR(90) COMMENT \'创建用户\',
    `create_time` datetime COMMENT \'创建时间\',
    `last_edit_time` datetime COMMENT \'最后修改时间\'
)

INSERT INTO `account` (`id`, `account_name`, `create_user`,  `create_time`, `last_edit_time`)
VALUES
(NULL, \'账户1\', \'admin\', now(), now()),
(NULL, \'账户2\', \'admin\', now(), now()),
(NULL, \'账户3\', \'admin\', now(), now());

image-20210321235212839

创建 Account

package com.liyananbest.writelearn.entity;

import lombok.Builder;
import lombok.Data;
import lombok.experimental.Tolerate;

/**
 * @author liyanan
 * @date 2021 年 03 月 21 日 23:26
 */
@Builder
@Data
public class Account {
    /**
     * 主键
     */
    private Long id;
    /**
     * 账户名
     */
    private String accountName;
    /**
     * 创建用户
     */
    private String createUser;
    /**
     * 创建时间
     */
    private String createTime;
    /**
     * 最后修改时间
     */
    private String lastEditTime;

    @Tolerate
    public Account() {
    }
}

创建 Mapper

package com.liyananbest.writelearn.mapper;

import com.liyananbest.writelearn.entity.Account;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 账户相关 Mapper
 * @author liyanan
 * @date 2021 年 03 月 21 日 23:37
 */
public interface AccountMapper {
    /**
     * 获取账户表所有信息
     * @author liyanan
     * @date 2021/3/21 23:38
     * @return java.util.List<com.liyananbest.writelearn.entity.Account>
     */
    @Select("<script>" +
            "select `id`, `account_name` from account " +
            "where " +
            "<if test=\'id != null\'>"+
            "id = #{id}"+
            "</if>"+
            "</script>")
    List<Account> selectByCondition(Account account);
}

做单元测试

package com.liyananbest.writelearn.mapper;

import com.liyananbest.writelearn.entity.Account;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class AccountMapperTest {

    @Resource
    private AccountMapper accountMapper;

    @Test
    void selectByCondition() {
        List<Account> accounts = accountMapper.selectByCondition(Account.builder().id(1L).build());
        assertEquals(1, accounts.size());
        assertEquals("账户1", accounts.get(0).getAccountName());
    }
}

发现成功通过,说明动态SQL已经成功了。

以上是关于Mybatis 注解方式使用动态SQL的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis中的动态SQL

[mybatis]动态sql_sql_抽取可重用的sql片段

学习MyBatis必知必会~注解开发动态SQL

mybatis的注解开发之三种动态sql

142. Spring Boot MyBatis升级篇-注解-动态SQL(if test)-方案二:@Provider

推荐学java——MyBatis高级