我在 WebSphere 7 上使用 JPA 和 EJB。
我有以下类(class):
@Entity
@Table(name="WIDGET")
public class Widget implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String details;
/* getters and setters */
}
我有一个这样的 DAO:
@Stateless
public class WidgetDAO implements WidgetDAOLocal {
@PersistenceUnit
private EntityManagerFactory emf;
private EntityManager em;
public EntityManager getEntityManager() {
if (emf == null) {
throw new Exception();
}
return emf.createEntityManager;
}
public Widget getWidget(Long id) {
Widget widget = null;
EntityManager em = getEntityManager();
try {
widget = (Widget)em.find(Widget.class, widgetId);
} finally {
em.close();
}
return widget;
}
public Widget createWidget(Widget widget) {
EntityManager em = getEntityManager();
try {
em.persist(widget);
em.flush();
} finally {
em.close();
}
return widget;
}
public Widget updateWidget(Widget widget) {
EntityManager em = getEntityManager();
try {
widget = getEntityManager().merge(widget);
em.flush();
} finally {
em.close();
}
return widget;
}
}
创建工作正常,我的小部件出现在数据库中。
但是当我尝试进行合并时,出现错误。执行合并的代码和我得到的错误如下:
public WidgetService {
@EJB
private WidgetDAO widgetDAO;
public WidgetDAO getWidgetDAO() {
return this.widgetDAO;
}
public Widget getWidget(Long id) {
return this.getWidgetDAO().getWidget(id);
}
public void updateDetails(Long widgetId, String details) {
Widget w = this.getWidget(widgetId);
w.setDetails(details);
this.widgetDAO.updateWidget(w);
}
}
错误是:
Exception caught from before_completion synchronization operation:
<openjpa-1.2.1-SNAPSHOT-r422266:686069 nonfatal user error> org.apache.openjpa.persistence.InvalidStateException:
The generated value processing detected an existing value assigned to this field: com.mydomain.domain.Widget.id.
This existing value was either provided via an initializer or by calling the setter method.
You either need to remove the @GeneratedValue annotation or modify the code to the initializer processing.
非常感谢对此的任何帮助!
最佳答案
Merge 获取您的实体的副本,将其分离并保留新实体,我认为这是尝试从旧实体设置 ID 并导致您生成的值发生冲突。如果您只想更新您的对象,您应该在事务中进行并提交。
关于java - 我的 JPA DAO 有什么问题?它会持续存在,但合并时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10760495/