【问题标题】:how to join the tables in spring hibernate如何在春季休眠中加入表格
【发布时间】:2017-02-03 12:07:11
【问题描述】:

我有 3 个表,如何在休眠中加入查询

约会

id schedule_date subject  user_id doctor_id
1  23-12-2016    Fever    1           21
2  24-12-2016    headache 2           22

处方

id appointment_id status
1  1              1
2  2              2

user_medications

id prescription_id drug_id status
1  1                1       1
2  1                2       1

现在我需要用户药物的结果

如果条件 user_id = 1 & status = 1

对于下面的sql,我会得到下面的结果。

SELECT um.id, p.id as prescription_id, um.drug_id, um.status FROM `appointments` a
LEFT JOIN `prescriptions` p ON a.id = p.appointment_id
LEFT JOIN `user_medications` um ON p.id = um.prescription_id
WHERE a.patient_id = 30 and um.id != null group by um.id

id prescription_id drug_id status
1  1                1       1
2  1                2       1

这是我的实体类:

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "appointments")
public class Appointment extends BaseEntity {

    private static final long serialVersionUID = 1320944167976543131L;

    @Column(name = "schedule_date")
    private Date scheduleDate;

    @Column(name = "patient_id")
    private Long patientId;

    @Column(name = "doctor_id")
    private Long doctorId;

    @Column(name = "subject")
    private String subject;

    @ManyToOne
    @JoinColumn(name = "doctor_id", insertable=false, updatable=false)
    private Doctor doctor;

    @ManyToOne
    @JoinColumn(name = "patient_id", insertable=false, updatable=false)
    private User user;


    public Date getScheduleDate() {
        return scheduleDate;
    }

    public void setScheduleDate(Date scheduleDate) {
        this.scheduleDate = scheduleDate;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public Doctor getDoctor() {
        return doctor;
    }

    public void setDoctor(Doctor doctor) {
        this.doctor = doctor;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

处方实体:

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "prescriptions")
public class Prescription extends BaseEntity {

    private static final long serialVersionUID = 6316326407564010588L;

    @Column(name = "user_id")
    private Long userId;

    @Column(name = "appointment_id")
    private Long appointmentId;


    @OneToOne
    @JoinColumn(name = "appointment_id", insertable=false, updatable=false)
    private Appointment appointment;

    @OneToMany(mappedBy = "prescription")
    private Set<UserMedication> userMedications = new HashSet<>();

    @Column(name = "is_self_declared")
    private Boolean isSelfDeclared;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }



    public Long getAppointmentId() {
        return appointmentId;
    }

    public void setAppointmentId(Long appointmentId) {
        this.appointmentId = appointmentId;
    }


    public Boolean getIsSelfDeclared() {
        return isSelfDeclared;
    }

    public void setIsSelfDeclared(Boolean isSelfDeclared) {
        this.isSelfDeclared = isSelfDeclared;
    }

    public Appointment getAppointment() {
        return appointment;
    }

    public void setAppointment(Appointment appointment) {
        this.appointment = appointment;
    }

    public Set<UserMedication> getUserMedications() {
        return userMedications;
    }

    public void setUserMedications(Set<UserMedication> userMedications) {
        this.userMedications = userMedications;
    }

    public Doctor getDoctor() {
        return doctor;
    }

    public void setDoctor(Doctor doctor) {
        this.doctor = doctor;
    }
}

用户用药实体:

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "prescription_medications")
public class UserMedication extends BaseEntity {

    private static final long serialVersionUID = -3853355501806579362L;

    @Column(name = "prescription_id")
    private Long prescriptionId;

    @Column(name = "drug_id")
    private Long drugId;

    @Column(name = "dosage")
    private String dosage;


    @ManyToOne
    @JoinColumn(name = "prescription_id", insertable=false, updatable=false)
    private Prescription prescription;



    public Long getPrescriptionId() {
        return prescriptionId;
    }

    public void setPrescriptionId(Long prescriptionId) {
        this.prescriptionId = prescriptionId;
    }

    public Long getDrugId() {
        return drugId;
    }

    public void setDrugId(Long drugId) {
        this.drugId = drugId;
    }

    public String getDosage() {
        return dosage;
    }

    public void setDosage(String dosage) {
        this.dosage = dosage;
    }


}

这是查询,我尝试使用原生查询 = true

@Query(value = "select a.id as appointment_id, um.id as user_medication_id, um.drug_id from appointments a "
            + "left join prescriptions p on a.id = p.appointment_id "
            + "left join user_medications um on p.id = um.prescription_id "
            + "where a.patient_id = :userId and um.is_active = :userMedicationStatus and um.id is not null",
            nativeQuery = true)
Page<UserMedication> findUserMedications(@Param("userId") Long userId, @Param("userMedicationStatus") Boolean userMedicationStatus, Pageable pageRequest);

我发现他出现以下错误,

'userMedicationRepository': Invocation of init method failed; nested exception is org.springframework.data.jpa.repository.query.InvalidJpaQueryMethodException: Cannot use native queries with dynamic sorting and/or pagination in method public abstract org.springframework

【问题讨论】:

    标签: java mysql spring hibernate


    【解决方案1】:

    在指定nativeQuery=true 时,不允许返回Page&lt;T&gt;

    如果您改为提供 HQL/JPQL 并删除 nativeQuery=true,则可以毫无问题地获取分页结果;否则,您需要返回 List&lt;UserMedication&gt; 来代替本机查询。

    您的查询转换为 HQL 以返回 UserMediciation 实体将是:

    SELECT um FROM UserMedication um
    JOIN Prescription p 
    WHERE p.userId = :userId
    AND um.active = :userMediciationStatus
    

    我没有看到is_active 列的定义,所以我认为它在BaseEntity 中定义为一个名为active 的属性。您需要根据需要相应地调整 HQL。我还选择不在UserMedicationPrescriptionAppointment 之间应用JOIN FETCH 语义。如果您发现需要将这些关系作为 UI 结果集的一部分获取,则需要相应地进行调整。但这绝对可以帮助您入门。

    【讨论】:

    • 我可以在 HQL/JPQL 中为上述内容获取一些文档参考吗
    • 添加了 HQL 表示。如您所见,HQL 也比原始 SQL 更易于阅读。
    • 我不能为这种类型的功能使用@Query 注释,就像这样...@Query(value = "SELECT um FROM UserMedication JOIN Prescription p WHERE p.userId = :userId AND um.active = :userMediciationStatus") Page findUserMedications(@Param("userId") Long userId, @Param("userMediciationStatus") int[] userMediciationStatus, Pageable pageRequest);
    • 对不起@javailike 有一个小错字。你能再试一次吗,我很抱歉。
    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 2012-12-05
    • 2015-06-30
    相关资源
    最近更新 更多