有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate与JDO makeTransient的等价物是什么

我正在将我的Dao层从KodoJDO移植到Hibernate。 我将菜单保存在数据库中,并根据用户的权限删减本地副本,只显示用户可以做的事情

当我在KodoJDO做这件事时,我不得不让我正在修剪的对象暂时化,因为我不想把更改写回数据库

我在Hibernate中没有看到任何等效的函数。有吗?如何防止这些更改被写回数据库

这里是剪枝函数

 public void prune(Collection<Entitlement> ents)
 {
  Session session=PersistenceManager.getManager();
  // Rewrite----------------------------------
  //session.makeTransient(this);

  for (Iterator<Leaf> iter = leafs.iterator(); iter.hasNext();)
  {
   Leaf l = (Leaf) iter.next();
   if(!l.isAllowed(ents))
   {
    iter.remove();
   }
  }
  for (Iterator<Branch> iter = branches.iterator(); iter.hasNext();)
  {
   Branch b = (Branch) iter.next();
   if(b!= this)
   {
    b.prune(ents);
   }
   if (b.hasNoChildren())
   {
    iter.remove();
   }
  }
 }

评论答案。我接受了最完整的答案,但斯卡夫曼和阿菲的答案也很有价值


共 (3) 个答案

  1. # 1 楼答案

    Session.evict(entity)可能has the semantics您正在寻找:

    Remove this instance from the session cache. Changes to the instance will not be synchronized with the database.

  2. # 2 楼答案

    evict(Object object)是您正在寻找的Session接口上的方法

    还要注意的是,hibernate中的词汇表有些不同。根据会话javadoc:

    transient: never persistent, not associated with any Session
    persistent: associated with a unique Session
    detached: previously persistent, not associated with any Session
    

    所以短暂并不意味着完全相同的事情“超脱”是他们用来形容你所说的东西的词

  3. # 3 楼答案

    在JPA2.0中是entityManager.detach(..)。我明确给出了JPA版本,因为建议通过JPA使用hibernate

    如果我们看看detach(..)方法是如何在hibernate的EntityManagerImpl中实现的,它在底层会话上使用getSession().evict(entity)

    但请注意,你应该很少需要这样做。我不知道这在JDO中是否是一种常见的做法,但在JPA/Hibernate中,如果正确使用它们,就不需要它

    根据您的评论——如果您想将hibernate实体用作其值发生更改但不会持久化的对象。我没有这样使用它们,因为我通常没有一个开放的会话/实体管理器。或者我使用价值对象。如果在视图中都有一个打开的会话,但没有值对象——是的,这是一个有效的用法