我試圖從服務中懶惰地獲取多對多關系(課程 - 學生)并將結果傳遞給控制器??。當我在服務中時LazyInitializationException,由于@Transactional注釋,沒有拋出。但是,當我在 Controller 中時,LazyInitializationException會拋出(在獲取時Course.students),因為 Session 已關閉。我怎樣才能解決這個問題,而不急切地獲取集合?
這是我的代碼:
Couse Model
@Entity
@Getter
@Setter
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@ManyToMany
@JoinTable(name = "COURSES_STUDENTS",
joinColumns = {@JoinColumn(name = "COURSE_ID")},
inverseJoinColumns = {@JoinColumn(name = "STUDENT_ID")})
private Set<Student> students;
public Course() {
this.students = new HashSet<>();
}
學生模型
@Entity
@Getter
@Setter
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@ManyToMany(mappedBy = "students")
private Set<Course> courses;
public Student() {
this.courses = new HashSet<>();
}
}
課程資料庫
@Repository
public interface CourseRepository extends JpaRepository<Course, Long> {
}
課程服務
@Service
public class CourseService {
private final CourseRepository courseRepository;
@Autowired
public CourseService(CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
@Transactional
public ResponseEntity<List<Course>> findAll() {
return this.courseRepository.findAll().isEmpty() ? ResponseEntity.noContent().build()
: ResponseEntity.ok(this.courseRepository.findAll());
}
}
課程控制器
@Controller
@RequestMapping("/")
public class CourseController {
private final CourseService courseService;
@Autowired
public CourseController(CourseService courseService) {
this.courseService = courseService;
}
@GetMapping
public ResponseEntity<List<Course>> index() {
return this.courseService.findAll();
}
}
應用程式屬性
spring.datasource.url=jdbc:h2:~/database;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.jpa.open-in-view=false
spring.mvc.hiddenmethod.filter.enabled=true
logging.level.org.springframework.web=DEBUG
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
提前致謝。
uj5u.com熱心網友回復:
所以有兩種方法:
- Spring Boot 中的這個 spring.jpa.open-in-view=true 屬性是什么?
這對性能不利,必須不惜一切代價避免。
- 使用 jpql 查詢加入 DAO 層所需的 fetch 延遲集合,以便在需要時在控制器中使用它們。
總而言之,不要使用事務性來保持資料庫會話打開以獲取惰性集合。只需加入 db / dao 層中的 fetch lazy collections 即可獲得每個端點所需的資料。
如果您想在這里查看如何使用 join fetch如何在 Spring Controller 中獲取與 JPA 和 Hibernate 的 FetchType.LAZY 關聯
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/449446.html
下一篇:物體持久化是否填充id欄位
