Maybe this is an overly simple question, but I am getting an exception when I try to delete a user entity.
The user entity:
@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;
And I have an entity class which references a user with a foreign key. What I want to happen is that when the user is deleted, any PasswordResetToken
objects that reference the user are also deleted. How can I do this?
@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;
The exception I am getting boils down to 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`))
I'd like to avoid adding a reference to PasswordResetToken
in the parent entity, becaue User
shouldn't need to know anything about PasswordResetToken
.