一对多关系支持读取和删除但不插入

时间:2019-01-24 08:18:46

标签: java hibernate spring-data-jpa

我想扩展earlier post中提到的要求以支持删除。我们有两个数据模型对象-组织和部门共享一对多关系。通过以下映射,我可以从组织对象中读取部门列表。我尚未添加级联ALL属性来限制在创建组织时添加部门。

我应该如何修改@OneToMany批注(可能还有@ManyToOne)以限制部门的插入,但是级联删除操作,以便在删除组织对象时删除所有关联的部门?

@Entity
@Table(name="ORGANIZATIONS")
public class Organization{

    @Id
    @GeneratedValue
    Private long id;

    @Column(unique=true)
    Private String name;

    @OneToMany(mappedBy = "organization", fetch = FetchType.EAGER)
    private List<Department> departments;


}

@Entity
@Table(name="DEPARTMENTS")
Public class Department{

   @Id
   @GeneratedValue
   Private long id;

   @Column(unique=true)
   Private String name;


   @ManyToOne(fetch = FetchType.EAGER)
   private Organization organization;

}

删除组织的代码只是一行

organizationRepository.deleteById(orgId);

验证此情况的测试用例如下

@RunWith(SpringJUnit4ClassRunner.class)
@DataJpaTest
@Transactional
public class OrganizationRepositoryTests {

    @Autowired
    private OrganizationRepository organizationRepository;

    @Autowired
    private DepartmentRepository departmentRepository;



    @Test
    public void testDeleteOrganization() {
        final organization organization = organizationRepository.findByName(organizationName).get(); //precondition

        Department d1 = new Department();
        d1.setName("d1");

        d1.setorganization(organization);

        Department d2 = new Department();
        d2.setName("d2");

        d2.setorganization(organization);

        departmentRepository.save(d1);
        departmentRepository.save(d2);

//        assertEquals(2, organizationRepository.getOne(organization.getId()).getDepartments().size()); //this assert is failing. For some reason organizations does not have a list of departments

        organizationRepository.deleteById(organization.getId());

        assertFalse(organizationRepository.findByName(organizationName).isPresent());
        assertEquals(0, departmentRepository.findAll().size()); //no departments should be found

    }

}

3 个答案:

答案 0 :(得分:1)

查看有关失败原因的代码注释:

@RunWith(SpringJUnit4ClassRunner.class)
@DataJpaTest
@Transactional
public class OrganizationRepositoryTests {

    @Autowired
    private OrganizationRepository organizationRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @PersistenceContext
    private Entitymanager em;

    @Test
    public void testDeleteOrganization() {
        Organization organization = 
                organizationRepository.findByName(organizationName).get(); 

        Department d1 = new Department();
        d1.setName("d1");
        d1.setOrganization(organization);

        Department d2 = new Department();
        d2.setName("d2");
        d2.setOrganization(organization);

        departmentRepository.save(d1);
        departmentRepository.save(d2);

        // this fails because there is no trip to the database as Organization 
        // (the one loaded in the first line)
        // already exists in the current entityManager - and you have not 
        // updated its list of departments.
        // uncommenting the following line will trigger a reload and prove 
        // this to be the case: however it is not a fix for the issue.

        // em.clear();

         assertEquals(2,
             organizationRepository.getOne(
               organization.getId()).getDepartments().size()); 

        //similary this will execute without error with the em.clear() 
        //statement uncommented
        //however without that Hibernate knows nothing about the cascacding 
        //delete as there are no departments
        //associated with organisation as you have not added them to the list.
        organizationRepository.deleteById(organization.getId());

        assertFalse(organizationRepository.findByName(organizationName).isPresent());
        assertEquals(0, departmentRepository.findAll().size()); 
    }
}

正确的解决方法是封装封装的添加/删除/设置操作并防止出现以下情况,从而确保正确维护内存模型: 直接访问收藏集。 例如

public class Department(){
    public void setOrganisation(Organisation organisation){
        this.organisation = organisation;

        if(! organisation.getDepartments().contains(department)){
            organisation.addDepartment(department);
        }
    }
}

public class Organisation(){

    public List<Department> getDepartments(){
        return Collections.unmodifiableList(departments);
    }

    public void addDepartment(Department departmenmt){
        departments.add(department);

        if(department.getOrganisation() != this){
            department.setOrganisation(this);
        }
    }
}

答案 1 :(得分:0)

您可以尝试添加以限制级联,以仅从组织到部门删除操作:

@OneToMany(mappedBy = "organization", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<Department> departments;

请注意,如果部门部门具有从属/外键约束,则还需要将删除操作也级联到这些从属实体。

您可以阅读本指南,它很好地说明了级联操作: https://vladmihalcea.com/a-beginners-guide-to-jpa-and-hibernate-cascade-types/

答案 2 :(得分:0)

尝试此代码,

    @OneToMany( fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "organisation_id", referencedColumnName = "id")
    private List<Department> departments;

    @ManyToOne(fetch = FetchType.EAGER,ascade = CascadeType.REFRESH,mappedBy = "departments")
    private Organization organization;

如有任何问题,请告知