Springboot+MybatilsPlus+Redis整合

Springboot+MybatilsPlus+Redis整合

1. 新建Maven工程,如下所示:

 

2. 添加pom.xml文件

xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.yongbosoftgroupId>
    <artifactId>springboot04artifactId>
    <version>1.0-SNAPSHOTversion>

    <parent>
        <artifactId>spring-boot-starter-parentartifactId>
        <groupId>org.springframework.bootgroupId>
        <version>2.7.10version>
    parent>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.4.0version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-redisartifactId>
            <version>1.3.8.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-elasticsearchartifactId>
        dependency>
    dependencies>




3. 编写配置文件 application.properties

 

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=******
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8

##SQL 数据初始化 2.5.0 初始化改到sql.init配置
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:sql/schema.sql
spring.sql.init.data-locations=classpath:sql/data/data.sql

server.port=80


## mybatis-plus配置
mybatis-plus.mapper-locations=classpath*:mapper/*.xml


##定义表前缀
## mybatis-plus.global-config.db-config.table-prefix=tb_


##配置Redis连接
#配置redis地址
spring.redis.host=127.0.0.1
#redis端口号
spring.redis.port=6379
#redis的服务器连接密码
spring.redis.password=

 

 

4. 编写Springboot启动类


package com.yongbosoft.union;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}


 

5. 编写MybatisPlus分页类

 

package com.yongbosoft.union.config;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.yongbosoft.union.mapper*")
public class MybatisPlusConfig {


    //PaginationInnerInterceptor 分页插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}

 

 

6. 编写Mybatis配置文件

xml version="1.0" encoding="UTF-8"?>
mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yongbosoft.union.mapper.UserMapper">


    <select id="findUserGtAge" parameterType="int" resultType="com.yongbosoft.union.pojo.User">
        select * from user where age > #{age}
    select>
mapper>

 

7.编写mapper类

package com.yongbosoft.union.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yongbosoft.union.pojo.User;

import java.util.List;


/**
 * BeseMapper 基础接口
 */
public interface UserMapper extends BaseMapper<User> {

    public List<User> findUserGtAge(int age);
    
}


 

8. 编写实体Bean

 

package com.yongbosoft.union.pojo;


import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

//Uers 对象和 user表如何进行关联

@Data
//@TableName("user")  //如果表名和对象名相同
//tb_user
//@TableName("tb_user")
public class User {

    private Long id;
    //表字段是user_name
    //@TableField("t_name")
    //@TableField("user_name")可以不用加,mybatisplus采用驼峰处理写法,自动处理
    private String userName;
    private String email;
    private Integer age;
}

 

9. 编写Service 和ServiceImpl实现类

 


package com.yongbosoft.union.service;

import com.yongbosoft.union.pojo.User;

import java.util.List;

public interface UserService {

    /**
     * 全部查询
     * @return
     */
    public List<User> findAll();

    /**
     * 分页查询
     * @param current
     * @param pageSize
     * @return
     */
    public List<User> findPage(int current,int pageSize);


    /**
     * 年龄大于 Number 查询
     * @param age
     * @return
     */
    public List<User> findUserGtAge(int age);


    /**
     * 年龄大于Number 查询
     * @param age
     * @return
     */
    public List<User> findUserGtAgeNew(int age);

}

 

package com.yongbosoft.union.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yongbosoft.union.mapper.UserMapper;
import com.yongbosoft.union.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.selectList(new LambdaQueryWrapper<>());
    }

    @Override
    public List<User> findPage(int current, int pageSize) {

        //分页查询
        Page<User> page = new Page<User>(current,pageSize);
        Page<User> userPage = userMapper.selectPage(page,new LambdaQueryWrapper<>());
        log.info("total:{}",userPage.getTotal());
        log.info("pages:{}",userPage.getPages());
        return userPage.getRecords();
    }

    @Override
    public List<User> findUserGtAge(int age) {
        return userMapper.findUserGtAge(age);
    }

    @Override
    public List<User> findUserGtAgeNew(int age) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.gt(User::getAge,21);
        return userMapper.selectList(queryWrapper);
    }

}

 

10. 编写 controller

 

 

package com.yongbosoft.union.controller;

import com.yongbosoft.union.pojo.User;
import com.yongbosoft.union.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * Spring中,@RestController的作用等同于将@Controller@ResponseBody两个注解结合使用。
 */

@RestController
//@Controller
//@ResponseBody
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    //http://localhost/user/findAll
    @GetMapping("findAll")
    public List<User> findAll(){
        return userService.findAll();
    }


    //http://localhost/user/findPage?page=1&pageSize=2
    @GetMapping("findPage")
    public List<User> findPage(@RequestParam("page") Integer page,
                               @RequestParam("pageSize") Integer pageSize){
        return userService.findPage(page,pageSize);
    }

    /**
     * 传统方法
     * @return
     */
    //http://localhost/user/findUserGtAge
    @GetMapping("findUserGtAge")
    public List<User> findUserGtAge(){
        return userService.findUserGtAge(20);
    }

    /**
     * 通过新的查询方法实现查询功能
     * @return
     */
    //http://localhost/user/findUserGtAgeNew
    @GetMapping("findUserGtAgeNew")
    public List<User> findUserGtAgeNew(){
        return userService.findUserGtAgeNew(24);
    }

}

 

 

11. 编写 读写 Redis 测试类

 

package com.yongbosoft.union;

import com.yongbosoft.union.pojo.Address;
import com.yongbosoft.union.pojo.Person;
import com.yongbosoft.union.repository.PersonRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

/**
 * 操作Redis,用户数据的保存和查询
 */


@SpringBootTest
public class TestES {


    //测试整合Redis
    @Autowired
    private PersonRepository personRepository;


    /**
     * 保存数据到Redis
     */
    @Test
    public void savePerson(){
        Person person = new Person();
        person.setFirstname("");
        person.setLastname("");

        Address address  = new Address();
        address.setCity("北京");
        address.setCountry("中国");
        person.setAddress(address);

        personRepository.save(person);

        Person person1 = new Person();
        person1.setFirstname("");
        person1.setLastname("");

        Address address1 = new Address();
        address1.setCountry("中国");
        address1.setCity("天津");
        person1.setAddress(address1);
        personRepository.save(person1);

    }

    @Test
    public void delPerson(){
        personRepository.deleteById("76c98d14-c9b8-4577-81cc-cbb16dc70f21");
    }


    /**
     * Redis中根据城市名称查询实体对象,并打印输出
     */
    @Test
    public void selectPerson(){

        List<Person> list = personRepository.findByAddress_City("天津");
        for (Person person:list){
            System.out.println(person);
        }
    }

    @Test
    public void selectListPerson(){
        List<Person> lists = personRepository.findByAddress_Country("中国");
        for (Person person:lists){
            System.out.println(person);
        }
    }


    @Test
    public void testSave(){

    }
}

 

12 运行效果

12.1 全量查询

 

12.2 分页查询 12.3 比较查询

 

 

13. 运行测试类保存数据到Redis中

 

13.1)保存数据到Redis中

/**
 * 保存数据到Redis
 */
@Test
public void savePerson(){
    Person person = new Person();
    person.setFirstname("");
    person.setLastname("");

    Address address  = new Address();
    address.setCity("北京");
    address.setCountry("中国");
    person.setAddress(address);

    personRepository.save(person);

    Person person1 = new Person();
    person1.setFirstname("");
    person1.setLastname("");

    Address address1 = new Address();
    address1.setCountry("中国");
    address1.setCity("天津");
    person1.setAddress(address1);
    personRepository.save(person1);

}


13.2)删除Redis中的数据

@Test
public void delPerson(){
    personRepository.deleteById("76c98d14-c9b8-4577-81cc-cbb16dc70f21");
}



13.3)根据名称查询数据
@Test
public void selectListPerson(){
    List<Person> lists = personRepository.findByAddress_Country("中国");
    for (Person person:lists){
        System.out.println(person);
    }
}

 

 

至此 Springboot + MybatisPlus +Redis + MySQL 整合完成
如果需要源码或者相关技术咨询,请加V monjeo2022
感谢您的浏览!