双向一对一映射

Bi-directional one-to-one mapping

@Entity
@Table(name="Instructor")
public class Instructor {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;
    
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "detail_id")
    private InstructorDetails detail;
    
    @Column(name="name")
    private String name;
}

这是我的第一个实体 class,这个 class 确实包含所需的 setter 和 getter 以及构造函数,我没有包含它们,因为它们会使问题冗长

@Entity
@Table(name="InstructorDetails")
public class InstructorDetails {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "did")
    private int did;
    
    @OneToOne(mappedBy = "detail",cascade = CascadeType.ALL)
    private Instructor instructor;
    
    @Column(name = "address")
    private String address;
    
    @Column(name = "course")
    private String course;
    
    @Column(name = "hobby")
    private String hobby;
    
    @Column(name = "dept")
    private String dept;
}

这是我的第二个实体 class,这个 class 确实包含所需的 setter 和 getter 以及构造函数,我没有包含它们,因为它们会使问题冗长

如您所见,我已经尝试执行双向一对一映射, 我已经明确提到 cascade=CascadeType.ALL,这意味着一个 table 中发生的所有操作都级联到另一个,我试图通过包含 @OneToOne(mappedBy = "detail", cascade = CascadeType.ALL)[=23 来执行双向映射=]

这里的问题是

Session session = sf.getCurrentSession(); 
session.beginTransaction();

InstructorDetails detail=new InstructorDetails("bengaluru", "Java", "Guitar", "development");
Instructor instructor=new Instructor("john",detail);

session.save(instructor);
session.getTransaction().commit();

此代码将详细信息推送到 InstructorInstructorDetails table,但如果

Session session = sf.getCurrentSession(); 
session.beginTransaction();

Instructor instructor=new Instructor();
instructor.setName("Sam");
InstructorDetails detail=new InstructorDetails("bengaluru", "Java", "Guitar", "development");
detail.setInstructor(instructor);
    
session.save(detail);
session.getTransaction().commit();

此代码仅将数据推送到 InstructorDetails table 和 Instructor table 未更新讲师详细信息,这意味着映射是单向的

Instructor上的所有CRUD操作级联到InstructorDetails,但我无法实现反之亦然,请在这里帮助我,我如何确保所有在 InstructorDetails 上执行的 crud 也会影响 Instructor

正如休眠状态中所述documentation:

Whenever a bidirectional association is formed, the application developer must make sure both sides are in-sync at all times.

因此,您应该按以下方式更正您的代码:

Session session = sf.getCurrentSession(); 
session.beginTransaction();

Instructor instructor = new Instructor();
instructor.setName("Sam");
InstructorDetails detail = new InstructorDetails("bengaluru", "Java", "Guitar", "development");

// sync both side of association
detail.setInstructor(instructor);
instructor.setDetail(detail);

session.save(detail);
session.getTransaction().commit();