Hibernate do not include child entities of same type as entity in list of another entity

Viewed 325

I have two entities, Menu and MenuItem, as showed in the source code below. I'm trying to get the Menu with all child entities from the database, but Hibernate is also inserting the child entities of a MenuItem in the nodes list of the Menu entity.

Menu.java

[...]

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "menu", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("order ASC")
    private List<MenuItem> nodes = new ArrayList<MenuItem>();
[...]

MenuItem.java

[...]

    @ManyToOne
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name = "parentId")
    private MenuItem parentItem;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parentItem", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<MenuItem> children = new ArrayList<MenuItem>();

    @ManyToOne(optional = false)
    @JoinColumn(name = "menuId")
    private Menu menu;
[...]

As a hint: I know you should not use FetchType.EAGER for collections, but as I need all elements of the collections, it is useful to load them when the Menu is loaded. The Menu won't be used without the lists.

2 Answers

Only MenuItems that are expected to be direct descendands of the Menu should have menu field set, otherwise all of them will be fetched to the nodes collection because of mappedBy = "menu".

btw, as far as your use case for EAGER fetch type seems justified, you should not use EAGER fetching in general, not only on collections. This is a good read about the topic.

CascadeType.ALL will propagate (cascade) all EntityManager operations to the relating entities.

Try to remove cascade = CascadeType.ALL from relation.

By default, no operations are cascaded.

Related