0

有两个具有@OneToMany 和@ManyToOne 双向关系的表,如下所示:

@Entity
public class Asset {
    private int id;
    private int count;
    @OneToMany
    private Set<Dealing> dealings;
...
}

@Entity
public class Dealing {

    private int id;
        ...
    @ManyToOne
    @JoinColumn(name = "customer_id", nullable = false, updatable = false)
    private Customer customer;
    @ManyToOne
    @JoinColumn(name = "product_id", nullable = false, updatable = false)
    private Product product;
    @ManyToOne(cascade = CascadeType.ALL)
    private Asset asset;
}

一切听起来都不错,但是当我想像这样使用 Restriction 搜索数据时,

session.createCriteria(Asset.class).add(Restrictions.eq("dealings.customer.id", customerId)).add(Restrictions.eq("dealing.product.id", productId)).list();

在这个级别我得到这个错误,

could not resolve property: dealings.customer of: com.project.foo.model.Asset

解决方案之一是改变我的策略,但我浪费时间找到这个,顺便说一句,我对此一无所知,是吗?

4

1 回答 1

1

首先,您没有双向 OneToMany 关联,而是两个不相关的单向关联。mappedBy在双向 OneToMany 关联中,必须使用属性将一侧标记为多侧的逆:

@OneToMany(mappedBy = "asset")
private Set<Dealing> dealings;

其次,对此类静态查询使用标准 API 是多余的,并且会导致代码比必要的更难阅读。我会简单地使用更容易阅读的 HQL。标准应该用于动态查询,恕我直言,但不适用于静态查询:

select asset from Asset asset 
inner join asset.dealings dealing
where dealing.customer.id = :customerId
and dealing.product.id = :productId

无论您使用 HQL 还是 Criteria,都不能使用asset.dealings.customer,因为asset.dealings它是一个集合。集合没有客户属性。为了能够从 Dealing 实体引用属性,您需要一个连接,如上面的 HQL 查询所示。标准也是一样的:

Criteria criteria = session.createCriteria(Asset.class, "asset");
criteria.createAlias("asset.dealings", "dealing"); // that's an inner join
criteria.add(Restrictions.eq("dealing.customer.id", customerId);
criteria.add(Restrictions.eq("dealing.product.id", productId);
于 2013-01-27T22:30:43.240 回答