【问题标题】:Hibernate Join table with more than one condition but @WhereJoinTable not work具有多个条件但 @WhereJoinTable 不起作用的休眠连接表
【发布时间】:2016-11-01 22:48:29
【问题描述】:

有两个表A和B:

A(id, b_id, a_other)

B(id, b_other)

A和B对应的类是这样的:

@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;
}

我想要的查询是这样的: select * from A left join B on A.b_id = B.id and A.b_id != 0;

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

我在A类中附加@WhereJoinTable(clause = "b_id > 0"),但它没有任何意义,因为我发现它根本不起作用。

我将@WhereJoinTable 更改为@Where,我发现没有任何变化,谁能帮忙找出缺少的东西?

提前致谢。

【问题讨论】:

    标签: java mysql hibernate join


    【解决方案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;
    }
    

    希望对你有所帮助。

    【讨论】:

    • 你说的是select * from A left join B on A.b_id = B.id where A.b_id != 0,当A.b_id = 0时我什么也得不到,我想要的是select * from A left join B on A.b_id = B.id and A.b_id != 0,我会得到带有空B的对象A而不是空aOthers时@ 987654328@,不一样。
    • 但是,`@Where(clause = 'b_id > 0')` 上面的字段不起作用,我发现在休眠 SQL 日志中没有效果。
    • 你能分享一个随机的例子,就好像你得到了什么......这应该可以。 @JoinColumn 声明后你试过了吗
    • 我尝试了两个例子,这里是其中的一个日志:select a0_.id as id1_0_0_, a0_.a_other as a_other2_0_0_, a0_.b_id as b_id3_0_0_, b1_.id as id1_1_1_, b1_.b_other as b_other2_1_1_ from a a0_ left outer join b b1_ on a0_.b_id=b1_.id where a0_.id=?,@Where 子句无效
    • @JoinColumn 后面有写Where
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多