mybatis微服务springboot

SpringBoot整合MyBatis-Plus

2019-10-28  本文已影响0人  盼旺

简介

Mybatis-Plus是一个Mybatis框架的增强插件。
即可快速进行 CRUD 操作,从而节省大量时间.代码生成,分页,性能分析等功能一应俱全,
官网

1.建student数据表

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,'团团',16);

UNLOCK TABLES;
#COLLATE 表示排序规则

项目目录


项目配置
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 数据源专用配置
### ==============================
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
#<!--开启驼峰式命名,数据库的列名能够映射到去除下划线驼峰命名后的字段名-->
mybatis-plus.configuration.map-underscore-to-camel-case=true
#<!--全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存-->
mybatis-plus.configuration.local-cache-scope=session
#开启二级缓存
mybatis-plus.configuration.cache-enabled=true
#这个配置会将执行的sql打印出来,在开发或测试的时候可以用
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数据库索引(默认为0)
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
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 {

    // 学号
    @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就自动会有很多基础的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也会有很多基础方法具体参考

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执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 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)); // 设置缓存有效期一小时
        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

包含

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的学生,并且分页
        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中的多个查询为什么是启用多个sqlSession来处理的?
因为你的userMapper不是从同一个sqlSession得到,所以不能一级缓存,
SqlSession sqlSession = sqlSessionFactory.openSession();//
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
先通过同一个sqlSeesion获取UserMapper的代理对象,
再使用代理对象调用方法,这样在执行相同sql语句是就不会创建多个SqlSesssion
redis做二级缓存
上一篇下一篇

猜你喜欢

热点阅读