Java JPA更新不反映在db上
我们使用的实体是Java JPA更新不反映在db上,java,jpa,eclipselink,Java,Jpa,Eclipselink,我们使用的实体是 public class User implements Cloneable,Serializable{ @Id @GeneratedValue protected long id; @NotNull protected String userName; @NotNull protected String email; @NotNull protected String firstName;
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;
}
这段代码可以工作一段时间,但是。有一段时间,新添加的usercompanyrole没有插入到表中。
他们无法在更新时抛出错误。
这只会在其他方面起到好的作用。
我们不知道如何解决这个问题。
重新启动服务器后,这将很好地工作。没有任何代码很难说。但是,当您说每个用户都有一个实体管理器存储为静态变量时,这听起来很糟糕。如果您将一个字段声明为
static
,那么每个应用程序只能有一个字段,而不是每个用户。您的代码暗示您正在使用JTA,并且容器正在将EntityManager注入到您的线程中-我不知道为什么有人会将此变量设置为静态,但这似乎是问题的根源。它不应该是静态的,因为每个线程都需要自己的EntityManager实例。很可能是这个问题的根源,因为EntityManager不是线程安全的,您显示的堆栈跟踪是由于锁定造成的-一个线程正在等待,因为其他线程锁定了某些对象。@Chris我们正在使用另一个实体管理器工厂来处理另一个持久性单元或实体。当使用另一个实体管理器工厂创建新的实体管理器时,新更新的实体不会反映在数据库上。该问题仅适用于列表用户角色;在用户类中,您已将问题编辑为完全不同的内容,因为原始问题已荡然无存。如果你发布了错误的内容,然后又提出了一个新的问题,那就更好了——但是你还没有输入足够的信息来帮助解决当前的问题,因为给出的代码是通用的,所以我们不知道你是如何创建和合并任何内容的。
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);
}
}
}