1.引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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>
<!--简化代码的工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--mybatis‐plus的springboot支持-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
</dependencies>
2.配置
2.1 spring boot 2.0(内置mysql5版本驱动)
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin
mybatis-plus.mapper-locations=classpath*:mapper/**/*.xml
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
spring:
datasource:
username: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai&useSSL=false
mybatis-plus:
config-location: classpath:mybatis-config.xml
mapper-locations: classpath*:mybatis/mapper/*.xml
2.2 spring boot 2.1及以上(内置mysql8版本驱动)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
3. 编写pojo
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
@TableId("ID")
private Long id;
@TableField("USER_NAME")
private String userName; //驼峰命名,则无需注解
}
@Data:lombok的注解,使用它可以省略getter/setter方法。
@NoArgsConstructor: 生成无参构造 方法
@AllArgsConstructor:生成所有参数构造 方法,参数顺序与属性定义顺序一致。
@TableName:指定表名
@TableId:指定主键名
@TableField:指定列名
4. 编写mapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
5.编写启动类
@SpringBootApplication
@MapperScan("com.***.mapper")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class,args);
}
}
6.测试
@SpringBootTest
public class UserMapperTest {
@Resource
private UserMapper userMapper;
@Test
public void testSelect() {
List<User> userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
}
7.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.glls.mp.mapper.UserMapper">
//单表
<select id="findById" resultType="com.glls.mp.pojo.User" parameterType="java.lang.Long">
select * from tb_user where id = #{id}
</select>
//多表
<resultMap id="映射名" type="包名.实体类名" autoMapping="true">
<id property="属性名" column="主键字段名"/>
如果类中关系属性为实体对象
<association property="关系属性名" javaType="关系属性的类型"
column="指定当前查询中的字段传入关联语句的中作为条件值"
select="空间名.语句名"/>
如果类中关系属性为List集合
<collection property="关系属性名" javaType="集合类型"
ofType="集合的泛型类型"
column="指定当前查询中的字段传入关联语句的中作为条件值"
select="空间名.语句名"/>
</resultMap>
<select id="名称" resultMap="映射名">
单表查询语句
</select >
</mapper>
在mapper中生成对应的方法。
8.主键策略
在实体类的id上添加注解即可
@TableId(value = "id", type = IdType.AUTO)
private String id;
//雪花算法 3.3以上默认
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
//雪花算法老版本
@TableId(value = "id", type = IdType.ID_WORKER)
private String id;
9.自动填充
可以实现自动更新时间操作
1.数据库修改
在User表中添加datetime类型的新的字段 create_time、update_time
2.实体类修改
@TableField(fill = FieldFill.INSERT)
private Date createTime; //create_time
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime; //update_time
3.实现元对象处理器接口
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//mp执行添加操作,这个方法执行
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//mp执行修改操作,这个方法执行
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
10. 乐观锁
数据库新建version字段 int 固定为1
实体类
@Version
private Integer version;
配置类
创建包config,创建文件MybatisPlusConfig.java
此时可以删除主类中的 @MapperScan 扫描注解
@Configuration
@MapperScan("cn.yh.mp.mapper")
public class MpConfig {
/**
* 乐观锁插件
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
修改完成后每次修改语句会自动查询版本号,不一致则修改失败
11 逻辑删除
1. 数据库添加deleted字段
ALTER TABLE `user` ADD COLUMN `deleted` boolean DEFAULT false
2.实体类添加deleted 字段,并加上 @TableLogic 注解
@TableLogic
private Integer deleted;
3.配置(默认为此配置)
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
12.条件构造器
eq 、ne、ge、gt、le、lt、isNull、isNotNull、 like、notLike、likeLeft、likeRight、select、in、orderBy、orderByDesc、orderByAsc
"eq"表示等于
"ne"表示不等于
“ge”表示大于等于
“gt”表示大于
“le”表示小于等于
“lt”表示小于
"select"表示查询字段
"user::name"Lambda方式构造条件:
可以加条件表达式来决定是否查询条件生效
@Test
public void testSelectOne() {
QueryWrapper<User> queryWrapper = newQueryWrapper<>();
queryWrapper.eq("user::name", "Tom");
queryWrapper.between("age", 20, 30);
queryWrapper.like("user::name","王")
queryWrapper.select("user::name","user::id","user::age")
queryWrapper.orderByDesc("age", "id");
queryWrapper.in(User::getName, "李四", "王五", "赵六");
//可以加条件表达式来决定是否查询条件生效
queryWrapper.in(name!=null,User::getName, "李四", "王五", "赵六");
}
13.分页查询
配置类中添加@Bean配置,和乐观锁插件可以配置在同一个config类
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
//分页查询
@Test
public void testSelectPage() {
Page<User> page = new Page(1,3);
Page<User> userPage = userMapper.selectPage(page, null);
//返回对象得到分页所有数据
long pages = userPage.getPages(); //总页数
long current = userPage.getCurrent(); //当前页
List<User> records = userPage.getRecords(); //查询数据集合
long total = userPage.getTotal(); //总记录数
boolean hasNext = userPage.hasNext(); //下一页
boolean hasPrevious = userPage.hasPrevious(); //上一页
System.out.println(pages);
System.out.println(current);
System.out.println(records);
System.out.println(total);
System.out.println(hasNext);
System.out.println(hasPrevious);
//selectMapsPage分页
Page<Map<String, Object>> page = newPage<>(1, 5);
Page<Map<String, Object>> pageParam = userMapper.selectMapsPage(page, null);
List<Map<String, Object>> records = pageParam.getRecords();
records.forEach(System.out::println);
System.out.println(pageParam.getCurrent());
System.out.println(pageParam.getPages());
System.out.println(pageParam.getSize());
System.out.println(pageParam.getTotal());
System.out.println(pageParam.hasNext());
System.out.println(pageParam.hasPrevious());
}