There are two tables with @OneToMany and @ManyToOne bidirectional relation, like this:
@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;
}
all things sound OK, but when I want to search data using Restriction like this,
session.createCriteria(Asset.class).add(Restrictions.eq("dealings.customer.id", customerId)).add(Restrictions.eq("dealing.product.id", productId)).list();
In this level I get this error,
could not resolve property: dealings.customer of: com.project.foo.model.Asset
one of the solutions are to change my strategy but i wasted time to find this,btw I don’t have any idea about it, do you ?
First of all, you don’t have a bidirectional OneToMany association, but two unrelated unidirectional associations. In a bidirectional OneToMany association the One side must be marked as the inverse of the Many side using the
mappedByattribute:Second, using the criteria API for such static queries is overkill, and leads to code that is harder to read than necessary.I would simply use HQL which is much easier to read. Criteria should be used for dynamic queries, IMHO, but not for static ones:
Whether you use HQL or Criteria, you can’t use
asset.dealings.customer, sinceasset.dealingsis a collection. A collection doesn’t have a customer attribute. To be able to reference properties from the Dealing entity, you need a join, as shown in the above HQL query. And it’s the same for Criteria: