2

Suppose I have two object Patient and its MedicalRecord with OneToMany relation.

i.e.

class Patient {
    ...
    @OneToMany(mappedBy = "patient")
    List<MedicalRecord> mr;
    ...
}

class MedicalRecord {
    ...
    @ManyToOne
    Patient patient;

    Date createdAt;
    ...
}

Now I want to work with the MedicalRecord(s) within one month. What is the best way to do this?

I know i could do it using JPQL with @NamedQuery or @Query. But I don't feel it's as good as I expected. Can I do this without issuing JPQL query and stay in the object domain? For example to add constraint on the "Patient.mr" field so that only records within one month will be retrieved and I can iterate through them without worrying about unnecessary database fetch?

Thanks!

2 Answers 2

4

This enum includes the date ranges:

public enum DateType {

    PAST_DAY,

    PAST_WEEK,

    PAST_MONTH, 

    PAST_YEAR 
}

This Query:

interface MedicalRecordRepository extends JpaRepository<MedicalRecord, Long> {
   @Query("select md from MedicalRecord md left join fetch md.patient pt   where md.createdAt >=:selectedDate")
   List<MedicalRecord> searchByDate(selectedDate);
}

Impletation Class:

     @Service
     class  MedicalRecordServiceImpl implements MedicalRecordService{

      public  List<MedicalRecord> searchByDate(DateType dateType){
            Date today = new Date();
            Calendar cal = new GregorianCalendar();
            cal.setTime(today);

            switch (dateType) {
            case PAST_DAY:
                cal.add(Calendar.DATE, -1);
                break;
            case PAST_WEEK:
                cal.add(Calendar.DAY_OF_WEEK, -1);
             break;
            case PAST_MONTH:
                cal.add(Calendar.DAY_OF_MONTH, -1);
                break;
            case PAST_YEAR:
                cal.add(Calendar.YEAR, -1);
                break;
            }
            List<MedicalRecord> result = repository.searchByDate(cal.getTime());
            return result;
       }
 }

Returns results based on your choice of date.

Sign up to request clarification or add additional context in comments.

Comments

2

You can utilize Hibernate filters for this purpose.

Assuming there is RECORD_DATE column in the table to which MedicalRecord is mapped, you can define a filter like RECORD_DATE >= SYSDATE - 30 for the mr collection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.