首先添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
添加完依赖之后,假设有一个实体类
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<User> 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();
}
}