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

时间:2017-12-18 23:05:24

标签: java spring hibernate spring-boot

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

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

@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我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

使用@EnableTransactionManagement启用事务管理 使用@org.springframework.transaction.annotation.Transactional注释代替@javax.transaction.Transactional