您的当前位置:首页正文

SpringBoot整合Mybatis 与 Redis

2024-11-08 来源:个人技术集锦

1.SpringBoot整合Mybatis

此博客为注解整合若是想使用mapper.xml文件请
1.1导入依赖

 <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- alibaba-druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>

1.2编写application.properties配置

#### springboot 整合mybatis的基础配置

#别名
mybatis.type-aliases-package=com.example.springboot_day04_01.domain
#驱动配置可省略,springboot可以自动识别
#spring.datasource.driver-class-name =com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/boot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =123456
#如果不配置阿里的druid,会自动使用默认的数据源 (com.zaxxer.hikari.HikariDataSource)
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
#控制台显示SQL
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

1.3为启动类添加注解

@MapperScan(basePackages = {"com.example.springboot_day04_01.mapper"})//扫描mybatis的Mapper接口类,路径指向dao层

1.4dao层事例

@Repository
public interface UserMapper {

    /**
     * 获取所有信息
     * @return
     */
    @Select("select * from user")
    @Results(@Result(property = "createTime",column = "create_time"))//字段名称不一样解决方法
    List<User> findAll();

    /**
     * 获取单个信息
     * @param id
     * @return
     */
    @Select("select * from user where id = #{id}")
    @Results(@Result(property = "createTime",column = "create_time"))
    User findById(int id);

    /**
     * 修改
     * @param user
     */
    @Update("update user set name = #{name}  where id = #{id} ")
    void update(User user);

    /**
     * 保存
     * @param user
     */
    @Update("insert  into user(name,phone,create_time,age) values(#{name},#{phone},#{createTime},#{age})")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")//返回所添加记录的id
    int save(User user);
    /**
     * 删除
     * @param id
     */
    @Delete("delete from user where id = #{id}")
    void delete(int id);

}

2.SpringBoot整合Redis

2.1导入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

2.2配置application.properties

#=========redis基础配置=========
spring.redis.database=3
spring.redis.host=127.0.0.1
spring.redis.port=6379
#连接池中的最小空闲连接,默认值是0。
spring.redis.jedis.pool.min-idle=10
# 连接池中的最大空闲连接,默认值是8。
spring.redis.jedis.pool.max-idle=50
#=========redis线程池设置=========
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时
spring.redis.jedis.pool.max-wait=1000

2.3编写或者自己找个redis工具类
2.3.1 json转换工具类

package com.example.springboot_day04_01.utils;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonUtils {
    private static ObjectMapper objectMapper = new ObjectMapper();
    //对象转字符串
    public static <T> String obj2String(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //字符串转对象
    public static <T> T string2Obj(String str,Class<T> clazz){
        if (StringUtils.isEmpty(str) || clazz == null){
            return null;
        }
        try {
            return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

2.3.2redis工具类



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 功能描述:redis工具类
 */
@Component
public class RedisClient {


    @Autowired
    private StringRedisTemplate redisTpl; //jdbcTemplate

    /**
     * 功能描述:设置key-value到redis中
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try {
            redisTpl.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 功能描述:通过key获取缓存里面的值
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return redisTpl.opsForValue().get(key);
    }

    @Autowired
    private StringRedisTemplate redisTemplate;


   /* *//**
     * 通过字符串key获取值
     *
     * @param key 键
     * @return 值
     *//*
    public String get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }


    *//**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     *//*
    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }*/


    /**
     * 功能描述:设置某个key过期时间
     *
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 功能描述:根据key 获取过期时间
     *
     * @param key
     * @return
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 递增
     *
     * @param key 键
     * @return
     */
    public long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几
     * @return
     */
    public long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, -delta);
    }

}

2.4测试使用

package com.example.springboot_day04_01.controller;

import com.example.springboot_day04_01.utils.JsonData;
import com.example.springboot_day04_01.utils.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {

    @Autowired
    private RedisClient redisClient;

    @GetMapping("/set")
public Object set(String k ,String v){
    redisClient.set(k,v);
    return JsonData.buildSuccess();
}
    @GetMapping("/get")
    public Object get(String k ){
        String s = redisClient.get(k);
        return JsonData.buildSuccess(s);
    }
}

Top