简体   繁体   English

仅当对象不为空时,Hibernate联接

[英]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. 我有查询来联接三个表以获得结果,但是在某些情况下对象可以为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. 在上面的PatientTO.patientId中,PatientRemindersTO中的详细信息可以为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 . 在这种情况下,您应该使用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. 是文档,您可以找到有关它的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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