事务边界划分会影响会话生命周期吗?
我有一些简单的春季启动应用程序:
@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
我错过了什么吗?
答案 0 :(得分:0)
使用@EnableTransactionManagement
启用事务管理
使用@org.springframework.transaction.annotation.Transactional
注释代替@javax.transaction.Transactional
。