简体   繁体   中英

Hibernate join only if the object is not null

I have query to join three tables to get the result, But in some cases objects can be null. In this case we need to avoid the join.

Criteria patientCriteria = session.createCriteria(PatientRemindersTO.class);
patientCriteria.createAlias("patientTO", "patientTO");
patientCriteria.createAlias("doctorTO", "doctorTO");



patientCriteria.setProjection(Projections.distinct(Projections.projectionList()
                            .add(Projections.property("patientRemindersId"))
                            .add(Projections.property("doctorTO.doctorId"))
                            .add(Projections.property("doctorTO.phoneNumber"))
                            .add(Projections.property("patientTO.patientId"))
                            .add(Projections.property("patientTO.Mobile"))
                            .add(Projections.property("reminderSettingsType"))
                            ));

DetachedCriteria fcCriteria = DetachedCriteria.forClass(PatientRemindersScheduleTO.class,"patientRemindersScheduleTO");
fcCriteria.add(Restrictions.eq("patientReminderScheduleActive",'Y'));                                           
fcCriteria.setProjection(Projections.property("patientRemindersScheduleTO.patientRemindersId"));

patientCriteria.add(Subqueries.propertyIn("patientRemindersId", fcCriteria));

List results = patientCriteria.list();

In the above patientTO.patientId details in PatientRemindersTO can be null. So it will not return any results. Is there any ways to perform null check before creating alias.

Thanks for your valuable time.

In this case you shoud use LEFT_OUTER_JOIN . so your criteria will like ->

Criteria patientCriteria = session.createCriteria(PatientRemindersTO.class);
patientCriteria.createAlias("patientTO", "patientTO", Criteria.LEFT_OUTER_JOIN));
patientCriteria.createAlias("doctorTO", "doctorTO", Criteria.LEFT_OUTER_JOIN));

here is doc, you can find details about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM