在Hibernate中如何将@OneToOne与@Where一起使用?

时间:2018-06-27 09:44:23

标签: java hibernate one-to-one

我现在有2个实体,一个是POST,另一个是POST_DETAILPOST_DETAIL存储了POST的不同翻译。

(简体)POST模式:

- ID NUMBER

(简体)POST_DETAIL模式:

 - ID NUMBER
 - REF_ID NUMBER  # FK to POST.ID
 - LANG VARCHAR
 - TITLE VARCHAR

我想在POST_DETAIL内使用Hibernate批注将 ONLY (例如英语)POST之一

class Post {
    ...
    // annotations
    private PostDetail postDetailEn;
}

感谢您的帮助

编辑: 我希望做

之类的事情
class Post {
    ...
    @OneToOne(mappedBy = "post")
    @JoinColumn(name = "ID", referencedColumnName = "REF_ID", 
                insertable = false, updatable = false)
    @Where(clause = "POST_DETAIL.LANG = 'EN'")           // not working
    @WhereJoinTable(clause = "POST_DETAIL.LANG = 'EN'")  // not working
    private PostDetail postDetailEn;
}

class PostDetail {
    ...

    @OneToOne
    @JoinColumn(name = "REF_ID", insertable = false, updatable = false)
    @Where(clause = "LANG = 'EN'")           // not working
    @WhereJoinTable(clause = "LANG = 'EN'")  // not working
    private Post post;

    @Column(name = "REF_ID")
    private Long refId;        

    @Column(name = "LANG")
    private String lang;
}

但是hibernate记录的sql对于where子句什么也没显示

编辑:例如: 数据库中的记录

+-----------+  +-----------------+  +-----------------+
| Post (#1) |  | PostDetail (#1) |  | PostDetail (#2) |
+-----------+  |    refId: 1     |  |    refId: 1     |
               |    lang : EN    |  |    lang : EN    |
               +-----------------+  +-----------------+

我想得到

Post(id=1, 
     postDetail=PostDetail(id=1, 
                           refId=1, 
                           lang=EN))

3 个答案:

答案 0 :(得分:0)

class Post {
    @OneToOne
    @JoinColumn(name = "ID", referencedColumnName = "REF_ID")
    private PostDetail postDetailEn;
}

答案 1 :(得分:0)

您应该为此使用@OneToOne注释。

所有者侧

 class Post {
       @OneToOne(cascade = CascadeType.ALL)
       @JoinColumn(name = "postdetail_id")
       private PostDetail postDetail;
    }

答案 2 :(得分:0)

我发现这篇关于@JoinFormula的帖子,并且我有类似的情况。

由于我只需要在PostDetail内放置一个Post,所以没有在Post中添加PostDetail字段,所以我的解决方案是

class Post {
    ...
    @ManyToOne(fetchType = FetchType.LAZY)
    @JoinFormula("(SELECT D.ID FROM POST_DETAIL D WHERE D.REF_ID = ID AND D.LANG = 'EN')")
    private PostDetail postDetailEn;
}