似乎当我使用 jpa 合并更新现有实体时,它确实插入了具有相同 ID 的实体,而不是更新预期的现有实体。因为插入后,数据库行顺序丢失。但是我仍然有相同 id 的相同实体,Jpa 是否使用插入来更新?我的意思是它是否删除现有实体并使用更新的值再次插入以完成其更新工作。主要混乱是数据库顺序丢失。
这是我的侦听器方法: userService 是我使用 JPA 中的 EJB 类。
public void onEditUserOrganization(RowEditEvent event){
UserOrganization uorg =(UserOrganization) event.getObject();
try {
userService.updateUserOrganization(uorg);
} catch (UserException ex) {
ex.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("error)"));
}finally{
parentlist = getUserOrganizationParents();
branchlist = getUserOrganizationBranches();
}
}
这是我的主要更新方法
@Override
public void updateUserOrganization(UserOrganization org) throws UserException{
if(org != null && !em.contains(org)){
try{
UserOrganization existing = em.find(UserOrganization.class, org.getUorgId());
existing.setOrgcode(org.getOrgcode());
existing.setOrgname(org.getOrgname());
existing.setParent(org.getParent());
}catch(Exception e){
throw new UserException("Couldn't update user org with id " + org.getUorgId());
}
}
}
这是我的实体类:
public class UserOrganization implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@NotNull
@Column(name = "uorg_id", nullable = false)
private Integer uorgId;
@Basic(optional = false)
@NotNull
@Column(name = "parent", nullable = false)
private short parent;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 10)
@Column(name = "orgcode", nullable = false, length = 10)
private String orgcode;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 150)
@Column(name = "orgname", nullable = false, length = 150)
private String orgname;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "uorgId")
private List<refMain> refList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "uorgId")
private List<User1> user1List;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "userOrganization")
private List<Bankrelation> relationList;
public UserOrganization() {
}
//getter setters..
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof UserOrganization)) {
return false;
}
UserOrganization other = (UserOrganization) object;
if ((this.uorgId == null && other.uorgId != null) || (this.uorgId != null && !this.uorgId.equals(other.uorgId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "mn.bs.crasmon.model.UserOrganization[ uorgId=" + uorgId + " ]";
}
在 JPA 中进行更新的最佳方法是什么