Hibernate UniDirectional ManyToOne按子属性查询

时间:2011-05-27 09:02:06

标签: java hibernate

@Entity
public class Store {}


@Entity
@Table(name = "storeitem")
public class StoreItem {

    @Id @Column
    private Integer storeId;

    @Id
    @ManyToOne @JoinColumn (name="productId", referencedColumnName="id")
    private Product product;

    @Column private Double cost;
}

mysql> desc storeitem;
+-------------+---------------------+------+-----+---------+-------+
| Field       | Type                | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+-------+
| StoreId     | int(10) unsigned    | NO   | PRI | 0       |       |
| ProductId   | bigint(20) unsigned | NO   | PRI | 0       |       |
| cost        | double unsigned     | NO   |     | 0       |       |



@Entity
@Table(name = "product")
public class Product {
    @Id @GeneratedValue @Column(name = "Id")
    private Long id;

    @Column(name = "Name")
    private String name;
}

mysql> desc product;
+-------------+---------------------+------+-----+---------+----------------+
| Field       | Type                | Null | Key | Default | Extra          |
+-------------+---------------------+------+-----+---------+----------------+
| Id          | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| Name        | varchar(70)         | NO   |     |         |                |




 Criteria cr=sess.createCriteria(StoreItem.class);
 cr.add(Restrictions.eq("product.name","butter"));
 cr.list();

当我尝试按照孩子的属性进行过滤时,我会在异常下面看到

org.hibernate.QueryException: could not resolve property: product.name of:StoreItem

2 个答案:

答案 0 :(得分:0)

Try{

    Criteria cr=sess.createCriteria(StoreItem.class, "si");
     crit.createCriteria("product","product").add(Restrictions.eq("name","butter"));
     cr.list();

}

答案 1 :(得分:0)

HQL解决了问题

String hql="from StoreItem where productId in (select pd.id from Product pd where name = 'butter')";
Query query=sess.createQuery(hql);
query.list();