休眠会话何时关闭

时间:2020-06-08 15:26:27

标签: spring-boot hibernate spring-data-jpa lazy-initialization

我创建了以下实体。

@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。为什么在方法结束后休眠会话没有关闭?

0 个答案:

没有答案
相关问题