SpringBoot整合Mybatis和Redis
时间: 2024-01-24 18:01:56 浏览: 91
SpringBoot 整合 Redis、mybatis 完整项目源码下载
5星 · 资源好评率100%
好的,以下是SpringBoot整合Mybatis和Redis的步骤:
1. 在pom.xml中引入Mybatis和Redis的依赖:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 在application.properties中配置Mybatis和Redis相关的参数:
```properties
# Mybatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.model
# Redis配置
spring.redis.host=localhost
spring.redis.port=6379
```
3. 编写Mybatis的Mapper接口和对应的SQL语句:
```java
@Mapper
public interface UserMapper {
@Select("SELECT id, name, age FROM user WHERE id=#{id}")
User getUserById(@Param("id") Integer id);
}
```
4. 编写Redis的配置类和RedisTemplate实例:
```java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
```
5. 在Service中使用Mybatis和Redis:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public User getUserById(Integer id) {
String key = "user_" + id;
User user = (User) redisTemplate.opsForValue().get(key);
if (user == null) {
user = userMapper.getUserById(id);
redisTemplate.opsForValue().set(key, user);
}
return user;
}
}
```
以上就是SpringBoot整合Mybatis和Redis的步骤,希望能够帮助到你。
阅读全文