我是java和休眠的新手。ExpenseType.java
public class ExpenseType extends BaseDomain {
private int companyId;
private String name;
private String description;
private Company company;
// Getters and Setters
}
Company.java
public class Company extends BaseDomain {
private String name;
private String address;
private String contactNumber;
private String emailAddress;
// Getters and Setters
}
我有2个对象ExpenseType和Company。他们有一个
many-to-one
关系。的映射在此文件
expenseType.hbm.xml
中。expenseType.hbm.xml
<hibernate-mapping>
<class name="bp.ar.domain.hibernate.ExpenseType" table="EXPENSE_TYPE">
.
.
<property name="companyId">
<column name="COMPANY_ID"/>
</property>
<many-to-one name="company" class="bp.ar.domain.hibernate.Company" fetch="select" insert="false" update="false" lazy="false">
<column name="COMPANY_ID" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
我的ExpenseType表中有COMPANY_ID外键。
在文件
ExpenseTypeDaoImpl.java
的实现中,我执行了类似的操作@Override
public Collection<ExpenseType> getAll(int companyId, Collection<Company> companies,
ExpenseTypeField orderBy) {
DetachedCriteria dc = getDetachedCriteria();
dc.addOrder(Order.asc("company"));
dc.addOrder(Order.asc(orderBy.name()));
return getAll(dc);
}
我真正想发生的事情是ExpenseType的结果将根据公司名称排序。上面的代码发生的事情是,它根据tbe COMPANY_ID排序ExpenseType。我尝试使用
dc.addOrder(Order.asc("company.name"));
,但出现错误。我有这个错误:
org.hibernate.QueryException: could not resolve property: company.name of: bp.ar.domain.hibernate.ExpenseType
请帮忙。提前致谢。
最佳答案
您需要先为该关系创建别名,然后才能对其属性进行排序。这类似于SQL JOIN。
DetachedCriteria dc = getDetachedCriteria();
dc.createAlias("company", "company");
dc.addOrder(Order.asc("company.name"));
return getAll(dc);