Disable deleting child records entries when deleting parent

Viewed 475

I have User class, which has collection of Roles represented by SQL view in database (read only). So, User can has a collection of Roles, which are supplied outside and cannot be changed by User's object. I have to live with that and can't change the design.

The issue is: When User's object is being deleted, Hibernate tries to also remove User's ID from enclosing tables and fails on removing user Id from Role's view.

The question: Is there any way to prevent Hibernate from removing User's id from enclosing tables (i.e. from User's Roles view)?

For now the application just falls with critical error when deleting User, because v_user_roles is read only, so DB refuses Hibernate's try to delete any records from it.

From the log:

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

P.S. Tried "Immutable", CascadeType.PERSIST, "nullable = false, insertable = false, updatable = false", disabling setters - without success.

User's entity:

@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: It simply calls PagingAndSortingRepository's deleteById(id) method via Service for User object

@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:

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

The issue is: When User's object are being deleted

Can you show the code that you use? This is not very specific. Maybe you use entityManager.remove on some object that uses delete cascading or orphan removal. If you use a delete query, this could also be a bug. In that case I'd recommend you try to reproduce the issue with e.g. https://github.com/hibernate/hibernate-test-case-templates and post it to the issue tracker: http://hibernate.atlassian.net/

Related