Spring Boot 集成 Mybatis 注解方式
2022-11-21 本文已影响0人
Tinyspot
1. 注解方式
1.1 配置
mybatis:
configuration:
map-underscore-to-camel-case: true
# 打印sql
logging:
level:
com.concrete.boot.dao.mapper: DEBUG
1.2 Mapper 接口
@Mapper
public interface OrderDao {
@Select("select * from con_order")
List<Order> findAll();
@Select("select * from con_order where id = #{id}")
Order queryOrderById(@Param("id") Integer id);
}
1.3 启动类 @MapperScan
@SpringBootApplication(scanBasePackages = "com.example.conboot.starter")
@MapperScan(basePackages = "com.concrete.boot.dao.mapper")
public class ConbootStarterApplication {
public static void main(String[] args) {
SpringApplication.run(ConbootStarterApplication.class, args);
}
}
2. 其他注解
@Alias
3. Mybatis
3.1 resultType vs resultMap
3.2 # vs $
4. 分页助手
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.5</version>
</dependency>
@Slf4j
@RestController
public class DaoController {
@Resource
private OrderDao orderDao;
@RequestMapping("/order/list")
public String queryOrders() {
List<Order> orders = orderDao.findAll();
return JSON.toJSONString(orders);
}
@RequestMapping("/order/list/{page}")
public String queryOrdersByPage(@PathVariable Integer page) {
// 1. 分页
PageHelper.startPage(page, 3);
// 2. 查询
List<Order> orders = orderDao.findAll();
// 3. 封装PageInfo
PageInfo<Order> pageInfo = new PageInfo<>(orders);
// 4. 输出 pageInfo.getList()
return JSON.toJSONString(pageInfo.getList());
}
}
请求地址:http://localhost:8080/order/list/1
5. 注解和 xml 混用
既有注解又有 xml 配置时,不要配置 mybatis-config.xml, 单独配置mapper.xml
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.concrete.boot.dao.entity
configuration:
map-underscore-to-camel-case: true