Hibernate无法使用枚举解析类型

时间:2013-06-23 15:25:16

标签: java hibernate orm enums

我有两个实体,一个具有特定枚举的字段。现在我想要检索具有特定枚举值的所有内容。

@Entity
@Table(name = "AlarmEvent")
@XmlRootElement
public class AlarmEvent implements Identifiable {
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "guid")
    @Column(name = "Id", columnDefinition = "uniqueidentifier")
    private String id;

    @ManyToOne
    @JoinColumn(name = "AlarmType_Id")
    @XmlJavaTypeAdapter(EntityAdapter.class)
    private AlarmEventDefinition alarmType;

    @Column(name = "Timestamp", nullable = false)
    private Date timestamp;

    @Override
    @XmlTransient
    public String getIdentifier() {
        return id;
    }

    public AlarmEventDefinition getAlarmType() {
        return alarmType;
    }

    public void setAlarmType(AlarmEventDefinition alarmType) {
        this.alarmType = alarmType;
    }

    public String getId() {
        return id;
    }

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

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }
}

和第二个实体

@Entity
@Table(name = "AlarmEventDefinition")
@XmlRootElement
public class AlarmEventDefinition implements Identifiable {
    public static enum AlarmEventDefinitionType {
        Start, End, Trigger, Report
    }

    @Id
    @Column(name = "Id")
    private Integer id;

    @Column(name = "Name_DE", length = 256)
    private String nameDe;

    @Column(name = "Type")
    @Enumerated(EnumType.STRING)
    private AlarmEventDefinitionType type;

    @OneToMany(mappedBy = "alarmType", fetch = FetchType.LAZY)
    @XmlTransient
    private List<AlarmEvent> events;

    public List<AlarmEvent> getEvents() {
        return events;
    }

    public Integer getId() {
        return id;
    }

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

    public String getNameDe() {
        return nameDe;
    }

    public void setNameDe(String nameDe) {
        this.nameDe = nameDe;
    }

    public AlarmEventDefinitionType getType() {
        return type;
    }

    public void setType(AlarmEventDefinitionType type) {
        this.type = type;
    }
}

现在我想这样做

List<AlarmEvent> result = (List<AlarmEvent>) session.createCriteria(AlarmEvent.class)
        .add(Restrictions.eq("alarmType.type", AlarmEventDefinitionType.Trigger))
        .list();

要检索所有AlarmEvent,其中AlarmEventDefinitions类型为Trigger。 Hibernate说:

  

org.hibernate.QueryException:无法解析属性:   alarmType.type of:datamodel.AlarmEvent

1 个答案:

答案 0 :(得分:0)

您只有alarmType类中定义的AlarmEvent属性,没有alarmType.type。这是错误信息。

您需要将条件扩展到关联的类AlarmEventDefinition。代码应该是这样的:

List<AlarmEvent> result = (List<AlarmEvent>) session.createCriteria(AlarmEvent.class)
        .createCriteria("alarmType").add(Restrictions.eq("type", AlarmEventDefinitionType.Trigger))
        .list();