Springboot整合mybatis_plus + redis(使用注解的方式)
在Spring Boot整合MyBatis Plus和Redis时,可以使用注解的方式来简化配置。以下是一个基本的示例:
- 添加依赖到
pom.xml
:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring Boot Starter for Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- MyBatis Plus Starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
:
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=数据库用户名
spring.datasource.password=数据库密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.redis.host=localhost
spring.redis.port=6379
- 创建实体类和Mapper接口:
// 实体类 User.java
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
// Mapper 接口 UserMapper.java
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 这里可以添加自定义的数据库操作方法
}
- 配置Redis缓存:
@Configuration
public class MybatisPlusCacheConfig {
@Bean
public Cache<String, Object> redisCache(RedisTemplate<String, Object> redisTemplate) {
return new MybatisRedisCache(redisTemplate);
}
}
- 使用MyBatis Plus和Redis缓存:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private Cache<String, Object> cache;
@Cacheable(cacheNames = "user", key = "#id")
public User getUserById(Serializable id) {
return userMapper.selectById(id);
}
@CachePut(cacheNames = "user", key = "#user.id")
public User updateUser(User user) {
userMapper.updateById(user);
return user;
}
@CacheEvict(cacheNames = "user", key = "#id")
public void deleteUserById(Serializable id) {
userMapper.deleteById(i
评论已关闭