在春季JPA中代表亲子关系

时间:2019-08-07 03:00:25

标签: spring hibernate spring-data-jpa

我有以下情况。我有一个代表用户表的父类User.java。我有两个子类-Doctor.java和Patient.java。这些类的数据在“用户”表中。病人表中提供了病人和医生之间的映射。并且此映射可以是ManyToMany。该“ doctor Patient”表由DoctorPatient.java类表示。

我需要以这样的方式来映射我的医生和患者类别:我的医生类别应让所有患者返回特定的医生,而患者类别应将所有医生返回特定患者。
我是新来的冬眠者,将不胜感激。


User.java

@Entity
@Table(name = "User")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;

    @Column(name="UserName", nullable = false, length = 16)
    private String userName;

    @Column(name="FirstName", nullable = false, length = 45)
    private String firstName;

    @Column(name="LastName", nullable = false, length = 45)
    private String lastName;

    @Column(name="Email", nullable = false, length = 45)
    private String email;

    // Getters and Setters
}

Doctor.java

public class Doctor extends User {
    @OneToMany(mappedBy="doctor")
    List<DoctorPatient> patientList;

    //Getters and Setters
}

Patient.java

public class Patient extends User {
    @OneToMany(mappedBy="patient")
    List<DoctorPatient> doctorsList;
    //Getters and Setters
}

DoctorPatient.java

@Entity
@Table(DoctorPatient)
public class DoctorPatient {
    @EmbeddedId
    private DoctorPatientId doctorPatientId;

    @ManyToOne(targetEntity = Doctor.class)
    @JoinColumn(name="doctorId")
    private Doctor doctor;

    @ManyToOne(targetEntity = Patient.class)
    @JoinColumn(name="patientId")
    private Patient patient;

    //Getter Setters
}

为DoctorPatient表创建命令

CREATE TABLE 'DoctorPatient' (
    'DoctorId''INT(11) NOT NULL,
    'PatientId' INT(11) NOT NULL,
    PRIMARY KEY ('DoctorId', 'PatientId'),
    INDEX 'FK_Doctor_idx' ('DoctorId'),
    INDEX 'FK_Patient_idx' ('PatientId'),
    CONSTRAINT 'FK_Patient' FOREIGN KEY ('PatientId') REFERENCES 'User' ('UserId'),
    CONSTRAINT 'FK_Doctor' FOREIGN KEY ('DoctorId') REFERENCES 'User' ('UserId')
)

当前,对于每位医生,我都需要从DoctorPatient表中获取Patientid(用户ID),我需要使用该表查询user表以获取患者详细信息。 同样,对于患者,我只能从DoctorPatient表中检索Doctorid(UserId)。然后,我需要遍历列表并点击“用户”表以获取完整的详细信息。


解决方案

更新的课程


Patient.java

public class Patient extends User {
    @ManyToMany
    @JoinTable(name="DoctorPatient", joinColumns=        {@JoinColumn(name="PatientId") }, inverseJoinColumns={           @JoinColumn(name="DoctorId") } )
    private Set<Doctor> DoctorList = new HashSet<>();
    //Getters and Setters
}

Doctor.java

public class Doctor extends User {
    @ManyToMany(mappedBy="DoctorList")
    private Set<Patient> patients = new HashSet<>();      
    //Getters and Setters
}

0 个答案:

没有答案