我必须阅读hibernate中的一些特定列。我写过这样的方法
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;
}
但是在这里我必须手动构造我不想要的对象。我想以对象形式读取结果,我不想手动构建对象。我的实体就像这样
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;
分支不映射到实体,而它是可嵌入的。我想以DTO的形式阅读数据,所以我已经通过了ResultTransformer类,但它只使用sqlQuery而不是HQL(如果我错了,请纠正我)。我无法改变我的疑问。请帮助我
答案 0 :(得分:1)
Hibernate可以在HQL中使用new
关键字(called dynamic instantiation/constructor expression)为您完成此任务:
只需将您的查询更改为:
select new your.package.name.Branch(bran.branch.branchId,bran.branch.branchName) from Location bran where bran.branch.branchId =:branchId