2009-04-10 211 views
1

我有兩個實體類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; 
    } 
} 

回答

2

這就是我們如何加入兩個實體,在我們的項目中JPA:

@Entity 
    @Table(name = "Period") 
    public class Period implements Serializable { 
     private List<Delay> delays = new ArrayList<Delay>(); 

     @OneToMany(mappedBy="period") //name of the field in joined entity 
     public List<Delay> getDelays() { 
     return delays; 
     } 
    } 

    @Entity 
    @Table(name = "Delay") 
    public class Delay implements Serializable { 

    private Period period; 

    @ManyToOne 
    @JoinColumn(name = "PERIODID") 
    public Period getPeriod() { 
     return period; 
    } 
} 
0

Here is an article來自Oracle,它解釋瞭如何映射這些關係。

當你使用這個在Java中,這取決於您的JPA框架,你需要將MyCharacter添加到列表中User設置userMyCharacter或僅兩個中的一個(因爲框架將管理另一邊爲你)。我建議編寫一個小測試來確定哪些方法可行(並且,無論如何,您都應該使用對象編寫測試用例)。

從數據庫加載對象時,您不需要這樣做,因爲所有框架都能正確處理這種情況。

1

我不知道我正確理解你的問題,但你可以嘗試設置的mappedBy上MyCharacter.owner:

@ManyToOne(mappedBy="characters")