mybatis plus 入门

mybatis plus 是中国程序员对 mybatis 的做的改变,往 hibernate 的方向靠拢了一下,宗旨是只做增强,不做改变,确实蛮好用的,下面介绍使用方法

 

1、导入依赖

<!--mybatis plus的依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatisplus.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>com.baomidou</groupId>
                    <artifactId>mybatis-plus-generator</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

 

2、application.yml 配置,大家按照自己的环境配置,不配置也可以,有默认配置的

# 容器服务
server:
  port: 8002
  servlet:
    context-path: /xiongdi-api

# spring 配置
spring:
  profiles:
    active: dev # 使用 application-dev.yml配置
  servlet:
    multipart: # 文件上传和下载
      enabled: true
      max-file-size: 100MB
      max-request-size: 100MB

# 自定义配置
xiongdi:
    redis:
      open: false # 是否开启缓存 true 开启 false 关闭

# mybatis plus的配置
mybatis-plus:
  # mybatis 的原生配置
  configuration:
    cache-enabled: false # 是否开启缓存
    map-underscore-to-camel-case: true # 是否开启自动驼峰命名规则(camel case)映射
    call-setters-on-nulls: true # MyBatis 在使用 resultMap 来映射查询结果中的列,如果查询结果中包含空值的列
    jdbc-type-for-null: 'null' # 如果type为空
  # MyBatis-Plus 全局策略配置
  global-config:
  # MyBatis-Plus 全局策略中的 DB 策略配置
    db-config:
      id-type: auto # 全局默认主键类型,AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
      field-strategy: not_null # 字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
      logic-delete-value: -1 # 逻辑已删除值,(逻辑删除下有)
      logic-not-delete-value: 0 # 逻辑未删除值,(逻辑删除下有效)
    banner: false # 是否显示mybatis-plus的图标

 

3、定义 Mapper 接口 继承 BaseMapper,继承该接口后无需编写 mapper.xml 文件,即可获得CRUD功能,泛型 T 代表实体,也就是我们从数据库查出来的数据用哪个类封装

package io.xiongdi.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.xiongdi.entity.TokenEntity;
import org.apache.ibatis.annotations.Mapper;

/**
 * TokenEntity 的操作DAO层【继承Base Mapper就具有了对TokenEntity的基本操作方法】
 * @author wujiaxing
 * @date 2019-06-30
 */
@Mapper
public interface TokenDao extends BaseMapper<TokenEntity> {
}

 

4、如果有需要自行编写的方法,也可以继续定义 mapper.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="io.xiongdi.dao.TokenDao">

</mapper>

 

5、编写 Service 接口,继承 IService,这个接口定义了很多默认抽象方法,如果方法没有自己想要的,可以自定义,泛型 T 也是实体

package io.xiongdi.service;

import com.baomidou.mybatisplus.extension.service.IService;
import io.xiongdi.entity.TokenEntity;

/**
 * token
 * @author wujiaxing
 * @date 2019-06-30
 */
public interface TokenService extends IService<TokenEntity> {

    /**
     * <p>
     *     根据请求token查询token信息
     * </p>
     * @param token
     * @return
     */
    TokenEntity queryByToken(String token);

    /**
     *  创建token
     * @param userId 用户ID
     * @return 返回token信息
     */
    TokenEntity createToken(long userId);

    /**
     * 设置token过期
     * @param userId 用户ID
     */
    void expireToken(long userId);
}

 

6、编写 service 的实现类,除了实现我们定义的接口,还要继承 ServiceImpl 类,该类泛型 M 表示你要告诉 mybatis plus 你的 Mapper 接口是哪个,一定要继承 BaseMapper 接口,泛型 T 是实体

package io.xiongdi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.xiongdi.dao.TokenDao;
import io.xiongdi.entity.TokenEntity;
import io.xiongdi.service.TokenService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.UUID;

/**
 * @author wujiaxing
 * @date 2019-07-08
 */
@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {

    /**
     * 12 小时过期 单位:毫秒
     */
    private final static int EXPIRE = 3600 * 12 * 1000;

    /**
     *  根据请求头的token查询数据库对应的token信息
     * @param token
     * @return
     */
    @Override
    public TokenEntity queryByToken(String token) {
        return this.getOne(new QueryWrapper<TokenEntity>().eq("token", token));
    }

    @Override
    public TokenEntity createToken(long userId) {
        // 得到当前时间
        LocalDateTime now = LocalDateTime.now();
        // 根据过期时间加上当前时间,得到token的有效期
        long indate = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() + EXPIRE;
        LocalDateTime tokenExpireDateTime = LocalDateTime.ofInstant(new Date(indate).toInstant(), ZoneId.systemDefault());
        // 生成token
        String token = generateToken();
        // 创建实体对象
        TokenEntity tokenEntity = TokenEntity.builder().expireTime(tokenExpireDateTime).userId(userId).token(token).updateTime(now).build();
        // 放入数据库保存
        this.saveOrUpdate(tokenEntity);
        return tokenEntity;
    }

    /**
     *  生成token
     * @return
     */
    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    public void expireToken(long userId) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        TokenEntity tokenEntity = TokenEntity.builder().userId(userId).expireTime(now).updateTime(now).build();
        this.saveOrUpdate(tokenEntity);
    }
}

 

QueryWrapper 类定义了很多条件方法,例如:like、lt、gt、eq 等等

 

posted @ 2019-07-13 22:50  渣男梦想  阅读(4562)  评论(0编辑  收藏  举报