简体   繁体   中英

how to get parent from child in JPA element collection?

hello i am working with spring and jpa and i have a parent entity with an elementsCollection children :

PARENT

@Table(name = "MY_PARENT_TABLE")
public class MyParentTable extends BaseEntity implements Comparable<MyParentTable> {
    @Id
    @NotNull
    private String id;


    @NotNull
    private String groupId;


    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "MY_ELEMENTS", joinColumns = @JoinColumn(name = "GROUP_ID"))
    @AttributeOverrides({
            @AttributeOverride(name = "elementId", column = @Column(name = "MY_ELEMENT_ID")),
    })
    private Set<MyElement> elements = new TreeSet<>();
...

CHILD

@Table(name = "MY_ELEMENTS")
public class MyElement extends BaseEntity implements Serializable, Comparable<MyElement> {
    @NotNull
    @UniqueElements
    private String elementId;
...

and i have a list of children List<MyElement> and i want to access, or get their parents directly, without searching the database for the parent that contains the specific child, because that will take too much time.

so is there a way to achieve that ?

Edit :

more precisely, the List<MyElement> children i have, contains children, and a number of them will have the same parent, so it wouldn't be a good solution to just reference the parent entity in the child, and do this :

for (var elm : children) 
   //search for parent in the database
   //update elm on parent  

because, and i wouldn't benefit from the fact that some of the children will have the same parent, ( every time i will have to search the database for every child's parent )

Sure, you just have to store that in your child object. I think it's called a two-way relationship. So you have Object A with a list of Object Bs, and each Object B has a reference to its owning Object A. Here's another StackOverflow question which I think will show you how to implement that in Java: Two-way relation in JPA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM