Nahid Guliyev
Nahid Guliyev

Reputation: 3

Select specific columns from table with JPA in java

I want to write a Query for getting specific columns.using

entitymanager.createQuery("SELECT u.name FROM Department u").getResultList();

however it returns object is not an instance of declaring class. What is the correct way to get specific column from table in jpa.as a provider i am using Hibernate

Upvotes: 0

Views: 1599

Answers (1)

Petr Mensik
Petr Mensik

Reputation: 27496

It returns list of objects (it would be hard for JPA to guess what types are you returning). But luckily you can give it a hint with TypedQuery like this

TypedQuery<String> query = em.createQuery("SELECT u.name FROM Department u",
    String.class);
List<String> departmentNames = query.getResultList();

Upvotes: 1

Related Questions