Spring Boot(四):如何优雅的使用 Mybatis

Stella981
• 阅读 688

一、前言

Orm框架的本质是简化编程中操作数据库的编码,发展到现在,基本上就剩宣称不用谢一句sql的hibernate,一个是可以灵活调试动态sql的mybatis,两者各有特点,在企业级系统来发中可以根据需求灵活使用。发现一个有趣的现象:传统企业大都喜欢hibernate,互联网行业通常使用mybatis。

hibernate特点就是所有的sql都用java代码来生成,不用跳出程序去写sql,有这编程的完整性,发展到最顶端就是spring data jpa这种模式,基本上根据方法名就可以生成对应的sql。

mybatis初期使用比较麻烦,需要各种配置文件、实体类、Dao层映射关系、还有一大堆其他配置文件。

当然mybatis也有发现了这种弊端,初期开发了generator可以根据表结构自动生成实体类、配置文件和dao层代码,可以减轻一部分开发量;后期也进行了大量的优化可以使用注解,自动管理dao层和配置文件等,发展到最顶级就是今天讲的这种springboot+mybatis可以完全注解不用配置文件,也可以简单配置轻松上手。

springboot就是牛逼呀,啥玩意关联springboot都能化繁为简。

Spring Boot(四):如何优雅的使用 Mybatis

二、mybatis-spring-boot-starter

mybatis-spring-boot-starter主要由两种解决方案,一种是使用注解解决一切问题,一种的简化后的老传统。

当然任何模式都需要先引入mybatis-spring-boot-starter的pom文件,现在最新版本是

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

三、无配置注解版

1、添加maven文件

<**dependencies**> <**dependency**> <**groupId**>org.springframework.boot</**groupId**> <**artifactId**>spring-boot-starter-data-jdbc</**artifactId**> </**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**>2.1.1</**version**> </**dependency**>

<**dependency**> <**groupId**>com.oracle.ojdbc</**groupId**> <**artifactId**>ojdbc8</**artifactId**> <**scope**>runtime</**scope**> </**dependency**>

_ _ <**dependency**> <**groupId**>com.alibaba</**groupId**> <**artifactId**>druid</**artifactId**> <**version**>1.1.21</**version**> </**dependency**>

_ _ <**dependency**> <**groupId**>log4j</**groupId**> <**artifactId**>log4j</**artifactId**> <**version**>1.2.17</**version**> </**dependency**> </**dependencies**>

2、application.yml添加相关配置

spring:
  datasource:
    username: mine
    password: mine
    url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
    driver-class-name: oracle.jdbc.driver.OracleDriver
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Spring Boot 会自动加载spring.datasource.*相关配置,数据源就会自动注入到 sqlSessionFactory 中,sqlSessionFactory 会自动注入到 Mapper 中,对了,你一切都不用管了,直接拿起来使用就行了。

在启动类中添加对 mapper 包扫描@MapperScan

@MapperScan(value="com.demo.mapper") @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

或者直接在 Mapper 类上面添加注解@Mapper,建议使用上面那种,不然每个 mapper 加个注解也挺麻烦的

3、controller

@RestController public class DeptController { @Autowired DepartmentMapper departmentMapper;

@GetMapping(**"/dept/{id}"**)
**public** Department getDepartment(@PathVariable(**"id"**) Integer id){
    **return** **departmentMapper**.getDeptById(id);
}

@GetMapping(**"/dept"**)
**public int** insertDeptById(@PathVariable(**"id"**) Integer id,@PathVariable(**"departmentName"**) String departmentName){
    **int** ret = **departmentMapper**.insertDept(id,departmentName);
    **return** ret;
}

}

4、开发mapper

package com.demo.mapper;

import com.demo.bean.Department;
import org.apache.ibatis.annotations.*;

public interface DepartmentMapper {
    @Select("select * from SSH_DEPARTMENT where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from SSH_DEPARTMENT where id=#{id}")
    public int deleteDeptById(Integer id);
    
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into SSH_DEPARTMENT(department_name) values(#{departmentName})")
    public int insertDept(Department department);
    
    @Update("update SSH_DEPARTMENT set departmentName=#{DEPARTMENT_NAME} where id=#{id}")
    public int updateDept(Department department);
}
  • @Select 是查询类的注解,所有的查询均使用这个
  • @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
  • @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
  • @Update 负责修改,也可以直接传入对象
  • @delete 负责删除

4、运行

上面三步就基本完成了相关 Mapper 层开发,使用的时候当作普通的类注入进入就可以了

(1)查询

Spring Boot(四):如何优雅的使用 Mybatis

(2)插入

  • 插入前数据库状态

Spring Boot(四):如何优雅的使用 Mybatis

  • 浏览器调用controller执行插入

Spring Boot(四):如何优雅的使用 Mybatis

  • 插入后结果查询

Spring Boot(四):如何优雅的使用 Mybatis

四、极简XML版本

极简 xml 版本保持映射文件的老传统,接口层只需要定义空方法,系统会自动根据方法名在映射文件中找对应的 Sql

1、配置

pom 文件和上个版本一样,只是application.yml新增以下配置

mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

mybatis-config.xml 配置

<?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>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

2、employeeMapper.xml

<?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.atguigu.springboot.mapper.EmployeeMapper">
   <!--    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);-->
    <select id="getEmpById" resultType="com.atguigu.springboot.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    </select>

    <insert id="insertEmp">
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

3、开发mapper

package com.demo.mapper;

import com.demo.bean.Employee;
import org.mybatis.spring.annotation.MapperScan;

@MapperScan
public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);
}

对比上一步,这里只需要定义接口方法。

4、运行结果与注解方式无异。

五、两种模式如何选择

Spring Boot(四):如何优雅的使用 Mybatis

两种模式各有特点,注解版适合简单快速的模式,其实像现在流行的这种微服务模式,一个微服务就会对应一个自己的数据库,多表连接查询的需求会大大的降低,会越来越适合这种模式。

老传统模式比较适合大型项目,可以灵活的动态生成sql,方便调整sql,有的人就是爱写sql,再配上点存储过程,越复杂越好,感觉自己越牛,那你就用这个。

素小暖讲Spring Boot

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Karen110 Karen110
2年前
​一篇文章总结一下Python库中关于时间的常见操作
前言本次来总结一下关于Python时间的相关操作,有一个有趣的问题。如果你的业务用不到时间相关的操作,你的业务基本上会一直用不到。但是如果你的业务一旦用到了时间操作,你就会发现,淦,到处都是时间操作。。。所以思来想去,还是总结一下吧,本次会采用类型注解方式。time包importtime时间戳从1970年1月1日00:00:00标准时区诞生到现在
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这