Why do I have to persist both objects if Address is nested in User?

后端 未结 3 1299
无人共我
无人共我 2021-02-09 05:54

I am trying to better familiarize myself with JPA so I created a very simple project. I have a User Class and an Address class. It appears that I have to persist both even tho

3条回答
  •  一整个雨季
    2021-02-09 06:26

    What you're talking about it's called Cascading. That means doing the same action to nested objects, such as an Address in your User. By default, there is no cascading at all if you don't specify any CascadeType.

    You can define various cascade types at once

    @OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
    private List
    addresses;

    or just tell JPA to cascade every operation:

    @OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = CascadeType.ALL)
    private List
    addresses;

    Both ways will result in, for example, a persisted Address while persisting an User or the deletion of the associated Address when an User is removed.

    But!... if you remove CascadeType.REMOVE from the first example, removing an User won't remove its associated Address (The removal operation won't be applied to nested objects).

提交回复
热议问题