SpringBoot整合MyBatis-Plus

簡介

Mybatis-Plus是一個Mybatis框架的增強插件。
即可快速進(jìn)行 CRUD 操作,從而節(jié)省大量時間.代碼生成,分頁,性能分析等功能一應(yīng)俱全,
官網(wǎng)

1.建student數(shù)據(jù)表

DROP TABLE IF EXISTS `student`;

CREATE TABLE `student` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(200) COLLATE utf8_bin DEFAULT NULL,
  `age` tinyint(3) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

LOCK TABLES `student` WRITE;

INSERT INTO `student` (`id`, `name`, `age`) VALUES (1,'點點',16),(2,'平平',16),(3,'美美',16),(4,'團(tuán)團(tuán)',16);

UNLOCK TABLES;
#COLLATE 表示排序規(guī)則

項目目錄


項目配置

server.port=8080
## ==============================
## MySQL connection config
## ==============================
spring.datasource.url=jdbc:mysql://localhost:3306/wg_insert?useUnicode=true&characeterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=159682
### ==============================
### Hikari 數(shù)據(jù)源專用配置
### ==============================
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
### ==============================
### mybatis配置
### ==============================
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.type-aliases-package=com.wg.mybits.entity
#<!--開啟駝峰式命名,數(shù)據(jù)庫的列名能夠映射到去除下劃線駝峰命名后的字段名-->
mybatis-plus.configuration.map-underscore-to-camel-case=true
#<!--全局地開啟或關(guān)閉配置文件中的所有映射器已經(jīng)配置的任何緩存-->
mybatis-plus.configuration.local-cache-scope=session
#開啟二級緩存
mybatis-plus.configuration.cache-enabled=true
#這個配置會將執(zhí)行的sql打印出來,在開發(fā)或測試的時候可以用
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# ==============================
# Thymeleaf configurations
# ==============================
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=UTF-8
# ==============================
# redis configurations
# ==============================
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
# Redis數(shù)據(jù)庫索引(默認(rèn)為0)
spring.redis.database=0
# 連接池最大連接數(shù)(使用負(fù)值表示沒有限制)
spring.redis.lettuce.pool.max-active=8  
# 連接池最大阻塞等待時間(使用負(fù)值表示沒有限制)
spring.redis.lettuce.pool.max-wait=-1ms
# 連接池中的最大空閑連接
spring.redis.lettuce.pool.max-idle=8  
# 連接池中的最小空閑連接
spring.redis.lettuce.pool.min-idle=0

2.編寫實體類 StudentEntity.java

package com.wg.mybits.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
@TableName("student")
public class StudentEntity implements Serializable {

    // 學(xué)號
    @TableId(type = IdType.AUTO)
    private Integer id;

    // 姓名
    private String name;

    // 年齡
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("StudentEntity{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }
}

3.編寫StudentMapper(即Dao層)

繼承BaseMapper就自動會有很多基礎(chǔ)的CRUD方法具體參考

package com.wg.mybits.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wg.mybits.entity.StudentEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

@Service
public interface StudentMapper extends BaseMapper<StudentEntity> {
    IPage<StudentEntity> selectPageVo(Page<StudentEntity> param, @Param("age") int age);
}

4.編寫StudentService(即service層)

繼承IService也會有很多基礎(chǔ)方法具體參考

package com.wg.mybits.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.wg.mybits.entity.StudentEntity;

public interface StudentService extends IService<StudentEntity> {
    public IPage<StudentEntity> selectUserPage(Page<StudentEntity> page, int age);
}

StudentServiceImpl

package com.wg.mybits.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wg.mybits.entity.StudentEntity;
import com.wg.mybits.mapper.StudentMapper;
import com.wg.mybits.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper,StudentEntity> implements StudentService{
    @Autowired
    private StudentMapper studentMapper;
    @Override
    @Cacheable(value="user",key="'userList'")
    public IPage<StudentEntity> selectUserPage(Page<StudentEntity> page, int age) {
        IPage<StudentEntity> pageResult = studentMapper.selectPageVo(page,age);
        return pageResult;
    }
}

5.配置文件的編寫

這里采用redis作為二級緩存
MybatisPlusConfig

package com.wg.mybits.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@MapperScan("com.wg.mybits.mapper")
public class MybatisPlusConfig {
    /**
     * mybatis-plus SQL執(zhí)行效率插件【生產(chǎn)環(huán)境可以關(guān)閉】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
    /**
     * 分頁插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 設(shè)置請求的頁面大于最大頁后操作, true調(diào)回到首頁,false 繼續(xù)請求  默認(rèn)false
        // paginationInterceptor.setOverflow(false);
        // 設(shè)置最大單頁限制數(shù)量,默認(rèn) 500 條,-1 不受限制
        // paginationInterceptor.setLimit(500);
        return paginationInterceptor;
    }
}

RedisConfig

package com.wg.mybits.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.time.Duration;

@EnableCaching // 開啟緩存
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    //緩存管理器
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)); // 設(shè)置緩存有效期一小時
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }
    /**
     *  配置自定義redisTemplate
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setValueSerializer(jackson2JsonRedisSerializer());
        //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
    /**
     * json序列化
     * @return
     */
    @Bean
    public RedisSerializer<Object> jackson2JsonRedisSerializer() {
        //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        serializer.setObjectMapper(mapper);
        return serializer;
    }
}

6.支持自定義的sql

這是分頁的sql
StudentMapper.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.wg.mybits.mapper.StudentMapper">
    <select id="selectPageVo" resultType="com.wg.mybits.entity.StudentEntity" parameterType="int">
    SELECT * FROM student WHERE age = #{age}
    </select>
</mapper>

7.測試類StudentMapperTest

包含

  • MyBatis-Plus基礎(chǔ)CRUD演示
  • QueryWrapper條件構(gòu)造器的條件查詢
  • 自定義SQL分頁查詢
package com.wg.mybits;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wg.mybits.entity.StudentEntity;
import com.wg.mybits.service.impl.StudentServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentMapperTest {
    @Autowired
    private StudentServiceImpl studentService;
    @Test
    public void testGet(){
        //條件查詢
        QueryWrapper<StudentEntity> queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.lambda().eq(StudentEntity::getAge,16);
        queryWrapper1.eq("age",16);
        System.out.println(studentService.getMap(queryWrapper1).size());
        System.out.println(studentService.getById(1).getName());
        System.out.println(studentService.getById(1).getName());
        System.out.println(studentService.getById(1).getName());
        //查詢age=16的學(xué)生,并且分頁
        Page<StudentEntity> page = new Page<>(1,2);
        System.out.println(studentService.selectUserPage(page,16).getSize());
        //檢測二級緩存
        @System.out.println(studentService.selectUserPage(page,16).getSize());
    }
}
mybatis中同一個mapper中的多個查詢?yōu)槭裁词菃⒂枚鄠€sqlSession來處理的?
因為你的userMapper不是從同一個sqlSession得到,所以不能一級緩存,
SqlSession sqlSession = sqlSessionFactory.openSession();//
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
先通過同一個sqlSeesion獲取UserMapper的代理對象,
再使用代理對象調(diào)用方法,這樣在執(zhí)行相同sql語句是就不會創(chuàng)建多個SqlSesssion
redis做二級緩存
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容