MyBatis 的一级缓存和二级缓存有什么区别?如何使用?
MyBatis 中有两级缓存,一级缓存和二级缓存,它们的区别和使用方式如下:
1. 一级缓存:
a. 作用范围为 SqlSession,在 SqlSession 内部多次查询使用相同的 SQL 语句和参数时,查询结果会被缓存到该 SqlSession 的一级缓存中,下次查询时直接从缓存中获取。
b. 一级缓存为默认开启的,不能关闭,也不能配置。缓存的数据会在 SqlSession 被提交或清理缓存时进行清除。
c. 如果业务逻辑需要多次查询相同的数据,可以利用一级缓存提高查询效率。但是需要注意,在使用一级缓存时需要考虑缓存清除的时机和是否会产生脏数据的问题。
2. 二级缓存:
a. 作用范围为 Mapper 映射文件级别,在多个 SqlSession 之间共享查询结果,可以有效减轻数据库压力。
b. 二级缓存的实现需要在映射文件中手动配置,需要将 Cache 属性设置为对应的缓存实现类名称或者别名。缓存实现类需要实现 Cache 接口。
c. 如果需要使用二级缓存,需要在 SqlSessionFactory 的配置中进行配置,开启二级缓存,并且在映射文件中配置需要使用缓存的语句和缓存实现类。
d. 二级缓存默认关闭,可以通过以下代码或配置文件开启:
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
e. MyBatis 内置了三种符合使用场景的缓存实现:PerpetualCache、FifoCache 和 LruCache,开发者也可以使用自定义的缓存实现类。
下面是一个简单的例子,演示了如何使用二级缓存:```
<cache eviction="LRU" flushInterval="1000" size="1024"/>
<cache-ref namespace="xxx"/><!-- 上面的 namespace="xxx" 中的 xxx 是要被共享的 Mapper.xml 文件的名称 -->
这个例子中,我们将 cache 标签作为二级缓存进行了配置,eviction 指定缓存回收策略, flushInterval 表示缓存刷新间隔, size 表示缓存容量。cache-ref 标签用来引用其他映射文件的缓存。
总之,MyBatis 的缓存可以大大提高查询效率,提高应用程序的性能和吞吐量。但是缓存的维护和清理策略需要开发者自行处理,需要根据具体应用场景进行配置和使用。
MyBatis 中,如何与 Spring 集成?如何与 Spring Boot 集成?
MyBatis 与 Spring 及 Spring Boot 的集成方式如下:
1. MyBatis 与 Spring 集成:
a. 首先,在 Spring 的配置文件中,需要配置 SqlSessionFactory、SqlSessionTemplate 和 MapperScannerConfigurer。
<!-- 配置 SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath*:mapper/*.xml"/>
</bean>
<!-- 配置 SqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- MyBatis Mapper 接口扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
b. 配置完毕后,可以在 Spring 项目中使用自动注入的方式获取对应的 Mapper 接口,例如:```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
// ...
}
2. MyBatis 与 Spring Boot 集成:
a. 在 Spring Boot 项目中,只需要在 pom.xml 文件中导入如下依赖即可。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter.version}</version>
</dependency>
其中 ${mybatis-spring-boot-starter.version} 应替换为对应的版本号。
b. 配置文件中同样需要配置 SqlSessionFactory 和 Mapper 接口扫描的路径,例如:
mybatis:
type-aliases-package: com.example.domain
mapper-locations: classpath*:mappers/*.xml
c. 在 Spring Boot 中使用 Mapper 接口也与普通的 Spring 项目类似,例如:```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
// ...
}
总之,在 Spring 和 Spring Boot 中,MyBatis 与框架的集成都十分简单,开发者只需要配置好相关组件,并在需要使用的地方注入相应的 Mapper 接口即可。