How to cascade delete unidirectional

148 Views Asked by At

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;
}
1

There are 1 best solutions below

0
Stefan B. On

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:

public static final String FIND_BY_USER = "EmailVerificationToken.FindByUser"; 

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;

public void deleteUser(User user){
EmailVerificationToken token = someService.findByUser(user); //you get a 
//managed instance using the previously defined query
em.remove(token);
em.remove(user);

}

em is an instance of the Entity manager.

Hopefully this helps you. For any further questions, you are free to ask.