I have a case where I have a user and the user had an EmailVerificationToken.
I would like to delete the EmailVerificationToken when the user gets deleted.
However, since the EmailVerificationToken is an object that is only needed for a short period of time (ie only used once and is irrelevant after), I don't want the User entity to contain the token. Instead, I want the EmailVerificationToken to reference the user it belongs to, but not the other way around.
How do I set it up so when I delete the user, it deletes the EmailToken even though it doesn't reference it in the User entity?
This is the code I have currently:
public class EmailVerificationToken implements IEntity, IDto {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "emailVerificationTokenId")
private Long id;
@OneToOne
@JoinColumn(name = "userId", nullable = false)
private User user;
}
and
public class User implements IEntity, IDto, UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "userId")
private Long id;
}
I am guessing you have a transactional service which handles the deletion of a User.
You need to add a named query in your EmailVerificationToken class. Something like
@NamedQuery(name = EmailVerificationToken.FIND_BY_USER, query = "Select e from EmailVerificationToken e where e.user =:user"), while adding a constant in your class for the name of the query, like:Then you need to define a service which finds a managed instance of your token class with the given User instance.
Then in the transactional method, where you would delete the user, first delete the token;
}
em is an instance of the Entity manager.
Hopefully this helps you. For any further questions, you are free to ask.