删除具有一对一关系的实体

Deleting an entity with one to one relation

我的两个实体具有一对一的关系

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "email"), name = "library_user")
public class AppUser {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @EqualsAndHashCode.Exclude
    private Long id;

    // other fields

    @OneToOne(mappedBy="user", cascade={CascadeType.REMOVE,CascadeType.PERSIST}, orphanRemoval = true)
    private PasswordResetToken token;

    // getters/setters and equals/hashcode 
}

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Table(name = "password_reset_token")
public class PasswordResetToken {
    private static final int EXPIRATION = 60 * 24;

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

    // other fields

    @OneToOne(targetEntity = AppUser.class, fetch = FetchType.EAGER, cascade={CascadeType.REMOVE,CascadeType.PERSIST}, orphanRemoval = true)
    @JoinColumn(nullable = false, name = "user_id")
    private AppUser user;

    // getters/setters and equals/hashcode 

我试图通过这种方法删除我的用户实体

    public void deleteUser(Long id) {
        resetTokenRepository.deleteAllByUserId(id);
        userRepository.deleteById(id);
    }

PasswordResetTokenRepository class 我在我的服务方法中调用了哪个方法,为了删除用户我使用了常规的休眠方法 deleteById(Long id)

@Repository
public interface PasswordResetTokenRepository extends JpaRepository<PasswordResetToken, Long> {
    void deleteAllByUserId(Long id);
}

但是当我尝试用这种方法删除时,我得到了这个错误: not-null 属性 引用 null 或临时值:kpi.diploma.ovcharenko.entity.user.PasswordResetToken.user 我阅读了几个网站如何删除一对一关系,但他们的建议对我没有帮助。比如我尝试了很多注解的变体cascade={CascadeType.ALL},试了所有的变体(CascadeType.REMOVE,CascadeType.PERSIST等等),每次我都会遇到同样的错误。请帮助我,了解我做错了什么。

试试这个:

@OneToOne(cascade = CascadeType.REMOVE, orphanRemoval = true)

Here 是完整的解释。