java - 如何在 spring hibernate 中加入表

标签 java mysql spring hibernate

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

约会

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

用户药物

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;
    }


}

这是查询,我尝试使用 native query = 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

最佳答案

您不得退回 Page<T>指定 nativeQuery=true 时.

如果您改为提供 HQL/JPQL 并删除 nativeQuery=true ,您可以毫无问题地获取分页结果;否则你需要返回 List<UserMedication>而不是本地查询。

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

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

我没有看到 is_active列已定义,所以我假设它是在 BaseEntity 中定义的作为一个名为 active 的属性.您需要根据需要相应地调整 HQL。我也选择不申请 JOIN FETCH UserMedication 之间的语义和两个PrescriptionAppointment .如果您发现需要将这些关系作为 UI 结果集的一部分获取,则需要相应地进行调整。但这绝对能让您入门。

关于java - 如何在 spring hibernate 中加入表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42023942/

相关文章:

mysql - 我有一个具有挑战性的 MySQL SELECT 查询,涉及库存和阈值边界

java - tomcat运行报错: Application not found

spring - 动态响应选择的变化

java - 一旦我从 future 获得结果,重新提交可调用的最佳方法是什么?

java - 如何只从java中存储在数据库中的日期中获取日期?

java - Android - ToggleButton 在滚动 ListView 后失去它的状态

javascript - 未定义最后插入的 ID

java - 覆盖 Spring :message tag with database values

java - 寻找一种更好的方法将 ArrayList<Double> 转换为 double[] 数组

java - 无法膨胀 android.view.InflateException : Binary XML file line #24: Error inflating class fragment