项目场景:
springboot项目, 使用org.mybatis.spring.SqlSessionTemplate 的selectOne
问题描述
使用SqlSessionTemplate的selectOne进行查询
查询两次后实体类TorEntity 中两个UsersEntity 对象内存地址相同
TorEntity torEntity = new TorEntity();
UsersConditionEntity usersConditionEntity= new UsersConditionEntity();
//第一次调用searchUserEntity
scrEntity.setUsersEntity(this.torDao.searchUserEntity(
torEntity.getUsersConditionEntity()));
//第二次调用searchUserEntity
scrEntity.setBeforeUsersEntity(this.torDao.searchUserEntity(condition));
//Dao接口实现
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
public UsersEntity searchUserEntity(UsersConditionEntity conEntity) {
return (UsersEntity) sqlSessionTemplate.selectOne("searchUser",conEntity);
}
//实体类
public class TorEntity {
private UsersEntity beforeUsersEntity = new Ms900100Entity();
private UsersEntity usersEntity = new Ms900100Entity();
}
原因分析:
1.疑点对象单例造成, 使用
@Scope("prototype"),问题未得到解决
2.疑点使用selectOne返回对象是引用内存中已经存在对象地址, 验证后发现返回新对象
3.Mybatis缓存机制, 默认开启一级缓存
当前工程设置开启二级缓存<setting name="cacheEnabled" value="true" />
导致第一次查询和第二次查询为同一个对象
解决方案:
设置flushCache=true时, 默认清除二级缓存
设置flushCache=false时, 默认不清除二级缓存
<select id="searchUser" parameterType="com.cll.entity.UsersConditionEntity"
resultMap="TorresultMap" flushCache="true">
select * from users;
</select>
参考文章:
https://blog.youkuaiyun.com/umgsai/article/details/50634074
在SpringBoot项目中,使用MyBatis的SqlSessionTemplate的selectOne方法进行查询时,发现两次查询后实体类中的两个对象地址相同。问题源于MyBatis的缓存机制,即使设置了对象为非单例,由于一级缓存的存在,导致两次查询返回同一对象。解决方案是在对应的SQL查询中设置flushCache=true,以清除二级缓存,确保每次查询返回新的对象。
1726

被折叠的 条评论
为什么被折叠?



