Hibernate could not initialize proxy - no Session

后端 未结 3 1671
小鲜肉
小鲜肉 2021-02-13 13:14

My code retrieves all information related to the user:

SessionFactory sessionFactory = HibernateUtilities.configureSessionFactory();
Session session = sessionFac         


        
3条回答
  •  爱一瞬间的悲伤
    2021-02-13 13:28

    I faced the same issue in JPA/Hibernate, and there are 2 ways to solve this issue:

    1/ Turn off the LAZY by default, as following:

    @Entity
    @Proxy(lazy = false)
    public class Project {
    ...
    }  
    

    Of course, this way is not recommended because of the performance issue, so you can go to the second way.

    2/ You can put @Transactional at the beginning of your method, it can help you to remain the session, or another understanding, it pass the duty of session to Hibernate, as following:

    @Test
    @Transactional
    public void testSaveGroup() {
        Department g = new Department();
        g.setName("XDG");
        assertNull(g.getId());
        this.groupRepo.save(g);
        assertNotNull(g.getId());
        System.out.println(g.getId());
        Project dummyPrj = new Project(123L, "KSTA", new Date(), "NEW", "Helm AG", g);
        this.projectRepo.save(dummyPrj);
        // verify
        List lst = this.groupRepo.findAll();
        Project savedPrj = this.projectRepo.getOne(123L);
        Assert.assertEquals("XDG", savedPrj.getGroup().getName());
    }
    

    My answer is late, but hope to help someone else :)

提交回复
热议问题