springboot集成mybatis(一)

MyBatis简介

MyBatis本是apache的一个开源项目iBatis, 2010年之路由apache software
foundation迁移至了google
code,并且改名为MyBatis。它支持定制化SQL、存储过程、高级映射及缓存。是一个轻量级的持久层框架。

眼下主流的持久层框架或Mybatis、Hibernate及JDBC
Template,这些持久层框架各有利弊。

 

一、MyBatis注解版(Annotation)

诠释版本可以优雅的勾配置文件,并跟springboot集成实现零配置。

 

1.springboot集成mybatis,增加maven依赖

<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

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扫描注解

@MapperScan("com.lianjinsoft.mapper")
@SpringBootApplication
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

 

4.多pojo数据表映射类(部分代码)

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文件中

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测试

@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

MyBatis 1MyBatis 2

@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!";
    }
}

View Code

 

Mybatis注解版本:

亮点:去除了配备文件,实现代码统一管理。

短:增加了Java代码的保护难度,不便利编写sql,可视化程度低。

 

源代码:https://gitee.com/skychenjiajun/spring-boot

 

网站地图xml地图