Is there a way to filter a soft deleted many-to-many association using @OneToMany
and @ManyToOne
, across an intermediate entity(mapping table)?
product
and product_option_group
are in N:M relation. I'm implementing the soft deletion using the disabled_datetime
column and want to filter a collection of ProductOptionGroup
from the Product
entity. This post is using @ManyToMany
and @Where
to achieve this. I followed and it worked(disabled product_option_group
s are filtered from product.getProductOptionGroups()
). Note @Where
on ProductOptionGroup
class.
// `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;
...
}
but I want to use @OneToMany
towards the product-product_option_group
table, like this.
@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 {
...
}
But then the @Where
annotations won't work anymore, so disabled product_option_group
s are also selected from product.getProductProductOptionGroups().stream().map(o -> o.getId().getProductOptionGroup().collect(Collectors.toList())
. How to solve this?