Mybatis-plus框架使用配置
MyBatis-Plus(简称 MP)是一个基于 MyBatis 的增强工具,它对 Mybatis 的基础功能进行了增强,但未做任何改变。使得我们可以可以在 Mybatis 开发的项目上直接进行升级为 Mybatis-plus,正如它对自己的定位,它能够帮助我们进一步简化开发过程,提高开发效率。
Mybatis-Plus 其实可以看作是对 Mybatis 的再一次封装,升级之后,对于单表的 CRUD 操作,调用 Mybatis-Plus 所提供的 API 就能够轻松实现,此外还提供了各种查询方式、分页等行为。最最重要的,开发人员还不用去编写 XML,这就大大降低了开发难度
一、引入依赖
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> <version>2.3.3.RELEASEversion> dependency><dependency> <groupId>com.baomidougroupId> <artifactId>mybatis-plus-annotationartifactId> <version>3.3.2version> dependency><dependency> <groupId>com.baomidougroupId> <artifactId>mybatis-plus-boot-starterartifactId> <version>3.3.2version> dependency> <dependency> <groupId>com.github.pagehelpergroupId> <artifactId>pagehelper-spring-boot-starterartifactId> <version>1.2.12version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>5.1.9version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druid-spring-boot-starterartifactId> <version>1.1.10version> dependency> <dependency> <groupId>cn.hutoolgroupId> <artifactId>hutool-allartifactId> <version>5.8.5version> dependency><dependency> <groupId>com.alibabagroupId> <artifactId>fastjsonartifactId> <version>1.2.21version> dependency> <dependency> <groupId>org.projectlombokgroupId> <artifactId>lombokartifactId> <version>1.18.16version> dependency>
二、application.yml文件配置
#服务端口号server: port: 9022#mybatis配置mybatis-plus: mapper-locations: classpath:/mapper/*.xml configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl call-setters-on-nulls: true#数据库配置spring: datasource: driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306/supply_goods?useUnicode=true&characterEncoding=utf8 username: root password: 123456
三、数据库表sql
CREATE TABLE `user` ( `id` bigint(18) NOT NULL AUTO_INCREMENT COMMENT 'id', `username` varchar(255) DEFAULT NULL COMMENT '用户名', `password` varchar(255) DEFAULT NULL COMMENT '密码', `sex` tinyint(1) DEFAULT NULL COMMENT '性别:0男、1女', `dept` varchar(255) DEFAULT NULL COMMENT '部门', `created` datetime DEFAULT NULL COMMENT '创建时间', `create_by` bigint(20) DEFAULT NULL COMMENT '创建人', `modify_by` bigint(20) DEFAULT NULL COMMENT '更新人', `last_update_time` datetime DEFAULT NULL COMMENT '更新时间', `del_flag` tinyint(1) DEFAULT '0' COMMENT '是否删除:0未删除 1已删除', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
四、实体类
sql在线生成s实体类:https://java.bejson.com/generator/
package com.supplier.domain;import com.baomidou.mybatisplus.annotation.*;import lombok.Data;import java.io.Serializable;import java.util.Date;@TableName("user")@Datapublic class User implements Serializable { @TableId(type = IdType.AUTO) private Integer id; private String username; private String password; private Integer sex; private String dept; @TableField(value = "create_by", fill = FieldFill.INSERT) private String createBy; @TableField(value = "modify_by", fill = FieldFill.UPDATE) private String modifyBy; @TableField(value = "created", fill = FieldFill.INSERT) private Date created; @TableField(value = "last_update_time", fill = FieldFill.INSERT_UPDATE) private Date lastUpdateTime; private Boolean delFlag; @TableField(exist = false) private String exit;}
返回实体类
package com.supplier.model;import com.supplier.constant.SysConstant;import lombok.Data;import java.io.Serializable;@Datapublic class R<T> implements Serializable { private static final long serialVersionUID = 1L; private int code; private String msg; private T data; public static <T> R<T> ok() { return restResult(null, SysConstant.SUCCESS_CODE, SysConstant.SUCCESS_MSG); } public static <T> R<T> ok(T data) { return restResult(data, SysConstant.SUCCESS_CODE, SysConstant.SUCCESS_MSG); } public static <T> R<T> ok(T data, String msg) { return restResult(data, SysConstant.SUCCESS_CODE, msg); } public static <T> R<T> fail() { return restResult(null, SysConstant.FAIL_CODE, SysConstant.FAIL_MSG); } public static <T> R<T> fail(String msg) { return restResult(null, SysConstant.FAIL_CODE, msg); } public static <T> R<T> fail(T data) { return restResult(data, SysConstant.FAIL_CODE, SysConstant.FAIL_MSG); } public static <T> R<T> fail(T data, String msg) { return restResult(data, SysConstant.FAIL_CODE, msg); } public static <T> R<T> fail(int code, String msg) { return restResult(null, code, msg); } private static <T> R<T> restResult(T data, int code, String msg) { R<T> apiResult = new R<>(); apiResult.setCode(code); apiResult.setData(data); apiResult.setMsg(msg); return apiResult; }}
package com.supplier.constant;public interface SysConstant { String SUCCESS_MSG = "请求成功!"; int SUCCESS_CODE = 200; String FAIL_MSG = "请求失败!"; int FAIL_CODE = 500;}
分页实体类
package com.supplier.model;import lombok.Data;import lombok.NoArgsConstructor;import java.io.Serializable;import java.util.List;@Data@NoArgsConstructorpublic class PageModel<T> implements Serializable { public int pageNum; public int pageSize; public long total; public List list; public PageModel(int pageNum, int pageSize, long total, List list) { this.pageNum = pageNum; this.pageSize = pageSize; this.total = total; this.list = list; }}
五、配置类
mybatis-plus分页配置(也可以直接引入mybatis分页插件)
package com.supplier.config;import com.baomidou.mybatisplus.annotation.DbType;import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;import com.baomidou.mybatisplus.extension.incrementer.H2KeyGenerator;import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration@MapperScan("com.supplier.mapper")public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); paginationInterceptor.setDbType(DbType.MYSQL); return paginationInterceptor; } @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } @Bean public IKeyGenerator iKeyGenerator() { return new H2KeyGenerator(); }}
插入、更新时设置字段默认值,更新时必须使用一下方式才生效
package com.supplier.config;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.reflection.MetaObject;import org.springframework.stereotype.Component;import java.util.Date;@Slf4j@Componentpublic class AutoFillHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { String userId = "1234"; this.strictInsertFill(metaObject, "createBy", String.class, userId); this.strictInsertFill(metaObject, "created", Date.class, new Date()); this.strictInsertFill(metaObject, "lastUpdateTime", Date.class, new Date()); } @Override public void updateFill(MetaObject metaObject) { String userId = "22"; this.strictUpdateFill(metaObject, "modifyBy", String.class, userId); this.strictUpdateFill(metaObject, "lastUpdateTime", Date.class, new Date()); }}
六、业务逻辑处理(Service接口类)
package com.supplier.service;import com.baomidou.mybatisplus.extension.service.IService;import com.supplier.domain.User;import com.supplier.model.PageModel;public interface UserService extends IService<User> { void add(User user); void modify(User user); User detail(Integer id); PageModel lists(Integer pageNum,Integer pageSize); void delete(Integer id);}
实现类
package com.supplier.service.impl;import cn.hutool.core.bean.BeanUtil;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.github.pagehelper.Page;import com.github.pagehelper.PageHelper;import com.supplier.domain.User;import com.supplier.mapper.UserMapper;import com.supplier.model.PageModel;import com.supplier.service.UserService;import org.apache.commons.lang3.StringUtils;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public void add(User user) { this.baseMapper.insert(user); } @Override public void modify(User user) { //当重新new对象时,会调用自动填充更新时间和更新人的数据 User userNews = new User(); BeanUtil.copyProperties(user,userNews); UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>(); userUpdateWrapper.eq("id",user.getId()); this.baseMapper.update(user,userUpdateWrapper); } @Override public User detail(Integer id) { //需要筛选条件时 return this.baseMapper.selectOne(new QueryWrapper<User>().eq("id",id).last("limit 1")); } public PageModel listsTwo(Integer pageNum,Integer pageSize) { //第一种分页,使用mybatis插件 PageHelper.startPage(pageNum,pageSize); Page<User> list = this.baseMapper.lists(); return new PageModel(pageNum,pageSize,list.getTotal(),list.getResult()); } @Override public PageModel lists(Integer pageNum,Integer pageSize){ //第二种分页,mybatis-plus分页 com.baomidou.mybatisplus.extension.plugins.pagination.Page<User> userPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum,pageSize); com.baomidou.mybatisplus.extension.plugins.pagination.Page<User> list = this.baseMapper.selectPage(userPage, null); return new PageModel(pageNum,pageSize,list.getTotal(),list.getRecords()); } public List<User> selectInfo(String username, Integer sex) { QueryWrapper<User> queryWrapper = new QueryWrapper(); //使用eq表示查询值为必填,select表示查询字段 queryWrapper.like(StringUtils.isNoneBlank(username),"username",username).eq("sex",sex).select("id","username"); //无查询条件 return this.baseMapper.selectList(queryWrapper); } @Override public void delete(Integer id) { this.baseMapper.deleteById(id); }}
七、数据访问层(dao接口类)
package com.supplier.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.github.pagehelper.Page;import com.supplier.domain.User;import org.apache.ibatis.annotations.Mapper;@Mapperpublic interface UserMapper extends BaseMapper<User> { Page<User> lists();}
mapper文件
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.supplier.mapper.UserMapper"> <select id="lists" resultType="com.supplier.domain.User"> select * from `user` select>mapper>
八、控制层(controller)
package com.supplier.controller;import com.supplier.domain.User;import com.supplier.model.R;import com.supplier.service.UserService;import org.springframework.web.bind.annotation.*;@RestController@RequestMapping("/user")public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @PostMapping public R add(@RequestBody User user){ userService.add(user); return R.ok(); } @PutMapping public R modify(@RequestBody User user){ userService.modify(user); return R.ok(); } @GetMapping("/{id}") public R detail(@PathVariable Integer id){ return R.ok(userService.detail(id)); } @GetMapping public R list(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10")Integer pageSize){ return R.ok(userService.lists(pageNum,pageSize)); } @DeleteMapping public R delete(Integer id){ userService.delete(id); return R.ok(); }}
来源地址:https://blog.csdn.net/m0_46300599/article/details/127999193