Hibernate标准问题

时间:2011-04-26 19:19:08

标签: hibernate criteria

假设我有两个Hibernate POJO:Customer和Order。 Order表有三个相关列:customerId,totalItemsSold和totalCost。 Customer表包含列:customerId,firstName,lastName和city。

我在Order和Customer表之间映射了多对一。我的订单POJO包含一个Customer对象。我想执行以下Criteria查询:

DetachedCriteria crit = DetachedCriteria.forClass(Order.class);
crit.add(Restrictions.eq("customer.city", "Chicago"));
getHibernateTemplate().findByCriteria(crit);

这总是抛出以下异常:

org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: customer.city of: Order

如何根据客户的城市使用Criteria搜索订单?我的订单pojo确实包含一个名为“Customer”的Customer对象,其中包含适当的getter和setter .....

按要求编辑(订单/客户类别):

public class Customer {
     private Integer customerId;
     private String firstName;
     private String lastName;
     private String city;

     public Integer getCustomerId() { return customerId; }
     public void setCustomerId(Integer customerId) { this.customerId = customerId; }
     public String getFirstName() { return firstName; }
     public void setFirstName(String firstName) { this.firstName = firstName; }
     public String getLastName() { return lastName; }
     public void setLastName(String lastName) { this.lastName = lastName; }
     public String getCity() { return city; }
     public void setCity(String city) { this.city = city; }
}

public class Order { 
     private Customer customer;
     private Integer totalItemsSold;
     private Integer totalCost;

     public Customer getCustomer() { return customer; }
     public void setCustomer(Customer customer) { this.customer = customer; }
     public Integer getTotalItemsSold() { return totalItemsSold; }
     public void setTotalItemsSold(Integer totalItemsSold) { this.totalItemsSold = totalItemsSold; }
     public Integer getTotalCost() { return totalCost; }
     public void setTotalCost(Integer totalCost) { this.totalCost = totalCost; }
}

这是Order类的hbm映射(包含Customer和Order之间的映射):

<many-to-one name="customer" class="Customer" column="customerId" />

3 个答案:

答案 0 :(得分:2)

你发布的内容似乎很好。也许您的hbm文件中有错误?

如果没有看到完整的hbm,我很想明确告诉你关于客户关系的超然标准:

crit.createAlias("customer", "customer"); 

答案 1 :(得分:1)

如果您只是按customerId搜索,那么您拥有的是:

DetachedCriteria crit = DetachedCriteria.forClass(Order.class);
crit.add(Restrictions.eq("customer.customerId", 12));
getHibernateTemplate().findByCriteria(crit);

可能会奏效。否则杰夫和上面提到的其他人,你必须加入与提到的客户表

crit.createAlias("customer", "customer"); 

答案 2 :(得分:0)

Order类中的Customer实例变量是customer或customerId吗?