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

后端 未结 3 1300
无人共我
无人共我 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:25

    Try the cascade element for the annotation.

    @OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade=CascadeType.PERSIST) 
    private List<Address> addresses; 
    

    The documentation says that by default no operation is cascaded. It also states that the cascade operation is optional, so it really depends on the implementation that you are using.

    Also, while setting the relationship, make sure you set both sides of the relationship. Set addresses to the user and user to the addresses.

    0 讨论(0)
  • 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<Address> addresses;
    

    or just tell JPA to cascade every operation:

    @OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = CascadeType.ALL)
    private List<Address> 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).

    0 讨论(0)
  • 2021-02-09 06:31

    You are using a oneToMany annotation. From my understanding you have to persist the parent class (the USer) when you want to add a child class (Address) to it.

    By persisting the User class, you do let know JPA know which row to update.

    0 讨论(0)
提交回复
热议问题