休眠无法删除对象

时间:2019-01-23 15:10:47

标签: hibernate spring-boot spring-data-jpa

我有2个实体Company和Menu 公司有很多菜单。

公司实体:

public class Company {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL,mappedBy = "company")
    private Set<Menu> menus;

    //other fields getters and setters

菜单实体:

public class Menu {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "company_id", nullable = false)
    private Company company;

//other fields getters and setters

当我删除公司时,它可以正常工作,通过菜单删除公司,但是我不能直接删除菜单:Api不会返回错误,但不会从数据库中删除记录。

服务:

    public boolean deleteMenu(long id) throws ResourceNotFoundException {
        try{
            menuRepository.deleteMenuById(id);
            return true;
        }catch (Exception e){
            throw e;
        }
    }

MenuRepository:

public interface MenuRepository extends CrudRepository<Menu, Long> {
    public Menu findMenuById(Long id);
    public void deleteMenuById(long id);
}

编辑

我猜问题是在这种情况下事务会回滚更改,所以我警告了这个错误: 事务默默回滚,因为它已被标记为仅回滚

1 个答案:

答案 0 :(得分:0)

我认为您delete方法上的throws语句使您无法捕获实际引发的异常。throws ResourceNotFoundException对您没有帮助。

第二,将您的层叠更改为cascade = CascadeType.REMOVE

相关问题