无法加入@JoinColumn,即@Id

时间:2012-03-20 02:01:33

标签: java hibernate join hibernate-criteria

我有一个@Entity类,它有多个ID列,所有这些都是外键。类代码如下所示:

@Entity
@Immutable
@Table(name = "AnyNews")
public class AnyNews implements Serializable {
    private static final long serialVersionUID = 43876852L;

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

    @Id
    @OneToOne
    @JoinColumn(name = "news_id")
    private News news;

    .....
}

我想在Restriction上添加Criteria News个实体的date列。所以我制定了这样的标准:

Criteria criteria = sessionFactory.getCurrentSession()
        .createCriteria(AnyNews.class, "any")
        .createCriteria("news", "news");
        .add(Restrictions.eq("news.id", id))
        .add(Restrictions.ge("news.date", from.getTime()));

代码看起来不错,但它会产生如下错误:

org.hibernate.exception.SQLGrammarException: could not execute query
...

问题是由于缺少Join语句引起的。查询中没有Join语句:

select
    this_.id as news4_5_0_,
    this_.news_id as keyword1_5_0_,
    this_.board_no as board2_5_0_,
    this_.seq as seq5_0_ 
from
    AnyNews this_ 
where
    this_.news_id=? 
    and news1_.date>=? 

为什么Hibernate会像这样进行查询。我不能在同一列上使用@Id和@JoinColumn注释吗?

1 个答案:

答案 0 :(得分:0)

您需要@OneToOne(fetch=FetchType.EAGER)注释才能加入。

或者,也许可以.setFetchMode("news", FetchMode.JOIN)