Mybatis:Mybatis是一款面向对象的关系型数据库。
Mybatis Plus:Mybatis Plus在Mybatis的基础上,简化了开发步骤,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。所以,在学习MybatisPlus之前应该对Mybatis有充分的认识,熟悉Mybatis的开发流程。
本文基于Spring Boot编写
Maven
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency>表名注解,用于实体类和数据库中表的映射,当实体类类名与数据库中表名一致时,无需加此注解。
例:
@TableName("user") public class Student { private Integer id; private String name; private Integer age; }主键注解,标明主键。
可添加主键名,与数据库中的主键映射起来。
例:数据库中user表分别有id name age三个属性。但实体类中的属性名为myId,无法自动映射。
@TableName("user") public class Student { @TableId("id") private Integer myId; private String name; private Integer age; }执行查询语句后,控制台如下:
==> Preparing: SELECT id AS myId,name,age FROM user ==> Parameters: <== Columns: myId, name, age <== Row: 1, zhangsan, 22 <== Row: 2, lisi, 23 <== Row: 3, wangwu, 24 <== Row: 4, zhaoliu, 25 <== Total: 4 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5434e40c] Student(myId=1, name=zhangsan, age=22) Student(myId=2, name=lisi, age=23) Student(myId=3, name=wangwu, age=24) Student(myId=4, name=zhaoliu, age=25)我们通过通知台可以看出,Mybatis Plus 自动将id 映射为myId,并且输出。
还可添加type,表明主键的类型。
例:使用type = IdType.AUTO
取消数据库中id的自增选项,通过实体类注解实现id自增。
@TableName("user") public class Student { @TableId(value = "id",type = IdType.AUTO) private Integer myId; private String name; private Integer age; }例:使用 type = IdType.INPUT
当你给Id赋值时,Id会使用你所输入的值,添加到数据库;当你不赋值时,会自动递增。
@Test void save() { Student student = new Student(); student.setMyId(6); student.setAge(100); student.setName("testPerson"); mapper.insert(student); } @Test void save() { Student student = new Student(); student.setAge(99); student.setName("testPerson1"); mapper.insert(student); }执行添加语句后,数据库如下:
1zhangsan222lisi233wangwu246testPerson1007testPerson199可知,当我们赋予主键值为6时,直接在数据库中插入id为6的数据,跳过了4、5,在插入testPerson1的数据时,没有给出id,所以系统通过自增的方式给id赋值。
例: type = IdType.ASSIGN_ID
注:因为默认使用了雪花算法,对主键的数据类型有要求,建议用包装类Long
idnameage126894546124674testPerson596例4:type = IdType.ASSIGN_UUID
注:因为默认使用了雪花算法,对主键的数据类型有要求,必须使用String类型。
idnameageb1w26rsar894y5g46sr12467i4feq56testPerson696非主键注解,标明数据库属性与实体类的映射关系。输出结果和@TableId基本相同,这里不再演示。
乐观锁的主要目的时防止多线程修改数据时,数据被多次修改,数据库无法及时更新的现象。
例:
给数据库添加version属性,并给出默认值。
idnameageversionxxxxxxx1给实体类添加@Version注解
@Version private Integer version;添加配置类,将乐观锁注入到容器中。
@Configuration public class StudentConfig { @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor(){ return new OptimisticLockerInterceptor(); } }进行修改操作
@Test void update(){ Student student = mapper.selectById(3); student.setName("zhangsanfeng"); mapper.updateById(student); }通过控制台我们可知
==> Preparing: UPDATE user SET name=?, age=?, version=? WHERE id=? AND version=? ==> Parameters: zhangsanfeng(String), 24(Integer), 2(Integer), 3(Integer), 1(Integer) <== Updates: 1不但对姓名做了修改,当这条SQL语句成功后,version变为了2
原数据库
idnameageversion3zhansgan121修改后的数据库
idnameageversion3zhangsanfengxx2通过枚举,将数据库中的字段映射成具有实际意义的新字段。
例:在数据库中,1代表男性 2代表女性,通过枚举,在控制台上直接输出sex = 男性而不是sex = 1
创建枚举类
public enum SexEnum { SEXM(1,"男性"), SEXF(2,"女性"); @EnumValue private Integer code; private String sex; SexEnum(Integer code, String sex) { this.code = code; this.sex = sex; } }实体类中添加性别属性
private SexEnum sex;修改application.yml
type-enums-package: com.woongcha.myspringbootmybatisplus.enums执行查询语句
Student(myId=1, name=zhangsan, age=22, version=1, sex=SEXM) Student(myId=2, name=lisi, age=23, version=1, sex=SEXM) Student(myId=3, name=zhangsanfeng, age=24, version=2, sex=SEXM)可以看到,sex=1被替换成了sex=SEXM。
表字段逻辑处理注解(逻辑删除),即部分数据我们不想展示出来,可以隐藏起来。
实体类中添加隐藏属性
private Integer hide;修改application.yml
global-config: db-config: logic-not-delete-value: 0 logic-delete-field: 1执行删除语句
@Test void delete() { mapper.deleteById(1); }查看数据库
idnameagehide1zhangsan221数据并没有从数据库中删除,但hide的值由0变成了1,达到了逻辑上删除的目的。
执行查询语句
@Test void test() { mapper.selectList(null).forEach(System.out::println); } ==> Preparing: SELECT id AS myId,name,age,version,sex,hide FROM user WHERE hide=0 ==> Parameters: <== Columns: myId, name, age, version, sex, hide <== Row: 2, lisi, 23, 1, 1, 0 <== Total: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7da39774] Student(myId=2, name=lisi, age=23, version=1, sex=SEXM, hide=0)SQL语句默认执行where hide=0,说明逻辑删除成功,且查不到我们删除的数据。
控制台可以看到查询到了结果
==> Preparing: SELECT id AS myId,name,age,version,sex,hide FROM user WHERE hide=0 AND (id IN (select id from user Where id = 1)) ==> Parameters: <== Columns: myId, name, age, version, sex, hide <== Row: 1, zhangsan, 22, 1, 1, 0 <== Total: 1逆向工程是通过数据库中已经存在的数据表,反向生成java中的实体类,并且生成对应的ORM(Object Relationship Mapping 对象关系映射)持久层代码。
在Mybatis官方中给出了Mybatis Generator(MBG),在Mybatis Plus中,AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
引入依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency>在任意路径新建Generator.java
public class Generator { public static void main(String[] args) { // 代码生成器-创建generator对象 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("woongcha"); gc.setOpen(false); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setUrl("jdbc:mysql://localhost:3306/myspringboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.woongcha.myspringbootmybatisplus"); pc.setModuleName("generator"); pc.setController("controller"); pc.setService("service"); pc.setServiceImpl("mapper"); pc.setEntity("entity"); mpg.setPackageInfo(pc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); mpg.setStrategy(strategy); mpg.execute(); } }运行Generator.java
快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码。
Mybatis Plus 由中国人开发,相比Mybaits,跟符合中国人的习惯,例如中文的注释等。
相比Mybatis 主要简化了编写SQL语句的过程,且提供了大量的接口,符合大多数人的使用。
Mybaits Plus Generator 集成了MBG的优点,且更灵活,能介入的更多,例如下划线命名法转换成驼峰命名等。
本文简化了CRUD的介绍,因为CRUD在编程的过程中Mybatis Plus过程中会有大量的中文提示,会明确的告诉你方法的意思以及属性的填写。
码字不易,感谢支持。