环境搭建
# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/book
spring.datasource.username=root
spring.datasource.password=12345
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
配置
UserMapper.xml
<?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.example.demo.mapper.UserMapper">
<select id="getUser" resultType="com.example.demo.bean.User">
select * from t_user where id=#{id}
</select>
<select id="listUser" resultType="com.example.demo.bean.User">
select * from t_user
</select>
</mapper>
UserService
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User getUserById(int id){
return userMapper.getUser(id);
}
}
UserMapper
public interface UserMapper {
public User getUser(int id);
public List<User> listUser();
}
MybatisController
@RestController
public class MybatisController {
@Autowired
UserService userService;
@GetMapping("/user")
public User getById(@RequestParam("id") int id){
return userService.getUserById(id);
}
}
注解
BookMapper
public interface BookMapper {
@Select("select * from t_book where id=#{id}")
public Book getBookById(int book);
}
|