Art Kujtimi
Art Kujtimi

Reputation: 11

How to create a general query in JPA?

In every table in my database I have a column called table_id. To get this value I need to create a method i.e getTableId() ... in every repository. Is there a way that I have to create the method getTableId once and call it from different classes. I think of a query like @Query(Select n.table_id from :myClass n).

Upvotes: 1

Views: 145

Answers (2)

Romil Patel
Romil Patel

Reputation: 13727

From your question, I assume that you don't want to use .findAll(), .findById() in your all repository and want to use only once, and want to write a query as below.

public interface XXXRepository extends CrudRepository<XXX, Integer> {
@Query(value = "select * from ?1 where ...", nativeQuery = true)
List<XXX> findByXXX(String tableName, ...);
}

Here you can only use Query Parameters after where.. which means you cannot use the Query Parameter as Table Name.

Yes, you can get Table name as below if you have a @Table(name="tableName") annotation in your Entity.

yourEntityClassName.class.getAnnotation(Table.class).name()

Upvotes: 1

balaaagi
balaaagi

Reputation: 512

Have a method passing the table name. Inject neccessary repositories. Based on the table name call findAll. From the results you can fetch the ids.

Upvotes: 0

Related Questions