How do I delete orphan entities using hibernate and JPA on a many-to-many relationship?

后端 未结 4 1639
猫巷女王i
猫巷女王i 2020-12-30 22:54

I want to delete orphan entities using hibernate and JPA on a many-to-many relationship but all that I found was this attribute the attribute. org.hibernate.annotations.Casc

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-30 23:05

    Actually, I did a test with the following entities:

    @Entity
    public class Person {
        @Id
        @GeneratedValue
        private Long id;
        private String firstName;
        private String lastName;
    
        @ManyToMany
        @Cascade(value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
        private Set roles = new HashSet();
    
        //...
    }
    
    @Entity
    public class Role {
        @Id
        @GeneratedValue
        private Long id;
    
        private String name;
    
        @ManyToMany(mappedBy = "roles")
        private Set persons = new HashSet();
    
        //...
    }
    

    And with the following dataset:

    
        
        
        
        
        
        
        
        
        
        
        
        
        
    
    

    The following test method:

    @Test
    public void testCascadeDeleteOrphanOnDelete() {
        Person person = entityManager.find(Person.class, 1L);
        entityManager.remove(person);
        ReflectionAssert.assertPropertyLenientEquals("id", Arrays.asList(2, 3), findAllPersons());
        ReflectionAssert.assertPropertyLenientEquals("id", Arrays.asList(3, 4), findAllRoles());
    
    }
    
    private List findAllPersons() {
        return entityManager.createQuery("from Person").getResultList();
    }
    
    private List findAllRoles() {
        return entityManager.createQuery("from Role").getResultList();
    }
    

    Just passes. Below the produced output:

    Hibernate: select personx0_.id as id17_0_, personx0_.firstName as firstName17_0_, personx0_.lastName as lastName17_0_ from Person personx0_ where personx0_.id=?
    Hibernate: select roles0_.persons_id as persons1_1_, roles0_.roles_id as roles2_1_, rolex1_.id as id18_0_, rolex1_.name as name18_0_ from Person_Role roles0_ left outer join Role rolex1_ on roles0_.roles_id=rolex1_.id where roles0_.persons_id=?
    Hibernate: delete from Person_Role where persons_id=?
    Hibernate: delete from Role where id=?
    Hibernate: delete from Role where id=?
    Hibernate: delete from Person where id=?
    Hibernate: select personx0_.id as id17_, personx0_.firstName as firstName17_, personx0_.lastName as lastName17_ from Person personx0_
    Hibernate: select rolex0_.id as id18_, rolex0_.name as name18_ from Role rolex0_
    

提交回复
热议问题