我有两个实体,一个实体带有特定枚举的字段。现在,我想检索所有具有特定枚举值的东西。
@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。
休眠说:
org.hibernate.QueryException:无法解析属性:
alarmType.type的:datamodel.AlarmEvent
最佳答案
您只有在alarmType
类中定义的AlarmEvent
属性,没有alarmType.type
。那就是错误消息的意思。
您需要将条件扩展到关联的类AlarmEventDefinition
。代码应该是这样的:
List<AlarmEvent> result = (List<AlarmEvent>) session.createCriteria(AlarmEvent.class)
.createCriteria("alarmType").add(Restrictions.eq("type", AlarmEventDefinitionType.Trigger))
.list();