1

Hi guys I am new to jpa, named queries, etc.. and I need something like this:

select t from :tableName t

Later in code I want something like this:

em.createQuery(...);
setParameter("tableName", "Person")

Result would be:

select * from person

How to write such a generic jpa query statement allowing to select all rows from :tableName which may be defined at runtime? thanks in advance

Niki
  • 85
  • 1
  • 6

2 Answers2

1

Try this I think this works well

 EntityManagerFactory emfactory=Persistence.createEntityManagerFactory("Eclipselink_JPA" );
  EntityManager entitymanager = emfactory.createEntityManager();

  Query query = entitymanager.
  createQuery("Select p from Person p");
  List<String> list = query.getResultList();
user8193706
  • 2,387
  • 2
  • 8
  • 12
  • not working.. i am using hibernate and sql server. see error: SQLServerException: Must declare the table variable – Niki Jun 26 '17 at 10:11
1

setParameter("foo", foo) is used to set the value for column of the table not to set the table name. I do not think it will work, as you want to set the table name dynamically.

You can try this:

public returnType foo(String tableName){
    String jpql = "SELECT t FROM " + tableName+ " t";
    Query query = em.createQuery(jpql);
    //rest of the code    
}