Java 如何使用 EntityManager (JPA) 在 DAO 中实现 update() 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1809159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement update () method in DAO using EntityManager (JPA)?
提问by Roman
What is the standard way to implement simple update?
实现简单更新的标准方法是什么?
Example: we have User with phone number NNNNNN and now we want to set it to YYYYYY.
示例:我们有电话号码为 NNNNNN 的用户,现在我们要将其设置为 YYYYYY。
@PersistenceContext
private EntityManager em;
public void update (User transientUser) {
what should be here?
}
User entity is as simple as possible:
用户实体尽可能简单:
@Entity
@Table (name = "USER")
public class User {
@Id
@GeneratedValue
private Integer id;
@Column (nullable = false, unique = true)
private String login;
private String phone;
public User () { }
... //some setters and getters
}
采纳答案by Pascal Thivent
According to the JPA specifications, EntityManager#merge()
will return a reference to anotherobject than the one passed in when the object was already loaded in the current context. So, I'd rather return the result of the merge()
and write the update()
method like this:
根据 JPA 规范,EntityManager#merge()
将返回对另一个对象的引用,而不是在对象已在当前上下文中加载时传入的对象。所以,我宁愿返回结果merge()
并update()
像这样编写方法:
@PersistenceContext
private EntityManager em;
public User update (User transientUser) {
return em.merge(transientUser);
}
Then, use it like this (skipping the initialization part):
然后,像这样使用它(跳过初始化部分):
user.setPhone("YYYYYY");
user = dao.update(user);
回答by Stefan Ernst
change the property and then use EntityManager merge()
更改属性,然后使用 EntityManager merge()
http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#merge%28T%29
http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#merge%28T%29