SpringBoot
是为了简化 Spring
应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程
MyBatis
是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射,几乎避免了所有的 JDBC 代码和手动设置参数以及获取结果集,使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录,在国内可谓是占据了半壁江山……
ORM对比图 以下针对Spring JDBC
、Spring Data Jpa
、Mybatis
三款框架做了个粗略的对比。一般应用的性能瓶颈并不是在于ORM,所以这三个框架技术选型应该考虑项目的场景
、团队的技能掌握情况
、开发周期(开发效率)
…
框架对比
Spring JDBC
Spring Data Jpa
Mybatis
性能
性能最好
性能最差
居中
代码量
多
少
多
学习成本
低
高
居中
推荐指数
❤❤❤
❤❤❤❤❤
❤❤❤❤❤
个人观点
抛开学习成本而言,对于业务简单的中小型项目中使用Spring Data Jpa
开发无异于是最快速的。但是鉴于国内市场环境而言,掌握Mybatis
无异于是佳的选择,低学习成本和动态SQL解耦的特点使得更容易被人们所接受。对于业务复杂且对性能要求较高的项目来说Mybatis
往往能更好的胜任,可以自己进行SQL优化,同时更让我喜欢的是Mybatis分页插件 与通用Mapper(单表CURD无需自己手写) 有了这两款插件的支持,还有什么理由拒绝Mybatis
呢
导入依赖 在 pom.xml
中添加 Mybatis
的依赖包mybatis-spring-boot-starter
,该包拥有自动装配的特点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <dependency > <groupId > org.mybatis.spring.boot</groupId > <artifactId > mybatis-spring-boot-starter</artifactId > <version > 1.3.2</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-test</artifactId > <scope > test</scope > </dependency >
连接数据库 与SpringDataJpa
、Spring JDBC
一样,需要在application.properties
中添加数据源的配置,同时也需要添加对mybatis
的配置
1 2 3 4 5 6 7 8 9 spring.datasource.url=jdbc:mysql://localhost:3306/chapter6?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false spring.datasource.password=root spring.datasource.username=root mybatis.mapper-locations=classpath:com/battcn/mapper/*.xml mybatis.type-aliases-package=com.battcn.entity mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.map-underscore-to-camel-case
是一个非常好的配置项,合理的命名规范可以让我们省略很多不必要的麻烦,比如xx-mapper.xml中的resultMap
的映射可以省略掉了
注意事项
由于 mybatis.mapper-locations=classpath:com/battcn/mapper/*.xml
配置的在java package
中,而Spring Boot
默认只打入java package -> *.java
,所以我们需要给pom.xml
文件添加如下内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <build > <resources > <resource > <directory > src/main/resources</directory > </resource > <resource > <directory > src/main/java</directory > <includes > <include > **/*.xml</include > </includes > <filtering > true</filtering > </resource > </resources > <plugins > <plugin > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-maven-plugin</artifactId > </plugin > </plugins > </build >
具体编码 完成基本配置后,接下来进行具体的编码操作。
表结构 创建一张 t_user
的表
1 2 3 4 5 6 CREATE TABLE `t_user` ( `id` int (8 ) NOT NULL AUTO_INCREMENT COMMENT '主键自增' , `username` varchar (50 ) NOT NULL COMMENT '用户名' , `password` varchar (50 ) NOT NULL COMMENT '密码' , PRIMARY KEY (`id` ) ) ENGINE =InnoDB DEFAULT CHARSET =utf8 COMMENT ='用户表' ;
实体类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.battcn.entity;import java.io.Serializable;public class User implements Serializable { private static final long serialVersionUID = 8655851615465363473L ; private Long id; private String username; private String password; }
持久层 这里提供了两种方式操作接口,第一种带@Select
注解的是Mybatis3.x
提供的新特性,同理它还有@Update
、@Delete
、@Insert
等等一系列注解 ,第二种就是传统方式了,写个接口映射,然后在XML中写上我们的SQL语句…
UserMapper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package com.battcn.mapper;import com.battcn.entity.User;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;import java.util.List;@Mapper public interface UserMapper { @Select ("SELECT * FROM t_user WHERE username = #{username}" ) List<User> findByUsername (@Param("username" ) String username) ; int insert (User user) ; }
UserMapper
映射文件
1 2 3 4 5 6 7 8 9 <?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.battcn.mapper.UserMapper" > <insert id ="insert" parameterType ="com.battcn.entity.User" > INSERT INTO `t_user`(`username`,`password`) VALUES (#{username},#{password}) </insert > </mapper >
测试 完成数据访问层接口后,最后编写一个junit
测试类来检验代码的正确性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package com.battcn;import com.battcn.entity.User;import com.battcn.mapper.UserMapper;import org.junit.Test;import org.junit.runner.RunWith;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith (SpringRunner.class)@SpringBootTest public class Chapter6ApplicationTests { private static final Logger log = LoggerFactory.getLogger(Chapter6ApplicationTests.class); @Autowired private UserMapper userMapper; @Test public void test1 () throws Exception { final int row1 = userMapper.insert(new User("u1" , "p1" )); log.info("[添加结果] - [{}]" , row1); final int row2 = userMapper.insert(new User("u2" , "p2" )); log.info("[添加结果] - [{}]" , row2); final int row3 = userMapper.insert(new User("u1" , "p3" )); log.info("[添加结果] - [{}]" , row3); final List<User> u1 = userMapper.findByUsername("u1" ); log.info("[根据用户名查询] - [{}]" , u1); } }
总结 更多Mybatis
的骚操作,请参考官方文档
目前很多大佬都写过关于 SpringBoot
的教程了,如有雷同,请多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE
编写,包括新版本的特性都会一起介绍…
说点什么
个人QQ:1837307557
battcn开源群(适合新手):391619659
微信公众号(欢迎调戏):battcn
个人博客:http://blog.battcn.com/
全文代码:https://github.com/battcn/spring-boot2-learning/tree/master/chapter6