也许这是一个过于简单的问题,但我在尝试删除用户实体时遇到了异常。Spring数据JPA:如何在不引用父级中的子级的情况下启用级联删除?
用户实体:
@Entity
@Table(name = "users")
public class User
{
@Transient
private static final int SALT_LENGTH = 32;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@NotNull
private String firstName;
@NotNull
private String lastName;
@Column(unique = true, length = 254)
@NotNull
private String email;
// BCrypt outputs 60 character results.
@Column(length = 60)
private String hashedPassword;
@NotNull
private String salt;
private boolean enabled;
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date createdDate;
而且我有它引用与外键的用户的实体类。我想要发生的是当用户被删除时,任何引用用户的对象也被删除。我怎样才能做到这一点?
@Entity
@Table(name = "password_reset_tokens")
public class PasswordResetToken
{
private static final int EXPIRATION_TIME = 1; // In minutes
private static final int RESET_CODE_LENGTH = 10;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String token;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
@JoinColumn(nullable = false, name = "userId")
private User user;
private Date expirationDate;
我得到的异常归结为Cannot delete or update a parent row: a foreign key constraint fails (`heroku_bc5bfe73a752182`.`password_reset_tokens`, CONSTRAINT `FKk3ndxg5xp6v7wd4gjyusp15gq` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))
我想避免在父实体添加引用PasswordResetToken
,becaue User
应该不需要了解任何PasswordResetToken
。
假设你看看这个[post](https://vladmihalcea.com/2015/03/05/a-beginners-guide-to-jpa-and-hibernate-cascade-types/),它解释更多关于你的问题和解决方案。 –
假设你必须添加'@OneToOne(mappedBy =“user”,cascade = CascadeType.ALL,orphanRemoval = true)' –
给用户实体?或者PasswordResetToken实体?我并不是真的想在User实体中添加任何引用,因为用户实体不需要知道重置令牌的存在。 – Airhead