SpringBoot数据层开发:MyBatisPlus+JPA+Redis缓存最佳组合

🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
在这里插入图片描述

SpringBoot数据层开发:MyBatisPlus+JPA+Redis缓存最佳组合

一、引言

在当今的软件开发领域,数据层的高效开发是构建高性能应用的关键。Spring Boot作为一款广泛使用的Java开发框架,为开发者提供了便捷的开发环境。而MyBatisPlus、JPA和Redis缓存的组合,能够充分发挥各自的优势,提升数据层的开发效率和应用性能。本文将详细介绍如何在Spring Boot项目中使用这三者的最佳组合进行数据层开发。

二、技术概述

2.1 MyBatisPlus

MyBatisPlus是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。它提供了丰富的代码生成器、通用CRUD方法等功能,大大减少了开发者编写SQL语句的工作量。

2.2 JPA

JPA(Java Persistence API)是Java EE 5.0平台标准的对象关系映射规范,它为Java开发人员提供了一种统一的方式来管理Java对象与数据库之间的映射。Spring Data JPA则是Spring提供的对JPA规范的实现,进一步简化了数据库操作。

2.3 Redis缓存

Redis是一个开源的、高性能的键值对存储数据库,常用于缓存场景。使用Redis作为缓存可以减少数据库的访问压力,提高应用的响应速度。

三、项目搭建

3.1 创建Spring Boot项目

可以使用Spring Initializr(https://start.spring.io/)来快速创建一个Spring Boot项目,添加以下依赖:

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- MyBatisPlus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3.4</version>
    </dependency>
    <!-- Spring Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- MySQL Driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

3.2 配置数据库和Redis

application.properties中配置数据库和Redis连接信息:

# Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# Redis configuration
spring.redis.host=localhost
spring.redis.port=6379

四、使用MyBatisPlus进行数据操作

4.1 创建实体类

创建一个简单的实体类User

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

@Data
@TableName("user")
public class User {
    @TableId
    private Long id;
    private String name;
    private Integer age;
}

4.2 创建Mapper接口

创建UserMapper接口继承BaseMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

4.3 使用MyBatisPlus进行CRUD操作

在Service层使用UserMapper进行CRUD操作:

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }

    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    public int addUser(User user) {
        return userMapper.insert(user);
    }

    public int updateUser(User user) {
        return userMapper.updateById(user);
    }

    public int deleteUser(Long id) {
        return userMapper.deleteById(id);
    }
}

五、使用JPA进行数据操作

5.1 创建实体类

同样使用上面创建的User实体类。

5.2 创建Repository接口

创建UserRepository接口继承JpaRepository

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

5.3 使用JPA进行CRUD操作

在Service层使用UserRepository进行CRUD操作:

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserJpaService {
    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    public User addUser(User user) {
        return userRepository.save(user);
    }

    public User updateUser(User user) {
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

六、使用Redis缓存

6.1 配置Redis缓存

创建一个Redis配置类RedisConfig

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.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
               .entryTtl(Duration.ofMinutes(10))
               .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
               .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
               .disableCachingNullValues();

        return RedisCacheManager.builder(redisConnectionFactory)
               .cacheDefaults(cacheConfiguration)
               .build();
    }
}

6.2 在Service层使用缓存

UserService中使用@Cacheable@CachePut@CacheEvict注解来管理缓存:

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
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;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Cacheable(value = "users", key = "'allUsers'")
    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }

    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @CachePut(value = "users", key = "#user.id")
    public User addUser(User user) {
        userMapper.insert(user);
        return user;
    }

    @CachePut(value = "users", key = "#user.id")
    public User updateUser(User user) {
        userMapper.updateById(user);
        return user;
    }

    @CacheEvict(value = "users", key = "#id")
    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }
}

七、总结

通过MyBatisPlus、JPA和Redis缓存的组合,我们可以在Spring Boot项目中实现高效的数据层开发。MyBatisPlus提供了便捷的SQL操作,JPA简化了对象关系映射,Redis缓存则提高了应用的性能。在实际开发中,可以根据具体的业务需求选择合适的技术进行数据操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fanxbl957

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值