我们可以用@Transactional修复LazyInitializationException吗?

问题描述 投票:1回答:1

事务边界划分会影响会话生命周期吗?

我有一些简单的春季启动应用程序:

@Entity
public class Human {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(cascade = { CascadeType.ALL })
    private List<Hobby> hobbies = new ArrayList<>();

    // getters/setters
}


@Entity
public class Hobby {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    // getters/setters
}

还有一些服务来测试它:

@SpringBootApplication
public class SpringbootTransactionsApplication implements CommandLineRunner {

    @Autowired
    private HumanRepo humanRepo;

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTransactionsApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        foo();
    }

    @javax.transaction.Transactional
    public void foo() {
        Human human = new Human();
        human.getHobbies().add(new Hobby());
        humanRepo.save(human);

        for (Human h : humanRepo.findAll()) {
            System.out.println(h.getHobbies());
        }
    }

}

因此,我希望框架能够获取错过的数据(爱好),因为方法foo被标记为Transactional。但是与org.hibernate.LazyInitializationException: failed to lazily initialize a collection失败我是否想念一些东西?

java spring hibernate spring-boot
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.