我在尝试获取元素集合时遇到了一个问题:朋友的集合是空的。
有3个类:
@Entity
@Table(name="USER")
public class User {
@Id
@Column(name="USER_ID", nullable=false)
private String mail;
@Column(name="PASSWORD")
private String password;
@Column(name="SURNAME")
private String surname;
@Column(name="NAME")
private String name = null;
@Column(name="STATUT")
private StatutUser statut;
@Column(name="PHONENUMBER")
private int phoneNumber;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy="friendPK.friend")
@Fetch(FetchMode.JOIN)
private Set<Friend> friends = new HashSet<Friend>();
...
Some getters and setters
第二个 :
@Entity
@Table(name = "FRIEND")
public class Friend
{
@EmbeddedId
public FriendPK friendPK;
@Column(name = "FRIEND_STATUT")
private StatutFriend statutFriend;
...
}
最后一个 :
@SuppressWarnings("serial")
@Embeddable
public class FriendPK implements Serializable{
@ManyToOne
@JoinColumn(name="USER1_ID", referencedColumnName="USER_ID")
protected User user1;
@ManyToOne
@JoinColumn(name="USER2_ID", referencedColumnName="USER_ID")
protected User friend;
}
当我尝试获取所有朋友的用户时,集合为空。
这是添加关系的方法所在的文件:
private EntityManagerFactory emf;
private EntityManager manager;
public String addFriends(String mail1, String mail2){
EntityTransaction t;
t = manager.getTransaction();
try{
t.begin();
User user = manager.find(User.class, mail1);
User friend = manager.find(User.class, mail2);
Friend f = new Friend();
f.setStatutFriend(StatutFriend.TOCHECK);
FriendPK friendPK = new FriendPK();
friendPK.setFriend(friend);
friendPK.setUser1(user);
f.setFriendPK(friendPK);
Set<Friend> relationship = new HashSet<Friend>();
relationship = user.getFriends();
relationship.add(f);
Set<Friend> relationship2 = new HashSet<Friend>();
relationship2 = friend.getFriends();
relationship2.add(f);
user.setFriends(relationship);
friend.setFriends(relationship2);
manager.persist(user);
t.commit();
error.setReq(StatutReq.DONE);
}
catch(Exception e){
error.setReq(StatutReq.ABORTED);
error.setError(e.getMessage());
}
finally
{
if (t.isActive())
{
t.rollback();
}
}
请放纵我的代码...我是初学者!非常感谢。