Skip child to fetching of parent - JPA

僤鯓⒐⒋嵵緔 提交于 2021-02-07 19:01:49

问题


I am facing an issue where the data is getting fechted recursively. I wanted to avoid the child to fetch the parent data. Which is causing a recursive issue. I have mentioned the code below

Pojo Structure

class Parent  {
    ..
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    private List<Child> childs;

    ..
    }

class Child {
    ..
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parentId")
    private Parent parent;
    ..
    }

Fetching the data like this

 `  em = EMF.get().createEntityManager();
    Query q = em.createQuery("Select p from Parent p", Parent.class);
    List<Parent> parents = q.getResultList();
    // Till this point all looks good but when the code gets executed 
    parent.getChilds();
`

It is fetching the data like this:

Parent
child1
    Parent
        child2
            Parent
                child2
                    Parent
                ..
        ..
child2
..

Which I dont need I just want the data like this:

Parent1
    child1
    child2
Parent2
    child1
    child2
    child3

回答1:


While FetchType.EAGER is a contract, FetchType.LAZY is only a hint, because lazy fetching is not always possible. This may depend e.g. on the JPA provider you use as well as on its configuration. Lazy fetching is particularly problematic with to-one relationships.

If every Child has a Parent, try adding optional=false to your @ManyToOne. This might enable lazy fetching.

Since the Parent entity is already loaded into the persistence context, populating Children.parent shouldn't trigger queries against the database. Are you actually seeing queries being executed? How do you know Children.parent is being loaded? If you are accessing the value to check that fact, chances are you are actually triggering the on-demand loading yourself.




回答2:


It'll work as infinite loop for hefty data. Best practice is to mention @JsonIgnore at child class column. Thank me Later




回答3:


To Avoid this issue , Please declare below annotation Parent & Child getter methods

   @JsonBackReference
    public Parent getParent() {
        return parent;
    }

@JsonManagedReference
    public List<Child> getChilds() {
    return childs;
    }



回答4:


To avoid this problem of cyclic references, I used a Mapper with MapStruct (see official documentation for a quick setup) :

Then I can easily write a mapper to ignore a property like this :

public interface SecondaryObjectMapper {
  @Mapping(target = "primaryObject.secondaries", ignore=true),
  SecondaryObjectDto toSecondaryObjectDto(SecondaryObject source);
}

and use it like this for example :

repository.findAll(pageable).map(secondaryObjectMapper::toSecondaryObjectDto)


来源:https://stackoverflow.com/questions/44161835/skip-child-to-fetching-of-parent-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!