Home > Back-end >  EntityManager createQuery with single column throws type error
EntityManager createQuery with single column throws type error

Time:10-29

I am using LocalContainerEntityManagerFactoryBean and OracleUCPConfig

I have class EmployeeEntity.java mapped to table employee

I have written a createQuery code as

Query query = em.createQuery("select id from Employee", EmployeeEntity.class);
query.getResultList()

I am getting error as:

Type specified for TypedQuery [EmployeeEntity] is incompatible with [java.lang.String]

how do I solve this issue?

I want all ids from the table not any other fields needs to retrieved

--EDIT--

I solved the issue by change the JQL to JPQL

Query query = em.createQuery("select new EmployeeEntity(id) from Employee", EmployeeEntity.class);
query.getResultList()

CodePudding user response:

you are mapping id to type EmployeeEntity, if you check your query, you are extracting only id instead of everything: select id from Employee. you can fix this by changing your query to:

Query query = em.createQuery("select e from Employee e", EmployeeEntity.class);

if you need only id column you could do something like:

TypedQuery<String> query = em.createQuery("select e.id from Employee e", String.class);
List<String> ids = query.getResultList();

CodePudding user response:

The second parameter of createQuery() is the type of the query result. In your case, the result type is String (a list of Strings), as you only SELECT the column id.

So this should work:

Query query = em.createQuery("select e.id from Employee e", String.class);
List<String> ids = query.getResultList();
  • Related