繁体   English   中英

如何在 spring 数据 jpa 中加入 2 个表时自动添加 where 子句

[英]How to auto add where clause when joining 2 tables in spring data jpa

上下文:有 2 个具有 1:1 关系的表想要在表连接上添加 where 子句试图通过添加@WhereJoinTable(clause = "addressType = 'STORE_ADDRESS'")注释来实现这一点,但在我的情况下它不起作用

@Entity
@Table(name = "A")
public class A extends BaseEntity {

    @Column(name = "name")
    @Size(max = 500)
    private String name;

    @Column(name = "created_by", updatable = false)
    private String createdBy;

    @Column(name = "updated_by")
    private String updatedBy;

    @OneToOne(mappedBy = "store", fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false)
    @JsonManagedReference
    @WhereJoinTable(clause = "addressType = 'STORE_ADDRESS'")
    private Address address;

    public Store() {
    }
}

,

@Entity
@Table(name = "address")
public class Address extends BaseEntity {
    @OneToOne
    @JoinColumn(name = "id")
    @JsonBackReference
    private A store;

    @Column(name = "address")
    private String address;

    @Column(name = "address_type")
    @Enumerated(EnumType.STRING)
    private StoreAddressType addressType;

    public StoreAddress() {

    }
}

@WhereJoinTable注解在使用关联表时使用。 1:1 关系不需要关联表。

@Where注释应用于您的目标实体。

这就是为什么您应该尝试使用@Where注释而不是@WhereJoinTable注释。 您可以按如下方式执行此操作。

import org.hibernate.annotations.Where;

@Entity
@Table(name = "A")
public class A extends BaseEntity {

    @Column(name = "name")
    @Size(max = 500)
    private String name;

    @Column(name = "created_by", updatable = false)
    private String createdBy;

    @Column(name = "updated_by")
    private String updatedBy;

    @OneToOne(mappedBy = "store", fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false)
    @JsonManagedReference
    @Where(clause = "addressType = 'STORE_ADDRESS'")
    private Address address;

    public Store() {
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM