这是我的模型(简化)
产品
@Entity
@Table(name = "products")
public class Product extends BaseEntity {
@Id
private Long id;
private String name;
@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumn(name = "product_id")
private List<ProductAttribute> attributes;
}
产品属性
@Entity
@Table(name = "product_attribute_values")
public class ProductAttribute extends BaseEntity {
@Id
private Long id;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "product_id")
private Product product;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "attribute_id")
private Attribute attribute;
private String value;
}
属性
@Entity
@Table(name = "attributes")
@Proxy(lazy = false)
public class Attribute extends BaseEntity {
@Id
private Long id;
private String name;
}
我想查询单个产品(按ID)并按属性名称排序属性(ProductAttributes)列表。
这是我的查询
final Criteria criteria = getSession().createCriteria(Product.class);
criteria.add(Restrictions.eq("id", productId));
Criteria crit = criteria.createCriteria("attributes");
Criteria secondCriteria = crit.createCriteria("attribute");
secondCriteria.addOrder(Order.desc("name"));
return (Product) criteria.uniqueResult();
我也尝试了这个,但它没有用(不识别名字字段)
final Criteria criteria = getSession().createCriteria(Product.class);
criteria.add(Restrictions.eq("id", productId));
criteria.createAlias("attributes", "atr");
criteria.addOrder(Order.asc("atr.attribute.name"));
有什么想法吗?
答案 0 :(得分:0)
我做到了。只需创建一个别名并在两个
中指定连接类型final Criteria criteria = getSession().createCriteria(Product.class);
criteria.add(Restrictions.eq("id", searchFilter.getProductId()));
criteria.createAlias("attributes", "atrs", CriteriaSpecification.LEFT_JOIN);
criteria.createAlias("atrs.attribute", "atr", CriteriaSpecification.LEFT_JOIN);
criteria.addOrder(Order.asc("atr.name"));