无法删除具有ManyToOne关系的父实体

时间:2020-01-14 10:08:21

标签: java spring jpa

我正在使用Java,Spring和JPA开发Web应用程序。我有这两个实体,分别代表一个用户及其关注通知。当用户关注另一个用户时,被关注的用户会收到关注通知。

@Entity
public class User{
    @Id
    private Long userId;

    @OneToMany(mappedBy = "user",
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    private List<Notification> notifications;
}

@Entity
public class FollowNotification{
    @Id
    private Long followNotificationId;

    @ManyToOne(
            fetch = FetchType.LAZY
    )
    @JoinColumn(name = "id")
    private User user;

    @ManyToOne
    private User follower;

}

我想删除“用户”并也删除其所有通知,但是我想保留该通知的引用用户,该用户开始跟随主要用户。 唯一的问题是,当我尝试删除用户时,出现此错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 无法删除或更新父行:外键约束失败 ({database_namefollow_notification,约束 FK8ob9ie1tjkkon036uokkg52j2外键(follower_id)参考 useruser_id))

我在做什么错?如何删除具有所有通知的用户,同时保留关系的另一端?

1 个答案:

答案 0 :(得分:1)

您具有外键约束follower_id,可确保您不能删除通知所引用的用户。在删除用户之前,您需要将给定用户的所有通知的引用通知user_id设置为null。

>

i)remove orphanRemoval = true以及CascadeType.ALL(CascadeType.ALL,包括REMOVE)指示删除操作应自动级联到该字段引用的实体对象(多个实体对象可以由收集字段))中的User

@OneToMany(mappedBy = "user") private List<Notification> notifications;

ii)以及在nullable = true中为用户添加FollowNotification,即

@JoinColumn(name = "id",nullable = true) private User user;

iii)现在删除用户的代码应如下所示

public void deleteUser(int id) {
 // code to get entity manager and then      
Query query = entitymanager.createQuery("Select u " + "from User u " + "where u.userId=+id");

      User user=query.getResultList( ).get(0);

      Set notifications= user.getNotification();
      Iterator<Notification> noteIterator = notifications.iterator();
        while (notification.hasNext()){
            Notification notification= noteIterator.next();
            notification.setUser(null); 
            } 
      entitymanager.remove(user);
    }
相关问题