我有 2 个实体,它们之间有关系。
两个实体都已创建并插入到数据库中。 在某些时候,用户能够在它们之间进行连接。 当我尝试这样做时,我得到:
javax.persistence.PersistenceException: Detected attempt to establish WannaMeetUser("654321") as the parent of WannaMeetUser("123456") but the entity identified by WannaMeetUser("123456") has already been persisted without a parent. A parent cannot be established or changed once an object has been persisted.
这是一个传递关系(用户可以有很多来自用户之王的 friend ):
附上代码:
@Entity
public class WannaMeetUser {
@Id //signifies the primary key
@Column(name = "ID", nullable = false)
private Key id;
@ManyToMany
@Basic
private List<WannaMeetUser> userFriends = new ArrayList<WannaMeetUser>();
}
public void addFriendToWannaMeetUser(@Named("userId") String userId,
@Named("friendId") String friendId) {
EntityManager mgr = getEntityManager();
try
{
WannaMeetUser user = mgr.find(WannaMeetUser.class, WannaMeetServerUtils.getKeyFromString("WannaMeetUser", userId));
WannaMeetUser friend = mgr.find(WannaMeetUser.class, WannaMeetServerUtils.getKeyFromString("WannaMeetUser", friendId));
String coupleId = getcoupleId(userId.toString(), friendId.toString());
if (friend == null || user == null) {
throw new EntityNotFoundException("Object does not exist");
}
WannaMeetCouple couple=mgr.find(WannaMeetCouple.class, coupleId);
if (couple == null) {
couple = createCouple(userId.toString(), friendId.toString());
couple.setId(coupleId);
setUserJoined(couple, userId.toString(), friendId.toString(), true);
}
else {
if (isFriendAllready(couple, userId.toString(), friendId.toString()))
;
setUserJoined(couple, userId.toString(), friendId.toString(), false);
doAddFriend(user, friend, 10, 12321321);
mgr.persist(couple);
mgr.persist(friend);
mgr.persist(user);
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
mgr.close();
}
}
我的问题是建立这种关系的最佳方式是什么?
谢谢
最佳答案
消息显示用户 1 已经在没有任何父级的情况下被持久化,但现在我们尝试 将用户 2 保留为用户 1 的父级,但已知用户 1 没有父级。
尝试使用级联一次性保存所有内容。您可以像这样声明级联关系:
@ManyToMany(cascade=CascadeType.ALL)
private List<User> userFriends;
然后使用级联一次性保存所有内容:
User user1 = new User();
User user2 = new User();
user1.getUserFriends().add(user2);
// this persists the whole tree in one go
entityManager.persist(user1);
关于java - 为父实体 JPA-GAE 分配现有子实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170177/