I have 2 tables one is Users
and the other is UserGroup
Having ManyToMany
relationship , how can I union them into a single List with spring-data-JPA .
** don't want to use native Queries
UPDATE:
the exact query that I want:
SELECT email FROM user
UNION
SELECT title FROM group
If you want union, I guess the structure of these 2 entities are similar.
You could create a super entity and make User and UserGroup extend this new entity. Add
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
on the new entity if you want to keep 2 separate tables.Then, create a Spring Data JPA Repository for the parent entity.
Calling
UserRepository.findAll
will make JPA do theUNION
of the 2 tables, and can return aList<User>
. You'll have bothLoginUser
andGroup
instances in this list:See https://en.wikibooks.org/wiki/Java_Persistence/Inheritance for more details about JPA inheritance.
JPA/Hibernate don't support custom UNION queries, but inheritance provides out-of-the-box UNION between entities of the same hierarchy when using
TABLE_PER_CLASS
strategy.You cant generate the query you want with JPA. It's not possible to UNION the different fields. But if you map email and title to the same field (which is a nonsense) and write the following JPQL, JPA will generate your query.
So I solved my problem with creating a view in database itself and then map that to my java entity because it seems that hibernate doesn't support 'union' query