6 Star 30 Fork 10

一阵清风 / mybatis-plugs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.en.md 22.79 KB
一键复制 编辑 原始数据 按行查看 历史
wdyun 提交于 2022-08-25 14:54 . readme修改2国际化

Mybatis-plugs

🍑 A mybatis tool that simplifys code

👉 https://gitee.com/wdyun/mybatis-plugs 👈

👉 mybatis-plugs 👈

Maven Central


🌎Chinese Documentation

📚 Brief introduction

mybatis-plugs is an enhanced persistence layer framework developed based on mybatis.

Just introduce dependencies in the springboot project mybatis-plugs-spring-boot-starter

You can simplify the crud operation of mybatis without writing the basic addition, deletion, modification and query SQL

🍺 Purpose

mybatis-plugs designed to simplify code and provide efficiency!

🐮 Characteristic

  • Do not make any changes to mybatis, only do the expansion and enhancement of mybatis.
  • The code is automatically generated, and the xxxMapper.java、xxxService.java、xxxServiceImpl.java、xxxController.java、xxxMapper.xml can be quickly generated according to the table name.
  • Less dependence, only relying on mybatis-plugs-spring-boot-starter
  • Automatically fill in the creation time, update time, creator and other information.
  • Built in paging plug-in based on mybatis physical paging.
  • Automatically record the execution time of SQL to facilitate locating slow queries.
  • The code is simple and easy to understand.
  • The built-in interface interceptor determines whether to intercept requests through annotations.
  • Support logical deletion through annotations.

📦 Quick start

We will explain the powerful functions of mybatis plugs through a simple demo. Before that, we assume that you have:
a.Have java development environment, corresponding IDE and MySQL database
b.Familiar with springboot
c.Familiar with Maven

What do we need to do if we use mybatis plugs to add, delete, modify and check the table from scratch?

👉 1.Create table

There is an existing sys_user table, and the corresponding database SQL script is as follows:

CREATE TABLE sys_user (
  id bigint NOT NULL COMMENT '主键ID',
  name varchar(30) COMMENT '姓名',
  age int COMMENT '年龄',
  phone varchar(11) COMMENT '电话',
  PRIMARY KEY (id)
)

👉 2.Create a springboot project
Create a springboot project using idea
First step:
Image text Step 2:
Image text Step 3:Select the Lombok plug-in
Image text Basic structure of the project
Image text

👉 3.Configure Maven

Add the Maven dependency of mybatis plug in the pom.xml file of the project:mybatis-plugs-spring-boot-starter

Latest version:Maven Central


<dependency>
  <groupId>com.enbatis</groupId>
  <artifactId>mybatis-plugs-spring-boot-starter</artifactId>
  <version>Latest version</version>
</dependency>

👉4.Configureyml

update application.properties为application.yml
add dev env: application-dev.yml
add test env: application-test.yml
add pro env: application-pro.yml

explain
1.The development environment is the configuration we use for development
2.The test environment is the configuration used by testers for software testing
3.Configuration used by production environment for online deployment
The configuration in application.yml is:

spring:
  profiles:
    active: dev
server:
  port: 8080

tips:

spring:
  profiles:
    active: dev

Specify the environment to use

server:
  port: 8080

Specify that the port started by the project is port 8080
The content of application-dev.yml is as follows:

mybatis:
  mapper-locations: classpath:/mapping/*.xml
  type-aliases-package: com.panpan.housesale.entity
  configuration:
    map-underscore-to-camel-case: true
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/test_db?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
    username: root
    password: 111111
    driver-class-name: com.mysql.cj.jdbc.Driver
    filters: stat,wall
    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
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

👉5.Modify startup class
Annotate mapper scan on the startup class

@MapperScan("com.xxxxx.xxxxx.mapper")

🍊 Code generator

We can quickly generate entity, controller, mapper, service, serviceimpl, mapping.xml through database tables

The code generation needs to connect to the database, so we need to connect to the database. We only need to configure the basic information of the database and generate the class CodeGenerator2 by using the code of mybatis-plugs.
👉1.Configure code generator
Create the generator class codegenerate under the same level directory of the startup class

public class CodeGenerate { 
  private static String url="jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false"; 
   private static String user="root"; 
   private static String psd="111111"; 
   private static String filePath="D://generate_code//"; 
   public static void main(String[] args) { 
    CodeGenerator2 codeGenerator2=new CodeGenerator2(url,user,psd,filePath); 
    codeGenerator2.generate(CodeGenerate.class); 

node:
url: Database connection URL
root: Database Username
psd: Database password
filePath: Java code generation location (to prevent code overwriting, we will not automatically generate to the corresponding code location)
CodeGenerator2: mybatis-plugs代码核心生成器

👉2.Usage method
1.Execute the main method
2.In the console, enter the author and the table to generate the code
Image text 3.After entering, click enter
4.When the following information is output, the code generation is successful
Image text 5.Go to the code generation location to view the generated code
Image text 👉3.Create code package
Create code package :entity、controller、mapper、service、impl以及xml的文件夹
Image text 👉4.Copy Code
Copy the generated code to the corresponding folder
Image text

👉5.Start project
Start project access http://localhost:8080/v1/sys_user/list Query all users list

🐮CRUD Interface

Note: by encapsulating the BaseService interface of mybatis, the crud operation of the database can be quickly realized

Generic t is any entity object; The parameter serializable is any type of primary key mybatis-plugs does not recommend using a composite primary key convention. Each table has its own unique ID primary key; The object wrapper is a conditional constructor.

1.Insert Interface
1.1 Single insert

/**
 * Insert a record
 * @param entity Incoming Insert Object
 * @return T
 */
T insert(T entity);

Usage: write code in the serviceImpl layer as follows

SysUser user = new SysUser();
user.setName("Tom");
user.setAge(32);
user.setPhone("13615425135");
super.insert(user);

1.2 Batch insert

/**
  * Batch insert
  * @param entityList
  * @return
*/
int saveBatch(List<T> entityList);

Usage: write code in the serviceImpl layer as follows

List<SysUser> sysUserList = new ArrayList<>();
for (int i = 0; i <10 ; i++) {
    SysUser sysUser = new SysUser();
    sysUser.setName("Tom"+i);
    sysUser.setAge(30+i);
    sysUser.setPhone("1361542513"+i);
    sysUserList.add(sysUser);
}
super.saveBatch(sysUserList);

2.Delete Interface
2.1 Single delete

/**
 * Delete a piece of data according to ID 
 * @param id Incoming query ID
 * @return Number of deleted items
 */
int deleteById(Serializable id);

Usage: write code in the serviceImpl layer as follows

super.deleteById(12000012);

2.2 Batch delete

/**
 * Batch delete
 * @param wrapper
 * @return
 */
int delete(Wrapper<T> wrapper);

Usage: write code in the serviceImpl layer as follows

Wrapper wrapper = new Wrapper<SysUser>();
wrapper.eq("age",30);
wrapper.like("name","Tom");
super.delete(wrapper);

Note: the conditional constructor will be specially explained.

3 Update Interface
3.1 Single update

/**
 * Update a piece of data according to ID
 * @param bean Incoming update object
 * @return Return the number of updates
 */
int updateById(T bean);

Usage: write code in the serviceImpl layer as follows

SysUser sysUser = new SysUser();
sysUser.setId(1234561114L);
sysUser.setPhone("13615425135");
sysUser.setAge(36);
super.updateById(sysUser);

3.2 Batch update

/**
 * Batch update
 * @param entityList
 * @return
 */
int updateBatchById(List<T> entityList);

Usage: write code in the serviceImpl layer as follows

List<SysUser> sysUserList = new ArrayList<>();
    SysUser sysUser = new SysUser();
    sysUser.setId(111100001101L);
    sysUser.setAge(35);
sysUserList.add(sysUser);
    SysUser sysUser2 = new SysUser();
    sysUser2.setId(111100001102L);
    sysUser2.setAge(32);
sysUserList.add(sysUser);
super.updateBatchById(sysUserList);
  1. List query interface
/**
 * List query data
 * @param wrapper query condition
 * @return list
 */
List<T> list(Wrapper<T> wrapper);

Usage: write code in the serviceImpl layer as follows

Wrapper wrapper = new Wrapper<SysUser>();
wrapper.like("name","Tom");
List<SysUser> list = super.list(wrapper);
  1. Page query
/**
 * Page query 
 * @param page
 * @param wrapper
 * @return
 */
Page<T> page(Page<T> page, Wrapper<T> wrapper);

Usage: write code in the controller layer as follows

@PostMapping("/page")
public ResultReturn<Page<SysUser>> getPage(@RequestBody SysUser user){
    return success(sysUserService.page( getPage(),new Wrapper(user)));
}

Note:controller needs to extend BaseController

6.Query single

/**
 * Get by ID 
 * @param id 对象ID
 * @return object
 */
T getById(Serializable id);

Usage: write code in the controller layer as follows

@GetMapping("/{id}")
public ResultReturn<SysUser> get(@PathVariable("id") Long id) {
    return success(sysUserService.getById(id));
}

7.Query quantity

/**
 * query count
 * @param wrapper query condition
 * @return number
 */
int selectCount(Wrapper<T> wrapper);

Usage: write code in the serviceImpl layer as follows

Wrapper wrapper = new Wrapper<SysUser>();
wrapper.like("name","Tom");
int count = super.selectCount(wrapper);

🐮 Conditional constructor Wrapper

1 eq constructor
If we want to quickly query the database table sys_ How to operate when the user's name is "Tom"?
Answer: just call the service to call the list, pass in the condition constructor wrapper, and the wrapper calls the eq method. The following method is to query the sysuser list whose name is Tom

sysUserService.list(new Wrapper<>(sysUser).eq("name","Tom"));

2 ne constructor
如果我们想快速查询数据库表sys_user 的姓名不是 “Tom” 如何进行操作呢?
If we want to quickly query the database table sys_user, How to operate if the sys_user's name is not "Tom"?
Answer: just call the service to call the list, pass in the condition constructor wrapper, and the wrapper calls the ne method. The following method is to query the sysuser list whose name is not Tom

sysUserService.list(new Wrapper<>(sysUser).ne("name","Tom"));

3 like constructor
If we want to fuzzy query by name, how do we do it?
Answer: just call the list to pass in the condition constructor wrapper, and the wrapper calls the like method. The following method is a fuzzy query based on the name "Tom"

sysUserService.list(new Wrapper<>(sysUser).like("name","Tom"));

4 in constructor If we want to query the names of "Tom", "Jack" and "June", how do we operate?
Answer: just call the service to pass in the condition constructor wrapper and the wrapper to call the in method to pass in the ArrayList

List arrayList=new ArrayList<>(); 
arrayList.add("Tom"); 
arrayList.add("Jack"); 
arrayList.add("June");
sysUserService.list(new Wrapper<>(sysUser).in("name",arrayList));

Extension:

The above only lists the methods of some conditional constructors. We also have 我们还有notNull (non null query), isNull (null value query), setSqlSelect (fixed column query), and so on. For more information, please check mybatis plugs

🐮 Login authentication

Mybatis-plugs internally encapsulates JWT Token authentication, which can be used directly when performing login function.
1.Create JWT
Mybatis-plugs provides JwtUtil tool classes to create token. The specific methods are as follows:

/**
 * The first three parameters are some information of the user token, such as ID, permission, name, etc. Don't put private information into (everyone can get it)
 * @param map Information to be encrypted
 * @param security Encrypted string
 * @param expire Failure time (MS)
 * @return
 */
public static String createJwt(Map<String,Object> map,String security,long expire) {
    //Add parameters that make up JWT
    JwtBuilder builder = Jwts.builder()
            .setHeaderParam("typ", "JWT")
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis()+expire))
            .setClaims(map)
            .signWith(generalKey(security),SignatureAlgorithm.HS256);
    //Create JWT
    return builder.compact();
}

If the failure time is not transmitted, it will default to 24 hours. We provide an overloaded method

/**
 * When creating JWT, the default expiration time is 24 hours
 * @param map Information to be encrypted
 * @param base64Security security Encrypted string
 * @return
 */
public static String createJwt(Map<String, Object> map, String base64Security) {
    return createJwt(map,base64Security,EXPIRE);
}

How to use it? Please refer to the following code:

//Get login user name
String username =user.getUsername();
String password= MD5Util.generate(user.getPassword());
List<SysUser> list=list(new Wrapper().eq("username",username).eq("password",password));
Optional<SysUser> first= list.stream().filter(dbUser->dbUser.getUsername().equals(username)&&dbUser.getPassword().equals(password)).findFirst();
if (first.isPresent()){
    user.setUsername(username);
    SysUser sysUser= first.get();
    Map<String,Object> userMap = new HashMap<>();
    userMap.put("userId",sysUser.getId()+"");
    userMap.put("name",sysUser.getName());
    userMap.put("companyId",sysUser.getCompanyId());
    userMap.put("username",sysUser.getUsername());
    userMap.put("effective", System.currentTimeMillis()+(120*60*1000));
    String token= JwtUtil.createJwt(userMap, JwtUtil.LOGIN_BASE);
    response.addHeader("authorization",token);
    Cookie cookie = new Cookie("authorization",token);
    cookie.setDomain(domain);
    cookie.setPath("/");

    response.addCookie(cookie);
    SysUser user1= first.get();
    SysUserVO vo = new SysUserVO();
    BeanUtils.copyProperties(user1,vo);
    vo.setAuthorization(token);
    vo.setImgHead(sysUser.getAvatarUrl());
    return  ResultReturn.success(vo);
}

Mybatis-plugs provides jwtutil tool class to parse tokens. The specific methods are as follows:

/**
 * decrypt
 * @param jsonWebToken token String
 * @param security security Encrypted string
 * @return
 */
public static Claims parseJwt(String jsonWebToken, String security) {
    try {
        Jws<Claims> claimsJws = Jwts.parserBuilder()
          .setSigningKey(Keys.hmacShaKeyFor(security.getBytes(StandardCharsets.UTF_8)))
          .build().parseClaimsJws(jsonWebToken);
        return claimsJws.getBody();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

3.Encapsulate login entity
After successful login, you can use the token to obtain the account of the login entity to obtain the login user. The specific method is as follows:

public static Account account(String token,String security){
    Claims claims= JwtUtil.parseJwt(token,security);
    String userId= (String)claims.get("userId");
    String username= (String)claims.get("username");
    Integer companyId= (Integer)claims.get("companyId");
    Account account = new Account();
    account.setId(Long.parseLong(userId));
    account.setUsername(username);
    if(null!=companyId){
        account.setCompanyId(Long.parseLong(Integer.toString(companyId)));
    }
    return account;
}

Where token is the token generated by JWT, security is the encrypted string, and the token can be obtained from the head or cookie.
See the following codes for specific usage:

Account account = JwtUtil.account(request.getHeader("Authorization"),"xxxx");

🐮 Interceptor

1.Introduce
The interceptor of mybatis-plugs has the functions of recording the execution time of the request method and filtering the requests of non login users. You can use annotations in the controller to intercept the non login requests.

Usage method: customize the interceptor and inherit the class: com.enbatis.mybatisplugs.commons.Interceptor.Interceptor

The example code is as follows:

@Component
public class ReqInterceptor extends Interceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
         return super.preHandle(request,response,handler);
    }
}

Next, register the interceptor, create a new class WebConfigurer and implement the WebMvcConfigurer interface. The code is as follows:

@Configuration
public class WebConfigurer implements WebMvcConfigurer {
    @Autowired
    private ReqInterceptor interceptor;
    /**
     * @Description  This method is used to configure static resources, such as HTML, JS, CSS, etc
     * @Param [registry]
     * @return void
     **/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    }

    /**
     * @Description  This method is used to register the interceptor. The interceptor written by us needs to be registered here to take effect
     * @Date 9:34 2022/2/7
     * @Param [registry]
     * @return void
     **/
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns("/**") Indicates that all requests are intercepted
        registry.addInterceptor(interceptor).addPathPatterns("/**");
    }
}

After configuration, the function of mybatis-plugs interceptor can be realized.
2.Intercept request
The controller method can intercept requests without any annotation or @Login(handler = Handler.INTERCEPT). If the user accesses the interface without logging in, the system will throw the information of not logging in. 3.Release request
Some requests can be accessed directly without login, such as registration interface, login interface, etc. at this time, the "@Login(handler = Handler.PASS)" annotation can be used to release the request, that is, access can be accessed without login. The code example is as follows: Registration interface:

@Login(handler = Handler.PASS)
@PostMapping("/register")
public ResultReturn registerUser(@RequestBody SysUserVO sysUser){
    sysUser.setCompanyId(0L);
    return  sysUserService.registerUser(sysUser);
}

Login interface:

@Login(handler = Handler.PASS)
@PostMapping("/login")
public ResultReturn login(@RequestBody SysUserVO vo){
       return  sysUserService.login(vo,request,response);
}

🐮 Enum conversion

Sometimes the database stores numeric types, but we need to use enumeration classes in entity classes. In this case, mybatils plugs provides a convenient and fast way to meet the requirements.
1.Define enumeration class

First, customize the enumeration class and implement the com.enbatis.mybatisplugs.enums.BaseEnum interface. The code is as follows:

import com.enbatis.mybatisplugs.enums.BaseEnum;
public enum StatusEnum implements BaseEnum<StatusEnum,Integer> {
    ORDERED(0,"OrderPlaced"),
    PAYED(1,"Paid"),
    DELIVER(2,"ToBeShipped"),
    DELIVERED(3,"Shipped"),
    RECEIVED(4,"ReceivedGoods"),
    OK(5,"OrderEnd");

    private final Integer value;
    private final String description;

    StatusEnum(Integer value, String description) {
        this.value = value;
        this.description = description;
    }
    public StatusEnum getEnumByValue(Long value) {
        StatusEnum[] enums = StatusEnum.values();
        for (StatusEnum e : enums) {
            if (e.getValue().equals(value)) {
                return e;
            }
        }
        return null;
    }
    @Override
    public Integer getValue() {
        return value;
    }

    @Override
    public String getDescription() {
        return description;
    }
}

2.Entity class reference enumeration
You need to change the field to enumeration type in the entity class, as follows:

/**
 * Orde status(
 */
private StatusEnum status;

3.Add profile

You need to add a class for enum conversion in the configuration file:com.enbatis.mybatisplugs.plugin.parser .AutoEnumTypeHandler

The code is as follows:

mybatis:
  mapper-locations: classpath:/mapping/*.xml
  type-aliases-package: com.panpan.housesale.entity
  configuration:
    map-underscore-to-camel-case: true
    #log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
default-enum-type-handler: com.enbatis.mybatisplugs.plugin.parser.AutoEnumTypeHandler

Through these three steps, you can realize the matching between the database field type and the enumeration type。

🍺 Donation

If you think it's not bad, invite the author to have a cup of coffee
Wechat support
Image text

Alipay Sweep support

Image text

Java
1
https://gitee.com/wdyun/mybatis-plugs.git
git@gitee.com:wdyun/mybatis-plugs.git
wdyun
mybatis-plugs
mybatis-plugs
dev

搜索帮助

53164aa7 5694891 3bd8fe86 5694891