gpt4 book ai didi

java - JPA中的双向关系

转载 作者:行者123 更新时间:2023-11-30 01:40:15 24 4
gpt4 key购买 nike

我有两个实体类,User 和 MyCharacter。用户有一个 MyCharacters 列表,每个 MyCharacter 都有一个对用户(所有者)的引用。我想要完成的是,我对这两个关系使用相同的联接表,这意味着,在 MyCharacter 中找到的所有者关系将自动使用与 User=>MyCharacter 中相同的联接表。这意味着 MyCharacter 中的 getOwner() 方法应该可以工作,而无需我在某些时候显式调用 setOwner(user)。

为了更清楚地说明这一点,这是我当前失败的单元测试(最后一个断言失败)


@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;
}
}

最佳答案

这就是我们在项目中使用 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;
}
}

关于java - JPA中的双向关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/737173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com