简体   繁体   中英

Conditional JoinColumn in Entity JPA/Hibernate

I do have a situation where I need to fetch data from three different tables based on some condition. Eg.

@Entity
class Order{
   id;
   type;
   typeId;

   @Join with boqTable to get the Boq Associated with if type == BOQ and id = typeId
   @Join with customTable to get custom data associated if type == CUSTOM and id = typeId
}

I should able to insert and update the child tables using the Order entity. How do I can this using JPA/Hibernate.. I searched a lot and i couldn't get any solution, apart from manually doing it at the service level instead of handling at the Entity Model

You can use one of 2 non-JPA compliant, Hibernate specific features. If the condition is static then see the Hibernate @Where annotation. See section 2.4.6:

https://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/

Otherwise see Hibernate filters:

Hibernate3 has the ability to pre-define filter criteria and attach those filters at both a class level and a collection level. A filter criteria allows you to define a restriction clause similar to the existing "where" attribute available on the class and various collection elements. These filter conditions, however, can be parameterized. The application can then decide at runtime whether certain filters should be enabled and what their parameter values should be. Filters can be used like database views, but they are parameterized inside the application.

https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/filters.html

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