也許這是一個過於簡單的問題,但我在嘗試刪除用戶實體時遇到了異常。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