mybatisplus开启二级缓存
时间: 2024-01-20 09:16:59 浏览: 88
MyBatis一二级缓存
以下是两种开启MyBatis Plus二级缓存的方法:
1. 在启动类上添加@EnableCaching注解,并在需要缓存的Service层方法上添加@Cacheable注解。
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching // 允许二级缓存
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
```java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Cacheable(value = "SeatPerson", key = "#areaNo")
public User getUserByAreaNo(String areaNo) {
// 从数据库中查询用户信息的逻辑
// ...
}
}
```
2. 在MyBatis Plus的配置文件中开启二级缓存。
```xml
<!-- mybatis-config.xml -->
<configuration>
<settings>
<setting name="cacheEnabled" value="true" /> <!-- 开启二级缓存 -->
</settings>
</configuration>
```
```java
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Mapper;
@Mapper
@CacheNamespace // 开启二级缓存
public interface UserMapper {
// ...
}
```
阅读全文