0

我有一个类声明为

@Entity
@Table(name = "word", schema = "public")
public class Word implements java.io.Serializable {
    ...
    private ContentLanguage contentLanguage;
    ...
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "content_language_id", nullable = false)
    public ContentLanguageT getContentLanguage() {
        return this.contentLanguage;
    }

    public void setContentLanguage(ContentLanguage contentLanguage) {
        this.contentLanguage = contentLanguage;
    }
  ...

ContentLanguage 被声明为

    @Entity
    @Table(name = "content_language", schema = "public")
    public class ContentLanguage implements java.io.Serializable {

        private int id;
        private String value;
 ....

我的操作需要查询 ContentLanguage 字段具有 id = 1 的所有单词. 有什么想法,因为我不想去开始使用 SQL 或 HQL 来完成一项相对简单的任务?

                public String execute() 
    {       
        //DetachedCriteria criteria1 = DetachedCriteria.forClass(ContentLanguageT.class);
        //criteria1.add(Restrictions.eq("id",1));
        DetachedCriteria criteria = DetachedCriteria.forClass(WordT.class);
        //criteria.add( criteria1 );
        criteria.add(Restrictions.eq("contentLanguageT", Integer.valueOf( contentLangID )));        
        allWords = wordDao.findByCriteria( criteria, 0, 50);        
        return SUCCESS;
    }
4

1 回答 1

2

Word.contentLanguage是类型ContentLanguage。所以你不能将它与整数进行比较。您只能将其与 ContentLanguage 进行比较。所以,要么你做

criteria.add(Restrictions.eq("contentLanguage.id", contentLanguageId));

或者你做

criteria.add(Restrictions.eq("contentLanguage", 
                             session.load(ContentLanguage.class, contentLanguageId)));

对于这样简单的静态查询,我真的更喜欢 HQL。以下内容不是更具可读性和直观性吗?

select w from Word w 
where w.contentLanguage.id = :contentLanguageId
于 2012-09-13T08:18:10.277 回答