Hibernate使用多个条件连接表但@WhereJoinTable不起作用

时间:2016-06-30 02:22:36

标签: java mysql hibernate join

有两个表A和B:

A(id,b_id,a_other)

B(id,b_other)

A和B的相应类别如下:

1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
5 * 5 = 25

查询我想要的是: @Entity @Table(name = "A") public class A { @Id @Column(name = "id") private Integer id; @JoinColumn(name = "b_id", nullable = true) @OneToOne(fetch = FetchType.EAGER) @WhereJoinTable(clause = "b_id > 0") private B b; @Column(name = "a_other") private Integer aOther; } public class B { @Id @Column(name = "id") private Integer id; @Column(name = "b_other") private Integer bOther; } ;

您可能会发现痛点是额外的加入条件A.b_id!= 0

我在A级中附上select * from A left join B on A.b_id = B.id and A.b_id != 0,但这没有任何意义,因为我觉得它根本不起作用。

我将@WhereJoinTable(clause = "b_id > 0")更改为@WhereJoinTable,我发现没有任何变化,任何人都可以帮助指出缺少的内容吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果您想要A.b_id!= 0,可以添加以下注释

@Where(clause = 'b_id > 0')

所以你的代码应该是这样的:

@Entity
@Table(name = "A")
public class A {
    @Id
    @Column(name = "id")
    private Integer id;
    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "b_id", nullable = true)
    @Where(clause = 'b_id > 0')
    private Audience audience;

    @Id
    @Column(name = "a_other")
    private Integer aOther;
} 

public class B {
    @Id
    @Column(name = "id")
    private Integer id;

    @Id
    @Column(name = "b_other")
    private Integer bOther;
}

希望对你有所帮助。