SpringBoot2.X整合Mybatis实现增删改查(注解版)
在SpringBoot的官网好像没有找到mybatis的整合指南,可能是国外比较流行使用JPA吧,所以写下此文章来记录整合过程的记录,此过程包含简单的CRUD以及后面进阶的整合之前学过的Thymeleaf模板引擎,简单做了一个查询数据渲染页面,相关的源代码已上传到Github上,连接放在文章末尾
整合的项目目录结构
整合thymeleaf实现简单查询的页面
第一步导入pom.xml依赖:Mybatis和Mysql两个核心依赖,这里我额外导多一个lombok依赖(可选)
<!--mybatis依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <!--mysql依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
第二步编写application.yml配置文件,写上要连接的数据库的配置信息
spring: datasource: url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driverusername: root password: 123456
这里默认使用的SpringBoot内置的数据源,在2.0版本后使用的是
HikariDataSource这个数据源,mysql驱动在2.0版本后使用的mysql8.0驱动,对应的驱动为
com.mysql.cj.jdbc.Driver,还应注意连接的url要加上时区
serverTimezone=UTC,否则会报时区错误,除非你修改了mysql默认的时区
第三步创建数据库的表,按照配置是在test数据库下创建student表,下面试建表的sql
DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `age` int(11) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
第四步创建实体类Student映射到mysql的表student
@Data//使用这个注解就默认帮我们生成getter和setter以及toString等 @NoArgsConstructor //lombok生成无参数构造函数 public class Student { private Integer id; private String Name; private Integer age; }
这里就用到开头的导入的lombok依赖了,需要配合IDEA的lombok插件,目的就是简化实体类的getter和setter,constructor,toString方法的编写
第五步编写StudentMapper
@Mapper public interface StudentMapper { @Select("select * from student where id=#{id}") Student findStudentById(Integer id); @Insert("insert into student(name,age)values(#{name},#{age})") void insertStudent(Student student); @Update("update student set name=#{name} where id=#{id}") void updateStudent(Student student); @Delete("delete from student where id=#{id}") void deleteStudentById(Integer id); }
整合第六步编写测试类来测试写的方法逻辑是否正确
@RunWith(SpringRunner.class) @SpringBootTest @Transactional public class StudentMapperTest { @Autowired private StudentMapper studentMapper; @Test public void findStudentById() { Student student = studentMapper.findStudentById(1); Assert.assertEquals(20, student.getAge().intValue()); } @Rollback @Test public void insertStudent() { Student student = new Student(); student.setName("bobiStudent"); student.setAge(24); studentMapper.insertStudent(student); } }
编写测试类时,可以使用快捷键
ctrl+shift+T快速生成上面四个方法,在测试过程中加入@Transactional事务注解和@Rollback注解,为得是在测试过程中保证测试的数据不会被添加到数据库的Student表中,这里如果想看到在Thymeleaf中有结果显示,那么测试时候添加的数据就不要用上这个注解
在CRUD的基础整合进阶版提升
当我们完成一套流程的CRUD的时候,是否觉得太简单呢?其实这些字段远远比不上实际开发过程的封装字段的复杂程度,例如开发中常用Map来存储实体类中的字段,又或者把多个对象封装成列表的形式输出,所以我自己在上面的CRUD基础上,增加了两个进阶的方法。
进阶优化一:查询所有的学生
//查询所有的学生的方法 @Select("select id,name, age from student") List<Student> findAll();
进阶优化二:通过Map的是形式插入学生类
@Insert("insert into student(name, age) values(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})") int insertStudentByMap(Map<String, Object> map);
对应的测试方法
@Test public void findAll(){ List<Student> studentList = studentMapper.findAll(); for(Student student : studentList){ System.out.println(student); } } @Test public void insertStudentByMap(){ HashMap<String, Object> userMap = new HashMap<>(); userMap.put("name","公众号CodeLuoJay"); userMap.put("age",21); int row = studentMapper.insertStudentByMap(userMap); Assert.assertEquals(1,row); }
进阶优化三:编写controller,查询所有学生整合LayUI表格输出到页面
@Controller public class StudentController { @Autowired private StudentMapper studentMapper; @GetMapping("/student/getStudent") @ResponseBody public List<Student> getUser(){ return studentMapper.findAll(); } @GetMapping("/list") public String index(){ return "list"; } }
list.html中内容:
<table class="layui-hide" id="demo"></table> <script src="https://www.layuicdn.com/layui/layui.js" charset="utf-8"></script> <!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 --> <script> layui.use('table', function(){ var table = layui.table; //展示已知数据 table.render({ elem: '#demo' ,url:'/student/getStudent' ,cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增 ,parseData: function (res) { console.log(res); return{ "code": 0, "msg":"", "count":10, "data":res } } ,cols: [ [ {field:'id', width:100, title: 'id'}, {field:'name', width:240, title: '用户名'} ,{field:'age', width:240, title: '性别'} ] ] }); }); </script>
我在controller中对应写了一个list页面访问请求数据,然后将查询出来的数据以JSON格式输出到list.html中,最后利用CDN加速下的layui表格渲染出数据,对应的页面输出结果:
整合Mybatis过程中遇到过的坑及解决办法
坑1:spring boot + Thymeleaf + layui table 渲染报错 Could not parse as expression:
原因: [[…]]之间的表达式在Thymeleaf被认为是内联表达式
解决办法:把两个[[ ]]隔开相应的距离,不让Thymeleaf解析为内联表达式
参考链接:thymeleaf渲染layui.js的“ col 里面的内容失败”
坑2:layui,返回的数据不符合规范,正确的成功状态码 (code) 应为:0
原因:layui table数据绑定需要特定格式的字符串,需要在JSON对象中封装如下格式
{ "code": 0, "msg":"", "count":10, "data":result//你封装的字符串 }
layui,返回的数据不符合规范,正确的成功状态码 (code) 应为:0
坑3:intellij idea报错Could not autowire. No beans of ‘UserMapper’ type found.
原因:IDEA自动检查bean注入误报的错误
参考链接:intellij idea报错Could not autowire. No beans of ‘UserMapper’ type found
坑4: 连接数据库时报错The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized
原因: 出错的原因是mysql的时区值设置的不正确mysql默认的时区值是美国,中国的时区要比美国晚8小时,需要采用+8:00的格式。
参考链接:The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized
如果不想改数据库的时区的话,可以在url中加入使用的时区serverTimezone=UTC
spring: datasource: url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver
文章配套源码
🔨Github:springboot-mybatis
如果文章对你有用,请给star!
欢迎关注我的公众号:CodeLuoJay
博客园:Codeluojay
简书:Codeluojay
- 点赞
- 收藏
- 分享
- 文章举报
- 前后端分离之SpringBoot2.x整合mybatis实现数据库的增删改查操作(一)
- 前后端分离之SpringBoot2.x整合mybatis实现数据库的增删改查操作(二)
- SpringBoot2.X整合Mybatis+Thymeleaf实现增删改查(XML版)
- SpringData Jpa(一):SpringBoot整合实现基本增删改查
- Spring + SpringMVC + Mybatis 整合,实现 CRUD (增删改查)
- springboot整合mybatis增删改查(四):完善增删改查及整合swgger2
- springboot+mybatis动态SQL,以Student为例,实现增删改查小程序。
- Spirng Boot整合Mybatis实现增删改查案例-注解版
- Kotlin整合Spring Boot实现数据库增删改查(mybatis版)
- ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查)
- SpringBoot+maven整合mybatis实现增删改查
- 原 Spring + SpringMVC + Mybatis 整合,实现 CRUD (增删改查)
- SpringBoot整合Mybatis实现增删改查的功能
- 实现增删改查(SpringBoot、MyBatis-Plus与Thymeleaf)
- ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查)
- springboot整合mybatis和mysql实现数据的增删改查
- SpringBoot整合Mybatis实现增删改查
- 采用shardbatis在springBoot中实现表的水平拆分,整合swagger,mybatis,shardbatis,pagehelper
- SpringBoot整合MyBatis实现乐观锁和悲观锁的示例
- springboot整合mybatis增删改查(一):项目创建