0

I have an entity A with two @OneToMany association with the entity B, the difference is an attribute of the entity B that change in 1 and 2 association.

@Entity
@Table
class AEntity {
    @Id
    Long id;
    
    @OneToMany(mappedBy = "a", cascade = CascadeType.PERSIST, orphanRemoval = true)
    private List<BEntity> bFirstList;
    
    @OneToMany(mappedBy = "a", cascade = CascadeType.PERSIST, orphanRemoval = true)
    private List<BEntity> bSecondList;

}
@Entity
@Table
class BEntity {
    @Id
    Long id;
    
    @ManyToOne
    @JoinColumn(name = "a_id")
    private AEntity a;
    
    private BType type;

}
enum BType {
    FIRST,
    SECOND;
}

I want in List bFirstList; all instance where type is FIRST, and in bSecondList all instances where type is SECOND.

How can I acheive this? Is it possible to specify a custom query for the join or is there a better approach to the problem?

Davide C
  • 830
  • 2
  • 11
  • 21

1 Answers1

1

I believe you are looking for something like this:

@Entity
@Table
class AEntity {
    @Id
    Long id;
    
    @OneToMany(mappedBy = "a", cascade = CascadeType.PERSIST, orphanRemoval = true)
    @Where(clause = "type = FIRST")
    private List<BEntity> bFirstList;
    
    @OneToMany(mappedBy = "a", cascade = CascadeType.PERSIST, orphanRemoval = true)
    @Where(clause = "type = SECOND")
    private List<BEntity> bSecondList;

} 

See https://stackoverflow.com/a/43239330/3444205.

Andrés Alcarraz
  • 1,570
  • 1
  • 12
  • 21