我将 JPA 实现 EclipseLink 和 MySQL 服务器用于我的应用程序的持久层。我的问题是,一个已经持久化并且已经有一个 id 的对象,通过与 CascadeType.All 的多对一关系被第二次插入。
这里的实体:
@Entity
@Table(name = "messages")
public class Message extends DbObject {
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
public User author;
public String message = "";
public Timestamp timestamp;
// Getters and setters removed ....
}
@Entity
@Table(name = "users")
public class User extends DbObject {
private String name;
// Getters and setters removed ....
}
@MappedSuperclass
public abstract class DbObject {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
当我运行以下代码时,我的“用户”表中有两个条目。但我只想将已经存在的用户分配给消息对象,而不是创建新用户。
User user = getCurrentUser(); // The user object is already persistent
Message msg = new Message();
msg.setUser(user);
EntityManager em = createEntityManager();
em.getTransaction().begin();
em.persist(msg);
em.getTransaction().commit();
em.close();