SpringBoot2.X整合Mybatis实现增删改查(注解版)


在SpringBoot的官网好像没有找到mybatis的整合指南,可能是国外比较流行使用JPA吧,所以写下此文章来记录整合过程的记录,此过程包含简单的CRUD以及后面进阶的整合之前学过的Thymeleaf模板引擎,简单做了一个查询数据渲染页面,相关的源代码已上传到Github上,连接放在文章末尾

项目结构

项目目录结构

案例实现效果

演示效果

pom.xml
        <!--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>

导入pom.xml依赖:Mybatis和Mysql两个核心依赖,这里我额外导多一个lombok依赖(可选)

application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456

编写application.yml配置文件,写上要连接的数据库的配置信息
这里默认使用的SpringBoot内置的数据源,在2.0版本后使用的是HikariDataSource这个数据源,mysql驱动在2.0版本后使用的mysql8.0驱动,对应的驱动为com.mysql.cj.jdbc.Driver,还应注意连接的url要加上时区serverTimezone=UTC,否则会报时区错误,除非你修改了mysql默认的时区

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;

创建数据库的表,按照配置是在test数据库下创建student表,下面试建表的sql

编写Student实体类
@Data//使用这个注解就默认帮我们生成getter和setter以及toString等
@NoArgsConstructor //lombok生成无参数构造函数
public class Student {
    private Integer id;
    private String Name;
    private Integer age;
}

创建实体类Student映射到mysql的表student,这里就用到开头的导入的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的时候,是否觉得太简单呢?其实这些字段远远比不上实际开发过程的封装字段的复杂程度,例如开发中常用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);
    }
优化三:整合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";
    }
}

编写controller,查询所有学生整合LayUI表格输出到页面

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
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值