如何使用SpringDataJPA(Hibernate)跨映射表过滤关联实体?
有没有办法在中间实体(映射表)中使用@OneToMany和过滤软删除的多对多关联@ManyToOne?
product并且product_option_group是 N:M 关系。我正在使用该disabled_datetime列实现软删除,并希望ProductOptionGroup从Product实体中过滤一个集合。这篇文章正在使用@ManyToMany并@Where实现这一目标。我跟着,它工作(禁用product_option_groups 被过滤)。需要注意@Where的ProductOptionGroup类。
// `product` <-> `product-product_option_group` <-> `product_option_group`
@Entity
@Table(name = "product")
public class Product implements Serializable {
...
@ManyToMany
@JoinTable(name = "product-product_option_group",
joinColumns = @JoinColumn(name = "product_id"),
inverseJoinColumns = @JoinColumn(name = "product_option_group_id"))
private final Set<ProductOptionGroup> productOptionGroups = new HashSet<>();
...
}
@Entity
@Table(name = "product_option_group")
@Where(clause = "disabled_datetime is null")
public class ProductOptionGroup implements Serializable {
...
@Column(name = "disabled_datetime")
private ZonedDateTime disabledDatetime;
...
}
但我想用@OneToMany在product-product_option_group桌子上,就像这样。
@Entity
@Table(name = "product")
public class Product implements Serializable {
...
@OneToMany(mappedBy = "id.product")
private final Set<ProductProductOptionGroup> productProductOptionGroups = new HashSet<>();
...
}
@Entity
@Table(name = "`product-product_option_group`")
public class ProductProductOptionGroup implements Serializable {
@EmbeddedId
private final ProductProductOptionGroupId id = new ProductProductOptionGroupId();
...
}
@Embeddable
public class ProductProductOptionGroupId implements Serializable {
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "product_id", referencedColumnName = "id")
private Product product;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "product_option_group_id", referencedColumnName = "id")
@Where(clause = "disabled_datetime is null")
private ProductOptionGroup productOptionGroup;
}
@Entity
@Table(name = "product_option_group")
@Where(clause = "disabled_datetime is null")
public class ProductOptionGroup implements Serializable {
...
}
但随后@Where注释将不再起作用,因此product_option_group也选择了 disabled s。如何解决这个问题?
THE END
二维码