springboot整合mybatis,redis,代码

Posted 丁春秋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合mybatis,redis,代码相关的知识,希望对你有一定的参考价值。

一 搭建项目,代码工程结构

使用idea或者sts构建springboot项目

 

 

二  数据库sql语句

SQLyog Ultimate v12.08 (64 bit)
mysql - 5.7.14-log 
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;

create table `person` (
    `id` int (11),
    `name` varchar (60),
    `age` int (11),
    `address` varchar (300)
); 
insert into `person` (`id`, `name`, `age`, `address`) values(\'1\',\'feinik1\',\'26\',\'广州\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'2\',\'feinik2\',\'25\',\'北京\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'3\',\'feinik3\',\'24\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'4\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'5\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'6\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'7\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'8\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'9\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'10\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'11\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'12\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'13\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'14\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'15\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'16\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'17\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'18\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'19\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'20\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'21\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'22\',\'zhongguo\',\'1\',\'上海\');
insert into `person` (`id`, `name`, `age`, `address`) values(\'23\',\'zhongguo\',\'1\',\'上海\');

 

三 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.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cxy</groupId>
    <artifactId>springbootredis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootredis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.41</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>mybatis generator</id>
                        <phase>package</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!--允许移动生产的文件-->
                    <verbose>true</verbose>
                    <!--允许自动覆盖文件,在开发者不可以设置为true-->
                    <overwrite>true</overwrite>
                    <!--制定生产文件的位置-->
                    <configurationFile>
                        src/main/resources/mybatis_generator.xml
                    </configurationFile>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

 

四 mybatis-gengerator的xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <!--驱动包的路径-->
    <!--<classPathEntry location="F:\\maven\\repos\\mysql\\mysql-connector-java\\5.1.34\\mysql-connector-java-5.1.34.jar"/>-->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--注释-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!--数据库连接-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/fr_db?zeroDateTimeBehavior=convertToNull&amp;
                        autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=utf-8"
                        userId="root"
                        password="1234"/>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="com.cxy.dataObject" targetProject="src/main/java">
            <!--是否对model添加构造函数-->
            <property name="constructorBased" value="false"/>
            <!--是否允许子包-->
            <property name="enableSubPackages" value="true"/>
            <!--建立的model对象是否不可变,也就是生成的model没有setter方法-->
            <property name="immutable" value="false"/>
            <property name="trimStrings" value="false"/>
        </javaModelGenerator>

        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--生成Mapper类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.cxy.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--生成与表对应的类名-->
        <table tableName="person" domainObjectName="PersonDo" enableCountByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false" selectByExampleQueryId="false"></table>

    </context>

</generatorConfiguration>

 

五代码生成

添加如图命令,然后执行,

或者参考springboot整合ssm和druid篇介绍

六 redis配置

package com.cxy.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@EnableCaching
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

 

七application.properties文件

## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/fr_db?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

## Mybatis 配置
mybatis.typeAliasesPackage=org.spring.springboot.domain
mybatis.mapperLocations=classpath:mapping/*.xml

## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=127.0.0.1
## Redis服务器连接端口
spring.redis.port=6379
## Redis服务器连接密码(默认为空)
spring.redis.password=
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
## 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
## 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
## 连接超时时间(毫秒)
spring.redis.timeout=0

 

八service.dao.controller代码

dao层:

package com.cxy.dao;

import com.cxy.dataObject.PersonDo;

import javax.validation.constraints.Size;
import java.util.List;

public interface PersonDoMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(PersonDo record);

    int insertSelective(PersonDo record);

    PersonDo selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(PersonDo record);

    int updateByPrimaryKey(PersonDo record);

    List<PersonDo> selectAllPerson();
}

service层,接口在这里就不直接粘贴了

package com.cxy.service.impl;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.cxy.dao.PersonDoMapper;
import com.cxy.dataObject.PersonDo;
import com.cxy.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl  implements PersonService {
    @Autowired
    private PersonDoMapper personDoMapper;
    @Cacheable(value = "person", key = "#id")
    @Override
    public PersonDo selectPersonByPrimaryKey(Integer id) {
        System.out.println("查询数据库");
        return personDoMapper.selectByPrimaryKey(id);
    }
    @CacheEvict(value = "person", key = "#personDo.id")
    @Override
    public Integer updatePersonByPrimaryKey(PersonDo personDo) {
        return personDoMapper.updateByPrimaryKey(personDo);
    }
    @CacheEvict(value = "person", key = "#id")
    @Override
    public Integer deletePersonByPrimaryKey(Integer id) {
        return personDoMapper.deleteByPrimaryKey(id);
    }
    @CachePut(value = "person", key = "#personDo.id")
    @Override
    public Integer savePersonDo(PersonDo personDo) {
        return personDoMapper.insert(personDo);
    }
}

controller层:

package com.cxy.controller;

import com.cxy.dataObject.PersonDo;
import com.cxy.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private PersonService personService;
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public PersonDo selectPersonByPrimaryKey(@PathVariable Integer id){
        return personService.selectPersonByPrimaryKey(id);
    }
    @RequestMapping(method = RequestMethod.PUT)
    public  Integer updatePersonByPrimaryKey(@RequestBody PersonDo personDo){
        return personService.updatePersonByPrimaryKey(personDo);
    }
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public  Integer updatePersonByPrimaryKey(@PathVariable Integer id){
        return personService.deletePersonByPrimaryKey(id);
    }
    @RequestMapping(method = RequestMethod.POST)
    public  Integer savePerson(@RequestBody PersonDo personDo){
        return personService.savePersonDo(personDo);
    }
}

九启动

package com.cxy;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.cxy.dao")
public class SpringbootredisApplication {

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

}

 

 

十运行查询:

 

 控制台输出:

第一次不走缓存,直接查询数据库,第二次走缓存

 

以上是关于springboot整合mybatis,redis,代码的主要内容,如果未能解决你的问题,请参考以下文章

springboot整合mybatis,redis,代码

springboot整合mybatis,redis,代码

springboot整合mybatis,redis,代码

6.springboot+mybatis+redis整合

springboot整合mybatis,redis,代码

Java之Spring Boot入门到精通IDEA版SpringBoot整合其他框架Junit,Redis,MyBatis(一篇文章精通系列)中