整合MyBatis操作
https://github.com/mybatis
SpringBoot官方的Starter:spring-boot-starter-*
第三方的: *-spring-boot-starter
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
# 配置mybatis规则
mybatis:
config-location: classpath:mybatis/mybatis-config.xml #全局配置文件位置
mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件位置
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 由于Spring Boot自动配置缘故,此处不必配置,只用来做做样。-->
</configuration>
Mapper接口:
<?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.wenliang.admin.mapper.AccountMapper">
<select id="getAcct" resultType="com.wenliang.admin.bean.Account">
select * from account where id=#{id}
</select>
</mapper>
@Mapper
public interface AccountMapper {
public Account getAcct(Integer id);
}
@Data
public class Account {
private Integer id ;
private String name;
private Double money;
}
@Service
public class AccountService {
@Autowired
AccountMapper accountMapper;
public Account getAccountId(Integer id) {
return accountMapper.getAcct(id);
}
}
@ResponseBody
@GetMapping("account")
public Account getById(@RequestParam("id") Integer id){
return accountService.getAccountId(id);
}
小结
- 导入MyBatis官方Starter。
- 编写Mapper接口,需@Mapper注解。
- 编写SQL映射文件并绑定Mapper接口。
- 在application.yaml中指定Mapper配置文件的所处位置,以及指定全局配置文件的信息 (建议:配置在mybatis.configuration)。