gpt4 book ai didi

java - 在表之间链接@ManyToOne 时如何创建对象

转载 作者:搜寻专家 更新时间:2023-10-30 23:26:40 25 4
gpt4 key购买 nike

我有 2 个类 - Person 和 Team。一个人只能在一个团队中,但一个团队可以有很多人(人对象)。问题在于 Person 和 Team 都需要其他类对象来创建它们自己。

类:

@Entity
@Table(name = "Team")
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private int id;

@Column(name = "teamName", nullable = false)
private String teamName;

@OneToMany(mappedBy = "myTeam", fetch = FetchType.LAZY)
private Set <Person> setOfMembers = new HashSet<Person>();

public Team(int id, String teamName, Set <Person> setOfMembers) {
//usual code (don't want to waste so much space)
}
... other irrelevant fields ...
}

@Entity
@Table(name = "Person")
public class Person{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false)
private int id;

@Column(name = "teamID", nullable = false)
private int teamID;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "teamID", referencedColumnName = "id")
private Team myTeam;

public Person(int id, int teamID, Team myTeam) {
//usual code
}
... other irrelevant fields ...
}

现在在主文件中,我正在尝试创建一个新对象:

Team t1 = new Team(1,"Nights Watch", <and here i need Person Object, so i 
do something as follows:> new Person(1,1, <and here i need Team object>));

所以它会反复出现,没有尽头。我想向数据库中添加一些记录,但我不知道如何。

实际上我需要一组人物对象,但我仍然不知道如何

最佳答案

为什么在 Team 类的初始化过程中需要所有队友?

只做一个没有 Person 参数的构造函数,然后做一个像这样的方法:

public void addTeamMember(Person person) {
setOfMembers.add(person);
}

然后,您可以创建Team,创建Person,最后将Person 添加到Team。

关于java - 在表之间链接@ManyToOne 时如何创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56350040/

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