【发布时间】:2016-06-27 02:04:43
【问题描述】:
我有四个类,一个代表一个产品,另一个代表这个产品的一个属性,另外两个保存这个属性的值,因为它可以是字符串或整数,都有 getter 和 setter(这里省略)。
产品.class
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "product", cascade = CascadeType.MERGE, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<Attribute> attributes = new HashSet<>(0);
[...]
}
属性类
@Entity
@Table(name = "attribute")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.INTEGER)
public class Attribute {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;
@ManyToOne
@JoinColumn(name = "custom_attribute_id")
private CustomAttribute customAttribute;
@Column(name = "type")
private Integer type;
[...]
}
AttributeString.class
@Entity
@Table(name = "attribute_string")
@DiscriminatorValue("1")
public class AttributeString extends Attribute {
@Column(name = "value")
private String value;
[...]
}
AttributeInteger.class
@Entity
@Table(name = "attribute_integer")
@DiscriminatorValue("2")
public class AttributeInteger extends Attribute {
@Column(name = "value")
private Integer value;
[...]
}
我想使用 Hibernate Criteria 创建一个投影查询来计算产品具有的不同属性和值的数量,如下所示:
// Projection query to list the summary of attribute
Session session = (Session) em.getEntityManagerFactory().createEntityManager()
.getDelegate();
Criteria criteria = session.createCriteria(Product.class);
criteria.creatAlias("attributes", "attribute");
criteria.creatAlias("attribute.customAttribute", "customAttribute");
Projection projectionSummary = Projections.projectionList()
.add(Projections.groupProperty("customAttribute.id"))
.add(Projections.groupProperty("attribute.value"))
.add(Projections.count("id"));
List<Object[]> items = criteria.setProjection(projectionSummary).list();
但这会引发错误org.hibernate.QueryException: could not resolve property: value of com.example.entity.Attribute
【问题讨论】:
标签: java hibernate projection