我创建了两个实体,即Teacher和Detail,代码片段如下所示
Teacher.java
@Entity
@Table(name = "teacher")
public class Teacher implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private int age;
@OneToOne(mappedBy = "teacher", cascade = CascadeType.ALL)
private Detail detail;
public Teacher() {
}
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
//getter and setter
}
Detail.java
@Entity
@Table(name = "detail")
public class Detail implements Serializable {
@Id
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id")
private Teacher teacher;
@Column(name = "subjects")
private String subjects;
public Detail() {
}
public Detail(String subjects) {
this.subjects = subjects;
}
//getter and setter
}
我正在尝试使用共享主键概念实现一对一映射 但是当我执行控制器时,只有“教师”表正在使用该值更新
try {
Teacher teacher=new Teacher("xyz",23);
Detail detail=new Detail("Java,c,c++");
teacher.setDetail(detail);
session.beginTransaction();
session.save(teacher);
session.getTransaction().commit();
model.addAttribute("added", "data inserted");
session.close();
}
执行后仅使用指定值更新教师表。详细信息表仍显示为空
答案 0 :(得分:0)
它不能完全那样工作。您仍然需要Detail
中的id字段,因此添加:
@Id
private long id;
进入您的Deatail
班。
并且-如注释所建议-将字段@Id
中的Teacher
注释替换为@MapsId
。这样,Teacher
的ID会映射到Detail
的ID,但只有在您还将教师设置为详细信息的情况下-始终需要设置关系的两面,例如:
teacher.setDetail(detail);
detail.setTeacher(teacher);