Skip to content
Advertisement

How use generic entity name in JPQL

I have three tables with same column name and types, what changes is just the table name.

Example: | TABLE1 | TABLE2 | TABLE3 | | —— | —— | ——- | | ID | ID | ID | | NAME | NAME | NAME | | FOO | FOO | FOO | | BAR | BAR | BAR |


I have three entities, one to each table.

Entity Parent:

JavaScript

Entity Childs:

JavaScript
JavaScript
JavaScript

I have a generic repository, with some methods:

JavaScript

So far so good. See code repetition below, with methods findEntityXToDto:

JavaScript
JavaScript
JavaScript

It’s here problem. How create SELECT JPQL generic? Something as:

JavaScript

Advertisement

Answer

Spring Data JPA release 1.4 supports the usage of restricted SpEL template expressions in manually defined queries that are defined with @Query. It supports a variable called entitiyName. It inserts the entityName of the domain type associated with the given repository. I would suggest using separate repositories and pass the SpEL there. For example:

Let you have a BaseEntity and other entities like TableOne, TableTwo and TableThree. All extends the BaseEntity and have the exact same attributes.

JavaScript

Create a base repository with @NoRepositoryBean annotation as it prevents spring to implement the repository on this base repository.

JavaScript

Finally Implement your own repository based on each entity:

JavaScript

And call this repository from the entity wise service class:

JavaScript

Now just call the method demoMethod and you’ll get result for TableOne entity. Implement exactly the same for the other entities. Hence you can solve your problem.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement