Darth Blue Ray
Darth Blue Ray

Reputation: 9745

Namedqueries and inheritance

I have a question about the use of namedqueries and inheritance

if I have a build like :

                               User (abstract) not persisted
                                    ¦
                    __________________________________
                    ¦               ¦                ¦

                Customer         Manager        Administrator        

And you place them for example in a single table (inheritancetype)

If you work with a Userrepository to retrieve them all you could work with namedqueries. For this you would need to write the namedqueries in the User entity.

Is it possible to retrieve the child classes with the namedqueries in the parentclass?

What if I choose to use inheritancetype = Table by class, then my namedqueries can't be the same?

Upvotes: 4

Views: 2236

Answers (2)

Chris
Chris

Reputation: 21145

Named queries can be defined anywhere in the persistence unit, and do not need to deal directly with the class they are defined on, it just makes sense to have them on user if they involve user. As for inheritance, JPA requires that any "select user from User user" type query return Users that match the selection criteria. This includes Customers, Managers and any subclass that is considered a User regardless of the type of inheritance used. Single table, joined, table per class - all require returning subclasses. So some care needs to be taken to avoid creating expensive queries due to unneeded inheritance.

JPA allows restricting using the TYPE() function in JPQL so that you can include or exclude specific classes from the results, and JPA 2.1 will include TREAT to perform similar functionality.

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

Absolutely. If you say:

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

(assuming age is a property of User) the query will return all subclasses of User matching given criteria. The result will be List<User> so you'll have to downcast to Customer, Manager or Administrator.

The inheritance strategy doesn't have anything to do here. If you ask for a User, JPA implementation will always return proper subclass. After all, User can and should be abstract.

Upvotes: 3

Related Questions