Spring Data Repository does not delete ManyToOne Entity

前端 未结 6 676
陌清茗
陌清茗 2021-01-30 13:39

I\'m am currently trying to use a Spring Data repository to delete some of my entities. The delete call works without any exceptions/error messages, but the entity is not delete

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 14:07

    What @user2936091 said is true but it doesn't solve the problem. I also had the exact same problem like you.

    The solution is to remove fetch=FetchType.EAGER from the parent class. Wen fetch type EAGER is used, the instance of board in the post object will have the

     private List posts = new ArrayList();
    

    populated because it was eagerly loaded, which means it still has a reference to itself, like @user2936091 mentions.

    My workaround to still load related properties eagerly was to create a DBService class and load the objects from there like this

    @Service
    public class DBService {
    
        BoardRepository boardRepo;
    
        @Transactional
        public Board getBoardProcess(Long id) {
           Board board = boardRepo.findById(id).get();
           board.getPosts().size(); // This will trigger the db query so that posts gets loaded
           // It needs to be done within a transactional so that the session is still the same to populate the fields. If it's done from outside of this method. It will not work
        }
    }
    

提交回复
热议问题