删除的对象将通过级联问题重新保存

时间:2014-10-26 09:59:33

标签: java spring hibernate

我知道 stackoverflow 上几乎没有类似的问题,但不幸的是它没有帮助我,所以我创建了自己的。 在我的项目中,我有两个实体ShopTypeShop与EAGER初始化。 TypeShop可能有几家商店。

@Entity
@Table(name = "shop_types")
public class TypeShop {
    ...
    @OneToMany(fetch = FetchType.EAGER, mappedBy="typeShop", cascade = CascadeType.ALL)
    private Set<Shop> shops;
    ...
}

@Entity
@Table(name = "shops")
public class Shop {
    ...
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "shop_type_id")
    private TypeShop typeShop;
    ...
}

这是控制器的代码:

@RequestMapping(value = "/admin/delete/{id}", method = RequestMethod.GET)
public String deleteShop(@PathVariable("id") Integer id) {
    try {
        shopDAO.delete(id);
    } catch (Exception e ) {          
        return "404";
    }
    return "redirect:/admin";
}

尝试删除shop对象,我得到org.springframework.dao.InvalidDataAccessApiUsageException: deleted object would be re-saved by cascade (remove deleted object from associations)

所以在那之后我修改了我的代码并在删除shop之前将其从父Set collection中删除。 现在它看起来像这样:

@RequestMapping(value = "/admin/delete/{id}", method = RequestMethod.GET)
public String deleteShop(@PathVariable("id") Integer id) {
    try {
        Shop shop = shopDAO.findById(id);
        TypeShop type = shop.getTypeShop();
        type.getShops().remove(shop);
        typeShopDAO.update(type);
        shopDAO.delete(id);
    } catch (Exception e ) { 
        return "404";
    }
    return "redirect:/admin";
}

但不幸的是,我又得到了同样的例外。请帮我解决一下。提前谢谢!

1 个答案:

答案 0 :(得分:0)

尝试传递shop对象而不是shop id并将代码移动到ShopService类,它应该在一个事务中。

@Transactional    
public void deleteShop(Integer id){
            Shop shop = shopDAO.findById(id);
            TypeShop type = shop.getTypeShop();
            type.getShops().remove(shop);
            typeShopDAO.update(type);
            shopDAO.delete(shop);
    }