在Hibernate中查询扩展类的属性

时间:2016-03-11 17:54:13

标签: java hibernate projection

我有四个类,一个代表一个产品,另一个代表该产品的属性,另外两个代表该属性的值,因为它可以是String或Integer,都带有getter和setter(这里省略)。

Product.class

import ng = angular

Attribute.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);

    [...]
}

AttributeString.class

@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;

    [...]
}

AttributeInteger.class

@Entity
@Table(name = "attribute_string")
@DiscriminatorValue("1")
public class AttributeString extends Attribute {

    @Column(name = "value")
    private String value;

    [...]
}

我想用Hibernate Criteria创建一个投影查询来计算产品具有的不同属性和值的数量,如下所示:

@Entity
@Table(name = "attribute_integer")
@DiscriminatorValue("2")
public class AttributeInteger extends Attribute {

    @Column(name = "value")
    private Integer value;

    [...]
}

但这会引发错误// 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();

1 个答案:

答案 0 :(得分:0)

正如您的例外所述

  

无法解析属性:com.example.entity.Attribute的值

Attribute.class中,您遇到了getter和setter方法的问题。它可能不遵循惯例。

如果您使用任何IDE like eclipse,请尝试使用它来创建getter setter方法,这将有助于您更多地遵循惯例。

id, product, customAttribute and type创建getter和setter。

id为例:

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

<强>更新

我认为attributes将是attribute。请检查我是否错了。

criteria.creatAlias("attributes", "attribute");

使用以下代码

criteria.creatAlias("attribute", "attribute");