Search code examples
javaspringhibernatespring-mvcspring-roo

Spring Roo and Hibernate: how to prevent deletion


I am using Spring Roo as framework and Hibernate as persistence.

In my application users and roles have a many to many relation. This is how the User model is defined:

public class User {

/**
 */
@ManyToMany(cascade = CascadeType.ALL)
private Set<Rol> roles = new HashSet<Rol>();

};

There is no navigability from Role to User.

When a user is deleted, here's the hibernate query that's produced:

Hibernate: select user0_.id as id1_5_0_, user0_.password as password2_5_0_, user0_.email as email3_5_0_, user0_.enabled as enabled4_5_0_, user0_.login as login5_5_0_, user0_.name as name6_5_0_, user0_.first_last_name as first7_5_0_, user0_.segundo_last_name as segundo8_5_0_, user0_.version as version9_5_0_ from user user0_ where user0_.id=?
Hibernate: select roles0_.user as user1_5_1_, roles0_.roles as roles2_6_1_, rol1_.id as id1_4_0_, rol1_.name as name2_4_0_, rol1_.version as version3_4_0_ from user_roles roles0_ inner join role rol1_ on roles0_.roles=rol1_.id where roles0_.user=?
Hibernate: delete from user_roles where user=?
Hibernate: delete from role where id=? and version=?

I am getting an exception, and I believe the cause is the last line. Why is it deleting the role? How can I prevent that?


Solution

  • Simply lose the (cascade = CascadeType.ALL).

    By specifying cascade = CascadeType.ALL (which includes by definition CascadeType.REMOVE) on the roles relation you basically tell hiberate you want the roles to be deleted when a user is deleted, which is unnecessary.

    All you want is that the row from user_roles (the relation row) will be removed when user is deleted, and this is done automatically by hibernate without specifying "CascadeType.REMOVE / ALL"