0
@Query(value = "select * from employee where ? = ?", nativeQuery = true)
    public List<Employee> getEmployees(String key, String value);

The Structure of Employee is

Id

Age

Name

when i call getEmployees with("Age",21) im getting List with zero length. in the console the query is displayed as

select * from employee where ? = ?

Community
  • 1
  • 1
Madhusudhan Aradya
  • 506
  • 1
  • 7
  • 16

2 Answers2

1

Use JPQL for custom Query

public List getEmployees(String key, String value) 
{

    Query query = (Query) entityManager.createQuery("from Employee where " + key + " = " + value);
    return query.getResultList();
}
ArunKumar M N
  • 1,256
  • 1
  • 10
  • 22
0

Use JPQL, so the query will look something like this.

@Query(value = "select * from employee where :key = :value", nativeQuery = true)
public List < Employee > getEmployees(@Param("key") String key, @Param("value") String value);
Santhosh A
  • 31
  • 1
  • 1
  • 6
  • Didn't work for me Still, it is showing "select * from employee where ? = ?" – Madhusudhan Aradya Mar 12 '19 at 09:40
  • Hibernate uses prepared statements so you can't see the full SQL. You can set the log level for org.hibernate.type to trace to see the values bound to the parameters. So that's the reason you see '?'. See this link for better understanding [https://stackoverflow.com/questions/2536829/hibernate-show-real-sql/2536835#2536835] Try not passing the key and manually pass the key: `@Query(value = "select * from employee where age = :value", nativeQuery = true) public List < Employee > getEmployees(@Param("key") String key, @Param("value") String value);` – Santhosh A Mar 12 '19 at 09:53
  • The key and value will be dynamic, the user may enter **id=1** or **name=john** or **age=23** so, "select * from employee where age = :value", nativeQuery = true" this will return employee record based only on age. – Madhusudhan Aradya Mar 12 '19 at 13:03