我创建了以下实体。
@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
. 我没有向该方法中添加transnational,而是从实体本身返回图书列表,而不将其Map到dto。为什么在方法结束后hibernate会话没有关闭?
暂无答案!
目前还没有任何答案,快来回答吧!