我们使用实体
public class User implements Cloneable,Serializable{
@Id
@GeneratedValue
protected long id;
@NotNull
protected String userName;
@NotNull
protected String email;
@NotNull
protected String firstName;
@NotNull
protected String lastName;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = "UserID", referencedColumnName = "ID")
protected List<UserCompanyRoles> userRoles;
}
public class UserCompanyRoles implements Serializable {
private static final long serialVersionUID = 1L;
private final static Logger logger = Logger.getLogger(UserCompanyRoles.class);
@Id
@GeneratedValue
private long id;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "UserID")
private User user;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "RoleID")
private Role role;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "CompanyID")
private Company company;
}
此实体用户使用dao
进行更新protected boolean update(Object entity,Long id) {
EntityManager entityManager = null;
EntityTransaction tx = null;
try {
entityManager = this.createEM();
tx = entityManager.getTransaction();
tx.begin();
Object objToUpdate = retrieve(entity.getClass(), id);
BeanUtils.copyProperties(objToUpdate, entity);
entityManager.merge(objToUpdate);
entityManager.flush();
tx.commit();
return true;
} catch (Exception e1) {
if (tx != null) {
tx.rollback();
}
return false;
} finally {
if(tx!=null){
tx.rollback();
}
if (entityManager != null && entityManager.isOpen()) {
this.closeEM(entityManager);
}
}
}
此代码可以使用一段时间但是。有些时候新添加的usercompanyrole没有插入到表中。 他们不能在更新时抛出错误。 只有一段时间,其他方面才会有效。 我们不知道要解决这个问题。 重启我的服务器后,这将很好用。