我有兩個實體類User和MyCharacter。用戶有一個MyCharacters列表,每個MyCharacter都有一個引用返回給用戶(所有者)。我想要完成的是,我爲這兩個關係使用了同一個連接表,這意味着在MyCharacter中找到的所有者關係會自動使用與User = > MyCharacter相同的連接表。這意味着MyCharacter中的getOwner()方法應該可以工作,而不必在某處調用setOwner(user)。JPA中的雙向關係
要清除目前無法多做一些事情,這是我的單元測試(最後斷言失敗)
@Test
public void testTwoWayRelation() {
User user = new User();
MyCharacter character = new MyCharacter();
List<MyCharacter> chars = new ArrayList<MyCharacter>();
chars.add(character);
user.setCharacters(chars);
facade.store(user);
assertNotNull(character.getId());
character = facade.find(MyCharacter.class, character.getId());
assertNotNull(character.getOwner());
}
我的實體類如下表所示。
@Entity
@Table(name = "myuser")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@OneToMany(cascade = { CascadeType.PERSIST })
protected List<MyCharacter> characters;
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<MyCharacter> getCharacters() {
return characters;
}
public void setCharacters(List<MyCharacter> characters) {
this.characters = characters;
}
}
@Entity
public class MyCharacter{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@ManyToOne
@JoinTable(name = "myuser_mycharacter", joinColumns = @JoinColumn(name = "characters_id"), inverseJoinColumns = { @JoinColumn(name = "user_id") })
protected User owner;
public MyCharacter() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
}