User12345
User12345

Reputation: 486

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.

Upvotes: 1

Views: 1239

Answers (1)

Bhushan Uniyal
Bhushan Uniyal

Reputation: 5703

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.

Upvotes: 1

Related Questions