【问题标题】:Spring Framework is not updating child entity when parent is updated更新父实体时,Spring Framework 不更新子实体
【发布时间】:2018-04-19 21:16:01
【问题描述】:

我不知道出了什么问题。这是我拥有餐厅的酒店实体:

@OneToMany(mappedBy = "hotel", cascade = CascadeType.ALL)
@JsonIgnoreProperties({"hotel"})
private List<Restaurant> restaurants;

这是我的餐厅实体,其中有酒店:

@ManyToOne(cascade = CascadeType.ALL)
@JoinTable(
        name = "restaurant_hotel",
        joinColumns = @JoinColumn(name = "restaurant_id"),
        inverseJoinColumns = @JoinColumn(name = "hotel_id")
)
@JsonIgnoreProperties({"restaurants"})
private Hotel hotel;

当我更新餐厅时,我可以毫无问题地设置酒店,并在查看酒店时看到变化。但是当我更新酒店时,只有酒店会更新。酒店的餐厅没有更新。

只是为了澄清一下,我无意在更新酒店时更改餐厅实体本身,反之亦然。只想在更新酒店实体时更改哪些餐厅属于酒店。目前只能在更新餐厅时更换酒店。

我在使用org.springframework.data.repository.PagingAndSortingRepository 保存酒店对象之前检查了它,并且它包含正确的餐厅。

【问题讨论】:

标签: spring hibernate spring-boot spring-data


【解决方案1】:

您应该查看此帖子 https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/,尤其是该部分 在提到父实体上的两个实用程序方法的双向 @OneToMany 中。

父实体 Post 具有两个实用方法(例如 addComment 和 removeComment),用于同步双向关联的双方。当您使用双向关联时,您应该始终提供这些方法,否则,您将面临非常微妙的状态传播问题。

我相信您的问题与类似的状态传播问题有关,如果您在父酒店实体中添加实用方法 addRestaurant、removeRestaurant 并在更新酒店之前使用它们,它将得到解决。

    public void addRestaurant(Restaurant restaurant) {
        restaurants.add(restaurant);
        restaurant.setHotel(this);
    }

    public void removeRestaurant(Restaurant restaurant) {
        restaurants.remove(restaurant);
        restaurant.setHotel(null);
    }

您的案例与链接中的案例之间的区别在于您使用的是@JoinTable 而不是@JoinColumn,但我认为这并不重要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-24
    • 2019-12-05
    • 2016-11-16
    • 2019-02-09
    • 1970-01-01
    • 2021-02-09
    • 2021-03-12
    • 2015-01-26
    相关资源
    最近更新 更多