最近无意之中发现了一个非常棒的持久层框架mybatis-flex,迫不及待研究了一下
发现简直就是我的梦中情框,之前写ibatis,后来写mybatis,接着写mybatis-plus,接着研究mybatis-flex
ibatis是apache开源的,当时是一款轻量级的数据据持久层的半自动式开发框架
它简化直接用jdbc开发的60%以上的代码量,并且支持将sql写入xml中,使结构变得非常清晰,而且能灵活配置,从此进入了ibatis的时代,受到当时大量的开发人员的喜爱
优点:
缺点:
它就是千锤百炼锻造出来的,它的前身就是ibatis
优点:
缺点
它是mybatis的增强工具,在mybatis的基础上只做增强不做改变
优点:
缺点:
它也是在mybatis上做了增强
我的要求:
mybatis-flex满足了我所有的要求,所以我觉得自己很有必要去了解一下
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.1.2
com.zxs
springboot-mybatis-flex
0.0.1-SNAPSHOT
springboot-mybatis-flex
springboot-mybatis-flex
17
1.5.6
1.2.47
com.github.xiaoymin
knife4j-dependencies
4.1.0
pom
import
org.springframework.boot
spring-boot-starter-web
com.github.xiaoymin
knife4j-openapi3-jakarta-spring-boot-starter
com.mysql
mysql-connector-j
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-jdbc
com.mybatis-flex
mybatis-flex-spring-boot-starter
${mybatis-flex.version}
com.alibaba
fastjson
${fastjson.version}
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test
username: root
password: zkb.com
type: com.zaxxer.hikari.HikariDataSource
hikari:
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
maximum-pool-size: 100
minimum-idle: 10
pool-name: HikaraPool-1
springdoc:
swagger-ui:
path: /swagger-ui.html
tags-sorter: alpha
api-docs:
path: /v3/api-docs
group-configs:
- group: '查询接口'
paths-to-match: '/**'
packages-to-scan: com.zxs.springbootmybatisflex.controller.sys
- group: '增删改接口'
paths-to-match: '/**'
packages-to-scan: com.zxs.springbootmybatisflex.controller.client
default-flat-param-object: true
knife4j:
enable: true
package com.zxs.springbootmybatisflex.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableKnife4j
public class SwaggerConfig {
// 设置 openapi 基础参数
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("zxs API 管理")
.version("1.0")
.description("探索mybatis-flex demo")
.license(new License().name("Apache 2.0")));
}
}
package com.zxs.springbootmybatisflex.controller.client;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import com.zxs.springbootmybatisflex.entity.User;
import com.zxs.springbootmybatisflex.service.UserService;
import com.zxs.springbootmybatisflex.uitl.DataResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import static com.zxs.springbootmybatisflex.entity.table.UserTableDef.USER;
@RestController
@Tag(name="用户增删改")
@RequestMapping("/suser")
public class SuserController {
@Autowired
UserService userService;
@Operation(summary = "根据id删除用户",description = "方式一")
@GetMapping("/deleteUser/{id}")
public DataResult deleteUser(@PathVariable(value = "id") Long id){
DataResult result = DataResult.success();
userService.deleteUser(id);
return result;
}
@Operation(summary = "根据id删除用户",description = "方式二")
@GetMapping("/deleteUser2/{id}")
public DataResult deleteUser2(@PathVariable(value = "id") Long id){
DataResult result = DataResult.success();
userService.removeById(id);
return result;
}
@Operation(summary = "根据id删除用户",description = "方式三")
@GetMapping("/deleteUser3/{id}")
public DataResult deleteUser3(@PathVariable(value = "id") Long id){
DataResult result = DataResult.success();
userService.deleteUser3(id);
return result;
}
@Operation(summary = "根据id删除用户",description = "方式四")
@GetMapping("/deleteUser4/{id}")
public DataResult deleteUser4(@PathVariable(value = "id") Long id){
DataResult result = DataResult.success();
QueryCondition queryCondition =USER.ID.eq(id);
userService.remove(queryCondition);
return result;
}
@Operation(summary = "增加用户",description = "方式一")
@PostMapping("/addUser1")
public DataResult addUser1(@RequestBody User user){
DataResult result = DataResult.success();
userService.save(user);
return result;
}
@Operation(summary = "修改用户",description = "方式一")
@PostMapping("/updateUser1")
public DataResult updateUser1(@RequestBody User user){
DataResult result = DataResult.success();
QueryWrapper queryWrapper = QueryWrapper.create().
where(USER.USERNAME.eq(user.getUsername())).
and(USER.PASSWORD.eq(user.getPassword()));
userService.update(user,queryWrapper);
return result;
}
@Operation(summary = "修改用户",description = "方式二")
@PostMapping("/updateUser2")
public DataResult updateUser2(@RequestBody User user){
DataResult result = DataResult.success();
QueryWrapper queryWrapper = QueryWrapper.create().
where(USER.USERNAME.eq(user.getUsername())).
and(USER.PASSWORD.eq(user.getPassword()));
userService.update(user,queryWrapper);
return result;
}
}
package com.zxs.springbootmybatisflex.controller.sys;
import com.zxs.springbootmybatisflex.entity.User;
import com.zxs.springbootmybatisflex.service.UserService;
import com.zxs.springbootmybatisflex.uitl.DataResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@Tag(name="用户查询")
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@Operation(summary = "获取全部用户",description="获取全部用户")
@GetMapping("/selectUsers")
public DataResult> selectUsers(){
DataResult> result = DataResult.success();
List list = userService.list();
result.setData(list);
return result;
}
@Operation(summary = "根据id获取用户",description = "方式一")
@GetMapping("/selectUser/{id}")
public DataResult selectUser(@PathVariable(value = "id") Long id){
DataResult result = DataResult.success();
User user = userService.selectUserById(id);
result.setData(user);
return result;
}
@Operation(summary = "根据id获取用户",description = "方式二")
@GetMapping("/selectUser2/{id}")
public DataResult selectUser2(@PathVariable(value = "id") Long id){
DataResult result = DataResult.success();
User user = userService.getById(id);
result.setData(user);
return result;
}
@Operation(summary = "根据id获取用户",description = "方式三")
@GetMapping("/selectUser3/{id}")
public DataResult selectUser3(@PathVariable(value = "id") Long id){
DataResult result = DataResult.success();
User user = userService.selectUserById2(id);
result.setData(user);
return result;
}
}
package com.zxs.springbootmybatisflex.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.mybatisflex.annotation.Column;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
//import io.swagger.annotations.ApiModel;
//import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = false)
@Tag(name = "用户", description = "用户实体类")
@Table("user")
public class User{
@Schema(description="用户id")
@JsonSerialize(using = ToStringSerializer.class)
@Id(keyType = KeyType.Auto)
private Long id;
/**
* 用户名
*/
@Schema(description="用户名")
private String username;
/**
* 密码
*/
@Schema(description="密码")
private String password;
/**
* 名称
*/
@Schema(description="名称")
private String name;
/**
* 邮箱
*/
@Schema(description="邮箱")
private String email;
/**
* 联系方式
*/
@Schema(description="手机号")
private String phone;
/**
* 用户状态:1有效; 2删除
*/
@Schema(description="状态")
private Integer status;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column("createTime")
private Date createTime;
/**
* 用户类型
*/
@Schema(description="登录次数")
private Integer logins;
}
package com.zxs.springbootmybatisflex.exception.code;
public enum BaseResponseCode implements ResponseCodeInterface {
/**
* 这个要和前段约定好
* 引导用户去登录界面的
* code=401001 引导用户重新登录
* code=401002 token 过期刷新token
* code=401008 无权限访问
*/
SUCCESS(200,"操作成功"),
SYSTEM_BUSY(500001, "系统繁忙,请稍候再试"),
OPERATION_ERRO(500002,"操作失败"),
METHODARGUMENTNOTVALIDEXCEPTION(500003, "方法参数校验异常"),
;
/**
* 错误码
*/
private final int code;
/**
* 错误消息
*/
private final String msg;
BaseResponseCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public int getCode() {
return code;
}
@Override
public String getMsg() {
return msg;
}
}
package com.zxs.springbootmybatisflex.exception.code;
public interface ResponseCodeInterface {
int getCode();
String getMsg();
}
package com.zxs.springbootmybatisflex.exception.handler;
import com.zxs.springbootmybatisflex.exception.BusinessException;
import com.zxs.springbootmybatisflex.exception.code.BaseResponseCode;
import com.zxs.springbootmybatisflex.uitl.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {
@ExceptionHandler(Exception.class)
public DataResult handleException(Exception e){
log.error("Exception,exception:{}", e);
return DataResult.getResult(BaseResponseCode.SYSTEM_BUSY);
}
@ExceptionHandler(value = BusinessException.class)
DataResult businessExceptionHandler(BusinessException e) {
log.error("BusinessException,exception:{}", e);
return new DataResult<>(e.getMessageCode(),e.getDetailMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
DataResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", e.getBindingResult().getAllErrors(), e);
List errors = e.getBindingResult().getAllErrors();
return createValidExceptionResp(errors);
}
private DataResult createValidExceptionResp(List errors) {
String[] msgs = new String[errors.size()];
int i = 0;
for (ObjectError error : errors) {
msgs[i] = error.getDefaultMessage();
log.info("msg={}",msgs[i]);
i++;
}
return DataResult.getResult(BaseResponseCode.METHODARGUMENTNOTVALIDEXCEPTION.getCode(), msgs[0]);
}
}
package com.zxs.springbootmybatisflex.exception;
import com.zxs.springbootmybatisflex.exception.code.ResponseCodeInterface;
public class BusinessException extends RuntimeException{
/**
* 异常编号
*/
private final int messageCode;
/**
* 对messageCode 异常信息进行补充说明
*/
private final String detailMessage;
public BusinessException(int messageCode,String message) {
super(message);
this.messageCode = messageCode;
this.detailMessage = message;
}
/**
* 构造函数
* @param code 异常码
*/
public BusinessException(ResponseCodeInterface code) {
this(code.getCode(), code.getMsg());
}
public int getMessageCode() {
return messageCode;
}
public String getDetailMessage() {
return detailMessage;
}
}
package com.zxs.springbootmybatisflex.exception;
import com.zxs.springbootmybatisflex.exception.code.ResponseCodeInterface;
public class RoleSaveException extends RuntimeException{
/**
* 异常编号
*/
private final int messageCode;
/**
* 对messageCode 异常信息进行补充说明
*/
private final String detailMessage;
public RoleSaveException(int messageCode, String message) {
super(message);
this.messageCode = messageCode;
this.detailMessage = message;
}
/**
* 构造函数
* @param code 异常码
*/
public RoleSaveException(ResponseCodeInterface code) {
this(code.getCode(), code.getMsg());
}
public int getMessageCode() {
return messageCode;
}
public String getDetailMessage() {
return detailMessage;
}
}
package com.zxs.springbootmybatisflex.mapper;
import com.mybatisflex.core.BaseMapper;
import com.zxs.springbootmybatisflex.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper {
}
package com.zxs.springbootmybatisflex.service.impl;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.zxs.springbootmybatisflex.entity.User;
import com.zxs.springbootmybatisflex.mapper.UserMapper;
import com.zxs.springbootmybatisflex.service.UserService;
import org.springframework.stereotype.Service;
import static com.zxs.springbootmybatisflex.entity.table.UserTableDef.USER;
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
@Override
public User selectUserById(Long id) {
return getById(id);
}
@Override
public User selectUserById2(Long id) {
QueryWrapper queryWrapper = QueryWrapper.create().where(USER.ID.eq(id));
return getOne(queryWrapper);
}
@Override
public void deleteUser(Long id) {
removeById(id);
}
@Override
public void deleteUser3(Long id) {
QueryWrapper queryWrapper = QueryWrapper.create().where(USER.ID.eq(id));
remove(queryWrapper);
}
}
package com.zxs.springbootmybatisflex.service;
import com.mybatisflex.core.service.IService;
import com.zxs.springbootmybatisflex.entity.User;
public interface UserService extends IService {
User selectUserById(Long id);
User selectUserById2(Long id);
void deleteUser(Long id);
void deleteUser3(Long id);
}
package com.zxs.springbootmybatisflex.uitl;
import com.zxs.springbootmybatisflex.exception.code.BaseResponseCode;
import com.zxs.springbootmybatisflex.exception.code.ResponseCodeInterface;
import lombok.Data;
@Data
public class DataResult{
/**
* 请求响应code,0为成功 其他为失败
*/
private int code;
/**
* 响应异常码详细信息
*/
private String msg;
/**
* 响应内容 , code 0 时为 返回 数据
*/
private T data;
public DataResult(int code, T data) {
this.code = code;
this.data = data;
this.msg=null;
}
public DataResult(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public DataResult(int code, String msg) {
this.code = code;
this.msg = msg;
this.data=null;
}
public DataResult() {
this.code= BaseResponseCode.SUCCESS.getCode();
this.msg=BaseResponseCode.SUCCESS.getMsg();
this.data=null;
}
public DataResult(T data) {
this.data = data;
this.code=BaseResponseCode.SUCCESS.getCode();
this.msg=BaseResponseCode.SUCCESS.getMsg();
}
public DataResult(ResponseCodeInterface responseCodeInterface) {
this.data = null;
this.code = responseCodeInterface.getCode();
this.msg = responseCodeInterface.getMsg();
}
public DataResult(ResponseCodeInterface responseCodeInterface, T data) {
this.data = data;
this.code = responseCodeInterface.getCode();
this.msg = responseCodeInterface.getMsg();
}
public static DataResult success(){
return new DataResult();
}
public static DataResult success(T data){
return new DataResult(data);
}
public static DataResult getResult(int code,String msg,T data){
return new DataResult(code,msg,data);
}
public static DataResult getResult(int code,String msg){
return new DataResult(code,msg);
}
public static DataResult getResult(BaseResponseCode responseCode){
return new DataResult(responseCode);
}
public static DataResult getResult(BaseResponseCode responseCode,T data){
return new DataResult(responseCode,data);
}
}
package com.zxs.springbootmybatisflex;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.zxs.springbootmybatisflex.mapper")
public class SpringbootMybatisFlexApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisFlexApplication.class, args);
}
}