如何删除Spring Hibernate EntityManager中的Cache

jixixiaofeng2002 2016-05-24 02:50:13
1、不知道为什么得到对象后,再执行Procedure,再重新提取这个对象时,就怎么都得不到Procedure中更新的数据
@Autowired PersonRepository personRepository;
@Autowired PersonDao personDao;
@Autowired EntityManager entityManager;

Person result = personRepository.save(person);

personDao.updateName(result.getId()); //调用了数据库的Procedure,更新了Person的数据,但之后我怎么都得不到这个更新的数据,还是旧的数据

//这里用了所有我所知道的删除Cache的方法,一个一个试,没有一个好使的,不知道为什么
entityManager.clear();
EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
entityManagerFactory.getCache().evictAll();
SessionFactory sessionFactory = ((HibernateEntityManagerFactory)entityManagerFactory).getSessionFactory();
Cache cache = sessionFactory.getCache();
cache.evictEntityRegions();
cache.evictCollectionRegions();
cache.evictDefaultQueryRegion();
cache.evictDefaultQueryRegion();

Session session = entityManager.unwrap(Session.class);
session.clear();

sessionFactory = session.getSessionFactory();
cache = sessionFactory.getCache();
cache.evictCollectionRegions();
cache.evictEntityRegions();

result = topoRepository.findOne(result.getId()); //这里得到的还是调用Procedure之前数据


2、不知道为什么,在@Test里就好使,能得到调用Procedure更新后的数据,用的是同样的方法
@Autowired PersonRepository personRepository;
@Autowired PersonDao personDao;

@Test
public void testUpdateRefId(){
Person result = personRepository.save(person);
personDao.updateName(result.getId());
result = topoRepository.findOne(result.getId());
}


3、其它信息:
主程序用的是Spring Boot
@SpringBootApplication
public class Application {

请大家指教。
...全文
257 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Nnick_s 2016-05-25
  • 打赏
  • 举报
回复
是的,你用Hibernate或是JPA都是这样,跟缓存有关系吗,应该是entityManager不知道你变更了数据库数据。PersonRepository 没有去查询数据库,你Test的时候环境是不是和正式的时候不一样?正式环境是不是用到了Web容器或是服务器?
Nnick_s 2016-05-25
  • 打赏
  • 举报
回复
可以用这个试一下,在你调用procedure之后
引用
entityManager.refresh(result);
jixixiaofeng2002 2016-05-24
  • 打赏
  • 举报
回复
大家都没遇到过这样的问题啊 我看这样的问题应该经常出现.只要外部应用更改了数据库, 程序就不会知道,所以也不会更新,不会从数据库重新提取一次数据.这样数据就不正确。

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧