【问题标题】:org.hibernate.QueryException: not an associationorg.hibernate.QueryException:不是关联
【发布时间】:2014-09-04 08:18:07
【问题描述】:

我想通过限制向 Hibernate 中的条件添加订单。 我有两个表 Event 和 MainEvent 的关系是一对多(一个 MainEvent 有很多事件)。

    final Criteria criteria = getCurrentSession().createCriteria(
            Event.class);
    criteria.createAlias("mainEvent.date", "deadline");
    criteria.addOrder(Order.asc("deadline"));
    return criteria.list();

当我尝试运行它时,它给了我以下错误:

org.hibernate.QueryException:不是关联:日期。

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;

}

【问题讨论】:

  • 发布您的实体代码

标签: hibernate criteria


【解决方案1】:

根据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)

【讨论】:

  • 很高兴看到我们应该在上下文中做些什么,而不是从文档中快速粘贴。
【解决方案2】:
   final Criteria criteria = getCurrentSession().createCriteria(
        Event.class);
criteria.createAlias("mainEvent", "me");
criteria.addOrder(Order.asc("me.deadline"));
return criteria.list();

【讨论】:

    猜你喜欢
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    相关资源
    最近更新 更多