我使用 Spring Roo 作为框架,使用 Hibernate 作为持久性。
在我的应用程序中,用户和角色具有多对多关系。这是User
模型的定义方式:
公共(public)类用户{
/**
*/
@ManyToMany(cascade = CascadeType.ALL)
private Set<Rol> roles = new HashSet<Rol>();
};
没有从角色
到用户
的导航性。
删除用户时,生成的 hibernate 查询如下:
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=?
我遇到异常,我相信原因是最后一行。为什么要删除角色?我怎样才能防止这种情况发生?
最佳答案
只需丢失(cascade = CascadeType.ALL)
即可。
通过在roles
关系上指定cascade = CascadeType.ALL
(根据定义包括CascadeType.REMOVE
),您基本上告诉hiberate您希望在删除用户
时删除roles
,这是不必要的。
您想要的只是当删除用户时,user_roles
中的行(关系行)将被删除,这是由 hibernate 自动完成的,无需指定“CascadeType.REMOVE/ALL”
关于java - Spring Roo 和 Hibernate : how to prevent deletion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23829716/