Hibernate - 使用Annotations自动删除父级时删除子级

时间:2015-05-19 21:04:59

标签: java sql hibernate one-to-many hibernate-mapping

我有2个实体,GroupUser个,意为parent个实体:

@Entity
@Table(name = "groups")
public class Group implements Serializable{
//Some other content

@OneToMany(fetch = FetchType.LAZY, mappedBy = "group", 
    cascade = CascadeType.ALL, orphanRemoval = true)
private List<User> users;
}

子实体User,其中Group为父级:

@Entity
@Table(name = "users")
public class User implements Serializable{
//other content

@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Group group;

这个想法是删除Group时,也应该删除所有相关的User。我用内存数据库创建了一个单元测试,显示了我的意思:

@Test
public void test_WhenGroupIsRemoved_RelatedUsersAlsoShouldBeRemoved() throws Exception{
    service.save(new GroupDTO(null, "Group", (long)47));
    List<GroupDTO> groups = service.getAll();
    assertEquals(1, groups.size());

    GroupDTO groupDTO = groups.get(0);
    userService.save(new UserDTO(null, "testName", "testSurname", "testEmail", "333", groupDTO));
    userService.save(new UserDTO(null, "testName2", "testSurname2", "testEmail2", "333-2", groupDTO));
    service.delete(groupDTO);

    List<GroupDTO> emptyGroups = service.getAll();
    assertEquals(0, emptyGroups.size());
    List<UserDTO> emptyUsers = userService.getAll(new UserFilterParameters());
    assertEquals(0, emptyUsers.size());
}

但我无法使用Group删除User,因为我得到java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: foreign key no action; FK_FM4CFGDT24TOH89YW4RBNU1LB table: USERS。 来自控制台的SQL代码:

Hibernate: insert into groups (id, name) values (default, ?)
Hibernate: select this_.id as id1_0_0_, this_.name as name2_0_0_ from groups this_
Hibernate: insert into users (id, email, group_id, name, phone, surname) values (default, ?, ?, ?, ?, ?)
Hibernate: insert into users (id, email, group_id, name, phone, surname) values (default, ?, ?, ?, ?, ?)
Hibernate: delete from groups where id=?

Hibernate: delete from groups where id=?之前我认为User应该被移除,我认为可以自动完成 - 使用适当的Annotation,但我无法弄明白。如果我从mappedBy = "group"方删除@OneToMany并添加@JoinColumnGroups实体)并将@JoinColumn(insertable = false, updatable = false)添加到@ManyToOne方(User实体)正如我在类似问题中发现的那样,我看到一些奇怪的ERROR: integrity constraint violation: NOT NULL check constraint; SYS_CT_10101 table: USERS column: GROUP_ID。 如果有人决定帮助我,我会很高兴 - 提前谢谢你! 更新服务:

@Service
public class GroupServiceImpl implements GroupService {
@Autowired
private GroupDAO groupDAO;
@Autowired
private GroupTransformer groupTransformer;

@Override
@Transactional
public void delete(GroupDTO groupDTO) {
    groupDAO.delete(groupTransformer.dtoToEntity(groupDTO));
}

而且有一个错误:在groupTransformer转换很简单,return new Group(...)。但它应该是:

@Override
public Group dtoToEntity(GroupDTO groupDTO) {
    return groupDTO.getId() != null? dao.getById(groupDTO.getId()) : new Group(groupDTO.getId(), groupDTO.getName());
}
当DTO具有Id(这意味着它存在于数据库中)时,应该使用DAO来获取Group。感谢用户@JB Nizet

0 个答案:

没有答案