Reputation: 1842
I have to read some specific columns in hibernate. I have written a method like this
Branch getBranch(long branchId)
{
String query = "select distinct bran.branch.branchId,bran.branch.branchName from Location bran where bran.branch.branchId =:branchId";
Session session = getSession();
session.beginTransaction();
Query buildQuery = getSession().createQuery(query).setParameter("branchId", branchId);
List<Object[]> countryList = buildQuery.list();
Branch branch = null;
for(Object[] obj : countryList)
{
branch = new Branch((Long)obj[0] , (String)obj[1]);
}
session.close();
return branch;
}
But here I have to construct the object manually which i don't want. I want to read the result in object form and i dont want manual construction of object. My entity is like this
public final class Location implements Comparable<Location>{
@Id
@Column(name = Tables.LOCATION.LOCATION_ID, nullable = false, precision = 15, scale = 0, updatable = false, insertable = false)
private long locationId;
@Column(name = Tables.LOCATION.LOCATION_NAME, length = 60, updatable = false, insertable = false)
private String locationName;
@Embedded
private Country country;
@Embedded
private Branch branch;
Branch does not map to an entity whereas it is embeddable. I want to read the data in form of DTO so i have gone through ResultTransformer class but it workd only with sqlQuery not with HQL(Correct me if i am wrong). I cant change my query .Please help me
Upvotes: 2
Views: 472
Reputation: 18542
Hibernate can do this for you by using the new
keyword (called dynamic instantiation/constructor expression) in the HQL:
Just change your query to:
select new your.package.name.Branch(bran.branch.branchId,bran.branch.branchName) from Location bran where bran.branch.branchId =:branchId
Upvotes: 1