我想通过限制向Hibernate中的条件添加订单。 我有两个表Event和MainEvent,关系为One To Many(MainEvent有很多事件)。
final Criteria criteria = getCurrentSession().createCriteria(
Event.class);
criteria.createAlias("mainEvent.date", "deadline");
criteria.addOrder(Order.asc("deadline"));
return criteria.list();
当我尝试运行它时,它会给我以下错误:
org.hibernate.QueryException:不是关联:date。
MainEvent实体:
@Entity
@Table(name = "MAIN_EVENT")
public class MainEventEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "MAIN_EVENT_ID")
private int id;
@Column(name = "MAIN_EVENT_DATE")
private Date date;
@OneToMany(mappedBy = "mainEvent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<EventEntity> events = new ArrayList<EventEntity>();
}
事件实体:
@Entity
@Table(name = "EVENT")
public class EventEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "EVENT_ID")
private int id;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "MAIN_EVENT_ID", nullable = false)
private MainEventEntity mainEvent;
}
答案 0 :(得分:2)
根据Criteria.createAlias的API,您可以为关联创建别名 ,而不是关联字段。
createAlias
Criteria createAlias(String associationPath,
String alias)
throws HibernateException
Join an association, assigning an alias to the joined association.
Parameters:
associationPath - A dot-seperated property path
alias - The alias to assign to the joined association (for later reference).
Returns:
this (for method chaining)
答案 1 :(得分:0)
final Criteria criteria = getCurrentSession().createCriteria(
Event.class);
criteria.createAlias("mainEvent", "me");
criteria.addOrder(Order.asc("me.deadline"));
return criteria.list();