Friday, April 5, 2013

Hibernate - How to query an entity with selected columns only

In Hibernate usually when we query an entity from database it contains all the data of that row, it means all the data in the columns are contained in that entity object.
For an example assume that you have a table named as user which contains columns id, name, age and address. When you want to query a user row usually you use a query like this.

select user from User user where user.id = 10

You know the returned User object contains all the data of the row(ie. id, name, age and address)
But what can you do if you need to query id, name and age only.
Yes, one solution is to use the required columns in to the query by separating with commas as below and getting an array of values as the result.
select user.id, user.name, user.age from User user where user.id = 10

But there is another way to do this in Hibernate.
You can use a query like this.
select new User(user.id, user.name, user.age) from User user where user.id = 10

Now you get a User object which contains values of id, name and age only. Yes it is that much easy :)

Important: In order to query like this you need to have the appropriate constructor in your entity. For an example according to this example your User class should have following constructor.
public User(Integer id, String name, Integer age) {
  this.id = id;
  this.name = name;
  this.age = age;
}

No comments:

Post a Comment