Home > front end >  @OneToMany - how to skip flagged child elements?
@OneToMany - how to skip flagged child elements?

Time:10-11

2 entities that I have: Country and User

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

Entity User has an attribute, removedtype boolean and we need to skip/ignore all User's that have removed equals true.

Does Hibernate provide any suitable mechanism to achieving my goal?

P.S: Google says that potentially I can use annotations like: @JoinColumn, @JoinColumnOrFormula, but based on docs that I have read, annotations mentioned above belong to @ManyToOne scenario, in my particular case I have @OneToMany relation.

CodePudding user response:

With hibernate, using @Where on the entity should do the trick. This will prevent any user to be loaded which has the removed flag set to true. You might find more information in the hibernate docs

If you only want this to be on the collection, you can add the annotation on the relationship

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

Alternatively, if you don't want to load any removed user at all, the annotation can be added to the 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;
}

A word of caution, I haven't used this, but I assume that if you have other entities with linked to a user which has the flag set to true, you'll need to update the annotations to allow nulls.

For example, imagine an ecomerce site, an Order is linked to a user. Loading an Order linked to a removed user will fail, or you can ammend the annotations so it returns an order with a null user. I hope this makes sense!

  • Related