- pom.xml
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.0
三、使用配置文件的方式
1. 准备工作
- 实体类
@Data
public class User {
@Id
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- UserMapper
@Mapper
public interface UserMapper {
public User getUser(String username);
}
- UserService
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User getUserByName(String username){
return userMapper.getUser(username);
}
}
2. 配置相应的xml
- 创建配置文件mybatis-config.xml,从 XML 中构建 SqlSessionFactory这里可以参考官网的说明 https://mybatis.org/mybatis-3/zh/getting-started.html.
- 创建UserMapper.xml,探究已映射的 SQL 语句
select * from User where username = #{username}
- 配置mybatis规则,application.yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
# url=jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username: root
password: 2550
driver-class-name: com.mysql.cj.jdbc.Driver
# 配置mybatis规则
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
3. 测试
@ResponseBody
@GetMapping("/user")
public User getUserByName(@RequestParam("username") String username) {
return userService.getUserByName(username);
}
四、使用注解
添加依赖 参考第二步
1. 数据准备- 创建一张表
- 创建实体类City
@Data
public class City {
private Long id;
private String name;
private String state;
private String country;
}
- 创建CityMapper
@Mapper
public interface CityMapper {
@Select("select * from city where id = #{id} ")
public City getById(Long id);
}
2. 测试方法
- 创建CityService
@Service
public class CityService {
@Autowired
CityMapper cityMapper;
public City getCityById(Long id) {
return cityMapper.getById(id);
}
}
- 测试方法
@Autowired
CityService cityService;
@ResponseBody
@GetMapping("/city")
public City getCityById(@RequestParam("id")Long id) {
return cityService.getCityById(id);
}
- 测试



