简体   繁体   English

如果我从我的代码中排除 session.evict() 会发生什么?

[英]What will happen if I exclude session.evict() from my code?

I am new to hibernate.我是 hibernate 的新手。 I would like to know if we have any alternatives for session.evict().我想知道我们是否有 session.evict() 的替代方案。 I have commented that line and my logic works fine.我已经评论了那条线,我的逻辑工作正常。

session.evict() method is used to remove a particular object from cache associated with the session. session.evict() 方法用于从与 session 关联的缓存中删除特定的 object。 So removing it will force the hibernate to fetch the object from database instead of looking into cache.所以删除它会强制 hibernate 从数据库中获取 object 而不是查看缓存。 Example例子

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
try
{
SomeEntity myEntity= (SomeEntity) session.load(SomeEntity.class, new Integer(1)); //look in cache (will not be found) if not found then fetch from database
System.out.println(myEntity.getName());

myEntity = (SomeEntity) session.load(SomeEntity.class, new Integer(1)); //look in cache(will be found) if not then fetch from database
System.out.println(myEntity.getName());

session.evict(myEntity); // will remove from cache

myEntity = (SomeEntity) session.load(SomeEntity.class, new Integer(1)); // object will again be fetched from database if not found in second level cache
System.out.println(myEntity.getName());
}
finally
{
session.getTransaction().commit();
HibernateUtil.shutdown();
}

Edit: Session.evict() will remove the entity from first level cache and after removing the object from the session, any change to object will not be persisted. Edit: Session.evict() will remove the entity from first level cache and after removing the object from the session, any change to object will not be persisted. The associated objects will also be detached if the association is mapped with cascade="evict".如果关联是用 cascade="evict" 映射的,则关联的对象也将被分离。

Hope it helps!!希望能帮助到你!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM