gpt4 book ai didi

java - 在 hibernate 中使用复合主键保留 1-m 实体

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:08 25 4
gpt4 key购买 nike

我在指导学生的实体上有低于 1-m 的关系。导师有复合主键,我将其用作学生的外键

@Entity
public class Mentor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private MentorPK id;
private String email;
@OneToMany(mappedBy="mentor")
private Set<Student> students;

public MentorPK getId() {
return id;
}
//getters and setters
}

@Embeddable
public class MentorPK implements Serializable {

private static final long serialVersionUID = 1L;
private String name;
private String add;
//getters and setters
//override equals and hashcode
}


@Entity
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;

@ManyToOne
@MapsId("id")
@JoinColumns({
@JoinColumn(name="name_fk", referencedColumnName="name"),
@JoinColumn(name="address_fk", referencedColumnName="address")
})
private Mentor mentor;

//Getters and setters
}

然后我将上面的内容坚持如下,但只有导师在学生表为空的地方坚持。

我怎样才能坚持导师与学生相处?

Set<Student> students = new HashSet<Student>();

Student s1 = new Student();
s1.setName("Student 1");

Student s2 = new Student();
s2.setName("Student 2");

students.add(s1);
students.add(s2);

MentorPK mpk = new MentorPK();
mpk.setAddress("C");
mpk.setName("D");

Mentor m = new Mentor();
m.setId(mpk);
m.setEmail("emaill");
m.setStudents(students);

studentManager.saveMentor(m);

最佳答案

尝试将学生字段的注释更改为

@OneToMany(mappedBy="mentor", cascade = CascadeType.PERSIST)

关于java - 在 hibernate 中使用复合主键保留 1-m 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30170797/

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