类删除引用时从关联表中删除行的方法?

时间:2019-04-11 13:15:38

标签: java mysql spring hibernate jpa

我有三个类,用户和产品,以及它们的关联类Order。我希望能够通过编辑“用户”或“产品”中的“设置”来添加和删除关联表中的行。添加正常,但是当我从中删除一些订单时用户,它们保存在数据库中。

this example之后,我想到了这段代码。

@Getter
@Setter
@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private Set<Order> orders;

    public void setOrders(Set<Order> orders) {
        this.orders = orders;
        orders.forEach(order -> order.setUser(this));
    }
}

@Getter
@Setter
@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
    private Set<Order> orders;

    public void setOrders(Set<Order> orders) {
        this.orders = orders;
        orders.forEach(order -> order.setProduct(this));
    }
}

和关联类:

@Getter
@Setter
@Entity
@NoArgsConstructor
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @ManyToOne
    @JoinColumn
    private Product product;

    @NotNull
    @ManyToOne
    @JoinColumn
    private User user;

    public Order(User user, Product product) {
        this.user = user;
        this.project = project;
    }

    @Override
    public boolean equals(Object o){
        if (this == o) return true;
        if (!(o instanceof Order)) return false;
        Engagement that = (Order) o;
        return Objects.equals(user.getUsername(), 
                           that.user.getUsername()) &&
               Objects.equals(product.getName(), 
                           that.product.getName());
    }

    @Override
    public int hashCode(){
        return Objects.hash(user.getUsername(), 
                           product.getName());
    }
}

在我的OrderService类中,添加和编辑如下的订单集:

public addProductsToUser(User user, Set<Product> products){
    Set<Order> orders = products.stream().map(product -> new Order(user, product)).collect(Collectors.toSet());
    user.setOrders(orders);
    userRepository.save(user); //save from CrudRepository
}

我希望当我更新用户时,它也会更新订单,以便删除不再引用的订单,但会保留多个订单。

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找orphanRemoval = true。这指定将删除与父级断开连接的对象。

在您的情况下,注释将如下所示:

@OneToMany(mappedBy = "user", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<Order> orders;

有关更多详细信息以及两者之间的区别,请参阅以下文章: What is the difference between cascade and orphan removal from DB?