1

I am using Spring Data JPA with Hibernate inside and PostgreSQL and RDBMS. And I created User class and Role class. User can have multiple roles. I want to delete Role which related to deleted User so I used @ManyToMany(cascade = CascadeType.ALL) , but when I delete user1 in DBInit related role has not been deleted and I don't know why. Role class is the owner of relation, so Role as subordinate class should be deleted too as I use @ManyToMany(cascade = CascadeType.ALL). After run() method in DBInit executed I have empty users table and empty users_roles table as I expected, but roles table has still has record. So why is that and to to remove cascade Role when I delete User? The relation is unidirectional, so I don't need to synchronize anything.

Edit: I use @ManyToMany relation so using orphanRemoval=true is not my case. @ManyToMany annotation doesn't even have orphanRemoval parameter.

roles table

id roles
1 User

User.java

@Entity
@Table(name = "users")
@NoArgsConstructor
@AllArgsConstructor
public class User
{
    @Id
    @Getter
    @Setter
    private String email;
    
    @Getter
    @Setter
    @ManyToMany(cascade = CascadeType.ALL)
    private List<Role> roles;
}

Role.java

@Entity
@Table(name = "roles")
@NoArgsConstructor
public class Role
{
    @Id
    @GeneratedValue
    @Getter
    @Setter
    private int id;
    
    @Getter
    @Setter
    String roleName;
    
    public Role(String roleName)
    {
        this.roleName = roleName;
    }
}

UserRepository

@Repository
public interface UserRepository extends JpaRepository<User, String>
{
}

RoleRepository

@Service
public interface RoleRepository extends JpaRepository<Role, Integer>
{
}

DBInit.java

@Service
public class DBInit implements CommandLineRunner
{
    @Autowired
    private UserRepository userRepository;
    
    @Override
    public void run(String[] args)
    {
        List<Role> roles1 = new ArrayList<>();
        roles1.add(new Role("User"));
        User user1 = new User("email1@email.com", roles1);
        
        userRepository.save(user1);
        userRepository.delete(user1);
    }
}

This is my last 3 hibernate queries, so hibernate tried to delete a record from roles, but something goes wrong

Hibernate: 
    delete 
    from
        users_roles 
    where
        user_email=?
Hibernate: 
    delete 
    from
        roles 
    where
        id=?
Hibernate: 
    delete 
    from
        users 
    where
        email=?
Denys_newbie
  • 1,140
  • 5
  • 15

0 Answers0