@OneToMany - 如何跳过标记的子元素?

@OneToMany - how to skip flagged child elements?

我拥有的 2 个实体:CountryUser

@Entity(name = "Country")
@Table(name = "countries")
public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL,
            orphanRemoval = true)
    private List<User> users = new ArrayList<>();
}

@Entity(name = "User")
@Table(name = "users")
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private boolean removed;
}

实体 User 有一个属性,removed类型 boolean 我们需要 skip/ignore 所有具有 removedUser等于 true.

Hibernate 是否提供任何合适的机制来实现我的目标?

P.S: Google 说可能我可以使用如下注释:@JoinColumn@JoinColumnOrFormula,但基于我读过的文档,上面提到的注释属于 @ManyToOne 场景,在我的特定情况下,我有 @OneToMany 关系。

对于休眠,在实体上使用 @Where 应该可以解决问题。这将防止加载已删除标志设置为 true 的任何用户。您可能会在 hibernate docs

中找到更多信息

如果你只希望这个在集合中,你可以在关系上添加注释

@Entity(name = "Country")
@Table(name = "countries")
public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL,
            orphanRemoval = true)
    @Where( clause = "removed = false" ) // <- here
    private List<User> users = new ArrayList<>();
}

或者,如果您根本不想加载任何已删除的用户,可以将注释添加到 class。

@Entity(name = "User")
@Table(name = "users")
@Where( clause = "removed = false" ) // <- here
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private boolean removed;
}

请注意,我没有使用过它,但我假设如果您有其他实体链接到将标志设置为 true 的用户,您将需要更新注释以允许空值.

例如,想象一个电子商务网站,一个订单链接到一个用户。加载链接到已删除用户的订单将失败,或者您可以修改注释,使其 returns 与 null 用户的订单。我希望这是有道理的!