[英]How to fix LazyInitializationException with @Transactional?
事务边界划分会影响会话生存期吗?
我有一些简单的 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 被标记为事务性。 但是失败了org.hibernate.LazyInitializationException: failed to lazily initialize a collection
我错过了什么吗?
使用@EnableTransactionManagement
和使用@org.springframework.transaction.annotation.Transactional
注释而不是@javax.transaction.Transactional
启用事务管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.