休眠会话何时关闭



我创建了以下实体。

@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "student")
private List<Book> books;
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "STUDENT_ID")
private Student student;
}

我的控制器看起来像这样

@RestController
public class Controller {
MyService myService;
public Controller(MyService myService) {
this.myService = myService;
}
@GetMapping("student")
public List<Book> getBooksForStudent(Long id) {
return myService.getBooks(id);
}
}

服务如下。

public class MyService {
@Autowired
private StudentRepo studentRepo;
public List<Book> getStudent(Long id) {
Optional<Student> studentOptional = studentRepo.findById(id);
return studentOptional.map(Student::getBooks).orElseThrow(IllegalArgumentException::new);
}
}

我按预期获得了书籍清单。但是由于我的书籍加载列表很懒惰,我应该得到一个LazyInitializationException.我没有将跨国添加到该方法中,并且我从实体本身返回书籍列表,而不将其映射到 DTO。为什么休眠会话在方法结束后没有关闭?

默认情况下@RestController是事务性的。Spring 引导会在您使用 Web 应用程序/使用 JPA 时自动注册OpenEntityManagerInViewInterceptor。参考@RestController方法似乎默认是事务性的,为什么?

最新更新