JPA / Hibernate flatten mapping (just want to get the grandchildren and skip the children)

StackOverflow https://stackoverflow.com/questions/22111712

  •  18-10-2022
  •  | 
  •  

Frage

The use case is like this:

There is an existing database where

A has many Bs

B has many Cs

But I don't really need the Bs, I just want to know how many Cs that A contains.

So I sort of need to flatten all the Cs in all the Bs that is contained in an A, and put them in the A.

In another word, I just want to get the grandchildren and skip the children.

Is there a way to do this without creating an entity for B?

War es hilfreich?

Lösung

This should be possible using a @OneToMany association with TABLE_B as a @JoinTable:

@Entity
@Table(name="TABLE_A")
public class A {

    @OneToMany
    @JoinTable(
            name="TABLE_B",
            joinColumns = @JoinColumn( name="A_ID"),
            inverseJoinColumns = @JoinColumn( name="B_ID")
    )
    public Set<C> cs;
}

@Entity
@Table(name="TABLE_C")
public class C {

}

This way entity A is directy linked to entity C, and the B's are only used as a join table.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top