在hibernate / jpa最佳实践问题中将分离的或新的实体与现有实体合并 [英] merging a detached or new entity with an existing entity in hibernate/jpa best practice question

查看:191
本文介绍了在hibernate / jpa最佳实践问题中将分离的或新的实体与现有实体合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当业务层创建一个新的实体,逻辑上表示应该更新的现有实体的一个实例(例如,它们具有相同的业务密钥),这种合并不良实践的方法是

When the business layer creates a new entity, which logically represents an instance of an existing entity that should be updated (say they share the same business key), is this method of merging bad practice?

public User add(User user){

    User existingUser = getUserDao().findByBusinessKey(user.getBusinessKey(), false);
    user.setId(existingUser.getId());

    user = getUserDao().merge(user);

    return user;
}

我问,因为在分离的实体上显式设置ID对我来说感觉很奇怪,但是即使用户实体的equals和hashcode方法得到适当的实现,在这里设置ID是确保合并发生的唯一方法。

I ask because setting the ID explicitly on the detached entity feels pretty strange to me, but even though the equals and hashcode method of the User entity are appropriately implemented, setting the ID here is the only way to ensure the merge takes place.

是否有更好的做法?

这种方法有什么特别的缺点吗?

Are there specific drawbacks to this method that would bite me later on?

感谢您的采访看看!

推荐答案

该代码将工作,但是在分离的实体上显式设置ID没有必要。一个典型的Hibernate应用程序有一个保存方法来处理两种情况:

That code will work, but setting the ID explicitly on the detached entity should not be necessary. A typical Hibernate app have a 'save' method that handles two cases:


  1. 用户想创建一个新的用户,所以应用程序创建一个以null作为ID的用户对象。

  2. 用户查询用户列表,并正在选择一个进行编辑。在这种情况下,应用程序执行查询并将对象传播到保存方法。该对象将具有一个ID,代码将为其应用新的值。

看起来像代码中的东西没有做第二种情况是典型的。如果用户对象来自一些先前的Hibernate查询(由用户点击编辑用户或类似的东西触发),那么它将已经有一个ID。因此,只需要 merge(user) call。

Looks like something in your code isn't doing the second case in the typical way. If the 'user' object comes from some prior Hibernate query (triggered by the user clicking 'edit user' or something like that), then it will already have an ID. Thus, only the merge(user) call is needed.

我通常会这样做:

if (user.getId() == null)
  em.persist(user);
else
  user = em.merge(user);

然后我添加代码来处理乐观锁定问题(另一个会话更新对象)和唯一约束问题另一个会话尝试使用相同的业务密钥来保留某些东西。)

Then I add code to handle optimistic locking issues (another session updated the object) and unique constraint issues (another session tried to persist something with the same business key).

如Seam等框架可以使这更简单,因为它们在控制器Bean方法之间传播Hibernate会话。所以即使没有合并。

Frameworks such as Seam can make this even simpler because they propagate the Hibernate session between the controller bean methods. So even the 'merge' is not needed.

这篇关于在hibernate / jpa最佳实践问题中将分离的或新的实体与现有实体合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆