首页 > 解决方案 > 删除父项时禁用删除子记录条目

问题描述

我有User类,它具有由数据库中的 SQL 视图表示的角色集合(只读)。因此,用户可以拥有一组角色,这些角色是在外部提供的,并且不能被用户的对象更改。我必须忍受这一点,不能改变设计。

问题是:用户的对象被删除时,Hibernate 会尝试从封闭的表中删除用户的 ID,并且无法从角色的视图中删除用户 ID。

问题:有什么方法可以防止 Hibernate 从封闭表中删除用户的 id(即从用户的 角色视图中)?

目前,应用程序在删除用户时出现严重错误,因为 v_user_roles 是只读的,所以 DB 拒绝 Hibernate 尝试从中删除任何记录。

从日志:

delete from mapp.user_locations where user_id=?  OK
delete from mapp.user_adresses where user_id=?  OK
delete from mapp.v_user_roles where user_id=? FAIL, I want to avoid this

PS尝试“不可变”,CascadeType.PERSIST,“nullable = false,inserable = false,updatable = false”,禁用setter - 没有成功。

用户实体:

@Table(name = "users", schema = "PROD")
public class User extends EntityWithIdAbst implements UserDetails {

    @Column(name = "USERNAME", nullable = false)
    private String username;

    @JsonIgnore
    @Column(name = "USERPASS", nullable = false)
    private String password;

    @Immutable
    @ManyToMany(cascade = { CascadeType.PERSIST}, fetch = FetchType.EAGER)
    @JoinTable(name = "v_user_roles", schema = "PROD",
            joinColumns = @JoinColumn(name = "user_id", nullable = false, insertable = false, updatable = false) ,
            inverseJoinColumns = @JoinColumn(name = "cur_role_id", nullable = false, insertable = false, updatable = false)
    ) @Getter
    private Set<Role> rolesInherited;

Controller: 它只是通过 Service for User 对象调用 PagingAndSortingRepository 的 deleteById(id) 方法

@ResponseBody
@DeleteMapping(value = "/delete/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<HttpResponseWithStatus> delete (E entity) {
    HttpResponseWithStatus resp = new HttpResponseWithStatus().setHttpStatus(HttpStatus.BAD_REQUEST);
    try {
        aService.deleteById(entity.getId());
...

服务:

@Service
public class UserServiceImpl extends PagingAndSortingRepository implements UserService {
...
    public void deleteById(Long id) {
        rep.deleteById(id);
    }
***

标签: javahibernatejpa

解决方案


问题是:当用户的对象被删除时

你能展示你使用的代码吗?这不是很具体。也许您entityManager.remove在某些使用删除级联或孤立删除的对象上使用。如果您使用删除查询,这也可能是一个错误。在这种情况下,我建议您尝试使用例如https://github.com/hibernate/hibernate-test-case-templates重现问题并将其发布到问题跟踪器:http: //hibernate.atlassian.net/


推荐阅读