Namedqueries and inheritance

I have a question about using namedqueries and inheritance

if I have an assembly:

User (abstract) not persisted ¦ __________________________________ ¦ ¦ ¦ Customer Manager Administrator 

And you place them, for example, in one table (inheritancetype)

If you are working with a Userrepository to get them all, you could work with namedqueries. To do this, you will need to write namedqueries in the User object.

Is it possible to get child classes using namedqueries in the parent class?

What if I prefer to use inheritancetype = Table by class, then my namedQ queries cannot be the same?

+4
source share
2 answers

That's right. If you say:

 SELECT u FROM User u WHERE u.age >= 18 

(if age is a User property), the query returns all User subclasses that match the specified criteria. The result will be a List<User> , so you will have to dump to Customer , Manager or Administrator .

The inheritance strategy has nothing in common. If you ask for User , the JPA implementation will always return the appropriate subclass. In the end, User can and should be abstract .

+2
source

Named queries can be defined anywhere in the persistence block and you do not need to directly access the class on which they are defined, but it makes sense for the user to have them if they are associated with the user. Regarding inheritance, the JPA requires that a request like “select user from user user” return users that match the selection criteria. This includes clients, managers, and any subclass that is considered by the user regardless of the type of inheritance used. A separate table, a combined table for each class - all require returnable subclasses. Therefore, the need to avoid creating costly queries due to unnecessary inheritance must be taken into account.

JPA allows you to restrict the use of the TYPE () function in JPQL so that you can include or exclude certain classes from the results, and JPA 2.1 will include TREAT to perform similar functions.

0
source

All Articles