目录
一、整合mybatis
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
1.1、配置模式
改yml配置文件
#配置mybatis规则
mybatis:
# config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
@Data
public class TUser {
private Integer id;
private String userName;
}
@Mapper
public interface TUserMapper {
TUser getTUser(Integer id);
}
@Service
public class CityService {
@Autowired
private CityMapper cityMapper;
public City getCityById(Long id){
return cityMapper.getCityById(id);
}
}
<?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的UserMapper相对应-->
<mapper namespace="com.cjc.boot.mapper.TUserMapper">
<!--这里的id要与mapper接口中方法名相同-->
<select id="getTUser" resultType="com.cjc.boot.bean.TUser">
select * from t_user where id=#{id}
</select>
</mapper>
@GetMapping("/getTUser")
@ResponseBody
public TUser getTUser(@RequestParam("id") Integer id){
return tUserService.getTUser(id);
}
1.2、注解模式
@Data
public class City {
private Long id;
private String name;
private String state;
private String country;
}
@Mapper
public interface CityMapper {
@Select("select * from city where id=#{id}")
public City getCityById(Long id);
}
@Service
public class CityService {
@Autowired
private CityMapper cityMapper;
public City getCityById(Long id){
return cityMapper.getCityById(id);
}
}
@ResponseBody
@GetMapping("/getCityById")
public City getCityById(@RequestParam("id") Long id){
return cityService.getCityById(id);
}