MyBatis简介
MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。它支持定制化SQL、存储过程、高级映射及缓存。是一个轻量级的持久层框架。
目前主流的持久层框架还是Mybatis、Hibernate及JDBC Template,这些持久层框架各有利弊。
一、MyBatis注解版(Annotation)
注解版本可以优雅的去除配置文件,并和springboot集成实现零配置。
1.springboot集成mybatis,增加maven依赖
代码语言:javascript复制<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
2.配置Mybatis数据源,application.properties文件添加配置信息
springboot默认读取spring.datasource.xxx属性,初始化DataSource并自动注入sqlSessionFactory
代码语言:javascript复制mybatis.type-aliases-package=com.lianjinsoft.pojo
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.15.128:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
3.springboot启动类,增加Mybatis扫描注解
代码语言:javascript复制@MapperScan("com.lianjinsoft.mapper")
@SpringBootApplication
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
4.增加pojo数据表映射类(部分代码)
代码语言:javascript复制public class Order {
private Integer id;
private String orderNo;
private String orderName;
private BigDecimal amount;
private Date addTime;
public Order(){}
public Order(String orderNo, String orderName, BigDecimal amount){
this.orderNo = orderNo;
this.orderName = orderName;
this.amount = amount;
this.addTime = new Date();
}
}
5.增加Mapper数据持久层操作方法
去掉sql配置文件,其实就是将sql语句转移到了Class文件中
代码语言:javascript复制public interface OrderMapper {
@Insert("INSERT INTO orders(order_no,order_name,amount,add_time) "
"VALUES(#{orderNo}, #{orderName}, #{amount}, #{addTime})")
void addOrder(Order order);
@Delete("DELETE FROM orders WHERE id=#{id}")
void delOrder(Integer id);
@Update("UPDATE orders SET order_name=#{orderName} WHERE id=#{id}")
void updOrder(Order order);
@Select("SELECT * FROM orders")
@Results({
@Result(property = "orderNo", column = "order_no"),
@Result(property = "orderName", column = "order_name"),
@Result(property = "addTime", column = "add_time"),
})
List<Order> queryOrders();
@Select("SELECT * FROM orders WHERE order_no=#{orderNo}")
@Results({
@Result(property = "orderNo", column = "order_no"),
@Result(property = "orderName", column = "order_name"),
@Result(property = "addTime", column = "add_time"),
})
Order queryOrderByNo(String orderNo);
}
6.增加TestCase,通过Junit测试
代码语言:javascript复制@RunWith(SpringRunner.class)
@SpringBootTest
public class OrderMapperTests {
@Autowired
private OrderMapper orderMapper;
@Test
public void test1_Add() {
orderMapper.addOrder(new Order("100001", "XX手机Plus 全面屏", new BigDecimal("4999")));
}
@Test
public void test2_Query() {
Order order = orderMapper.queryOrderByNo("100001");
Assert.assertNotNull(order);
}
@Test
public void test3_QueryOrders() {
Assert.assertEquals(1, orderMapper.queryOrders().size());
}
@Test
public void test4_Upd() {
Order order = orderMapper.queryOrderByNo("100001");
order.setOrderName("三星S8 全面屏");
orderMapper.updOrder(order);
}
@Test
public void test5_Del() {
orderMapper.delOrder(orderMapper.queryOrders().get(0).getId());
Assert.assertEquals(0, orderMapper.queryOrders().size());
}
}
7.执行TestCase中的方法,验证Mybatis持久层方法是否正确
Demo中的TestCase有依赖关系,请按照测试方法的前后顺序分别执行Test方法。
8.验证通过,编写Controller
代码语言:javascript复制@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderMapper orderMapper;
@RequestMapping("/add")
public String addOrder(Order order){
order.setAddTime(new Date());
orderMapper.addOrder(order);
return "add success!";
}
@RequestMapping("/update")
public String updOrder(Order order){
orderMapper.updOrder(order);
return "update success!";
}
@RequestMapping("/query")
public Order queryOrder(String orderNo){
return orderMapper.queryOrderByNo(orderNo);
}
@RequestMapping("/queryAll")
public List<Order> queryAll(){
return orderMapper.queryOrders();
}
@RequestMapping("/delete")
public String delOrder(Integer id){
orderMapper.delOrder(id);
return "delete success!";
}
}
Mybatis注解版本:
优点:去除了配置文件,实现代码统一管理。
缺点:增加了Java代码的维护难度,不方便编写sql,可视化程度低。
源代码:https://gitee.com/skychenjiajun/spring-boot