2012-03-20 78 views
1

我有一個@Entity類,它有多個ID列,並且它們都是外鍵。這個類的代碼如下所示:無法加入@JoinColumn @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; 

    ..... 
} 

我想在CriteriaNews實體date列添加Restriction。所以我做了這樣的條件:

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 
... 

這個問題是由於缺少加入語句引起的。在查詢中沒有加入聲明:

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註釋嗎?

回答

0

您需要一個@OneToOne(fetch=FetchType.EAGER)註釋來完成該連接。

或者,也許做一個.setFetchMode("news", FetchMode.JOIN)