记录SpringBoot整合MyBatis(实现动态SQL)

首先添加依赖


    org.springframework.boot
    spring-boot-starter-web


    mysql
    mysql-connector-java


    org.mybatis.spring.boot
    mybatis-spring-boot-starter

添加完依赖之后,假设有一个实体类User,其内部存在id、username、password、group四个属性

首先在application.yml内部添加上数据源的信息:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/demo_db?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

Mapper类:

package cn.demo.user.mapper;

@Repository
public interface UserMapper{

    @Select("select * from user")
    List findAllUser();

    @Select("select * from user where id = #{id}")
    User findOneUser1(Long id);

    @Select("select * from user where username = #{username} and password = #{password}")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "username", column = "username"),
        @Result(property = "password", column = "password"),
        @Result(property = "group", column = "group")
    })  // 当有多个参数时,注意要加上“@Param”注解,必要时还要添加上“@Results”注解
    User findOneUser2(@Param("username") String username, @Param("password") String password);
}

启动类:注意使用“@MapperScan”注解

@SpringBootApplication
@MapperScan("cn.demo.user.mapper")
public class UserApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

此时,就可以在业务层注入UserMapper执行对应的方法了

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User findOneUser(String username, String password) {
        return this.userMapper.findOneUser2(username, password);
    }
}

实现动态SQL语句

要实现动态的SQL语句,则需要在原有基础上在创建一个新的动态SQL类

public class UserProvider {

    public String findUserById(Long id) {
        return new SQL() {{
            SELECT("*");
            FROM("user");
            if (id%2 == 1) {
                WHERE("");
            } else {
                WHERE("1=2");
            }
        }}.toString();
    }
}

你可能感兴趣的:(记录SpringBoot整合MyBatis(实现动态SQL))