Hibernate:已删除的对象将通过级联重新保存

时间:2013-07-27 05:22:44

标签: java spring hibernate spring-mvc

定义:

@OneToMany(mappedBy = "product", fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, orphanRemoval = true)
@Where(clause = "ownerType=22")
private List<AirlineSupplierProductFile> files = new ArrayList<AirlineSupplierProductFile>(0);

代码:

@RequestMapping(value = "/remove-product-file", method = RequestMethod.GET, headers = BaseController.AJAX_HEADER)
public @ResponseBody JSONResponse removeProductFile(@RequestParam(value = "id", required = true) Long id,
        @RequestParam(value = "product", required = true) Long productId,
        @CurrentUser UserDetailsExtended currentUser) {
    JSONResponse json = new JSONResponse();

    try {
        AirlineSupplierProductFile file = (AirlineSupplierProductFile) fileStorageService.get2(id, OwnerType.AirlinesSupplierProduct);
        if (file.getProduct() == null || file.getProduct().getId() == productId)
            fileStorageService.delete(file);
    }
    catch (Exception e) {
        json.setData(I18n.getString("errors.common.unexepected"));
        json.setCode(AjaxError.Undefined);

        log(e, currentUser.getUsername());
    }

    return json;
}

其中fileStorageService.delete(file)是:

@Transactional
public void delete(IFileStorageFile object) {
    Session session = SessionFactoryUtils.getSession(sessionFactory, false);

    session.delete(object);
}

问题:deleted object would be re-saved by cascade失败。

问题:为什么?

谢谢

1 个答案:

答案 0 :(得分:0)

从其拥有产品的airlineSupplierProductFiles列表中删除AirlineSupplierProductFile:

AirlineSupplierProductFile file = (AirlineSupplierProductFile) fileStorageService.get2(id, OwnerType.AirlinesSupplierProduct);

if (file.getProduct() == null || file.getProduct().getId() == productId) {
    if (file.getProduct() != null) {
        file.getProduct().removeAirlineSupplierProductFile(file);
    } 
    fileStorageService.delete(file);
}
相关问题