上篇文章《springboot集成mybatis(一)》介绍了SpringBoot集成MyBatis注解版。本文还是使用上篇中的案例,咱们换个姿势来一遍^_^
二、MyBatis配置版(XML)
配置版本应该是大家最熟悉的一套。用过ibatis的朋友都知道,大部分工作量都在xml文件里面。通过标签可以组合出各种复杂的sql。
Mybatis为我们简化了Dao层的代码,直接通过接口映射配置文件中的sql。
1.集成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文件添加配置信息
mybatis.type-aliases-package=com.lianjinsoft.pojo
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.15.129: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 MybatisXmlApplication { public static void main(String[] args) {
SpringApplication.run(MybatisXmlApplication.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数据持久层操作方法
public interface OrderMapper {
List<Order> queryOrders(); Order queryOrderByNo(String orderNo); void addOrder(Order order); void delOrder(Integer id); void updOrder(Order order);
}
6.增加Mybatis主配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
7.增加Mapper对应的配置文件及sql
<?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.lianjinsoft.mapper.OrderMapper" >
<resultMap id="BaseResultMap" type="com.lianjinsoft.pojo.Order" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="order_no" property="orderNo" jdbcType="VARCHAR" />
<result column="order_name" property="orderName" jdbcType="VARCHAR" />
<result column="amount" property="amount" jdbcType="DECIMAL"/>
<result column="add_time" property="addTime" jdbcType="TIMESTAMP" />
</resultMap> <sql id="Base_Column_List" >
id, order_no, order_name, amount, add_time
</sql> <select id="queryOrders" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM orders
</select> <select id="queryOrderByNo" parameterType="java.lang.String" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM orders
WHERE order_no = #{orderNo}
</select> <insert id="addOrder" parameterType="com.lianjinsoft.pojo.Order" >
INSERT INTO orders
(order_no,order_name,amount,add_time)
VALUES
(#{orderNo}, #{orderName}, #{amount}, #{addTime})
</insert> <delete id="delOrder" parameterType="java.lang.Integer" >
DELETE FROM
orders
WHERE
id =#{id}
</delete> <update id="updOrder" parameterType="com.lianjinsoft.pojo.Order" >
UPDATE orders
SET order_name=#{orderName}
WHERE
id=#{id}
</update> </mapper>
8.增加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());
} }
9.执行TestCase中的方法,验证Mybatis持久层方法是否正确
Demo中的TestCase有依赖关系,请按照测试方法的前后顺序分别执行Test方法。
10.验证通过,编写Controller(按照传统三层结构应该先编写service,此处省略)
@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!";
} }
总结:
注解版本更符合springboot微服务设计思想,快速、简洁、零配置的开发模式。
配置版本更有怀旧情怀,如何你习惯了在配置文件中编写sql(特别是复杂的sql),那么配置版本更适合你。
源代码:https://gitee.com/skychenjiajun/spring-boot