问题描述
如何正确显示延迟加载许多字段,以便用户可以GET
/PATCH
/POST
/DELETE
许多Spring Data REST中有很多实体关系?
How do I correctly expose lazy-loaded many-many fields so that users can GET
/PATCH
/POST
/DELETE
many-many entity relationships in Spring Data REST?
例如,给定Student
实体和Teacher
实体之间存在多对多关系,并具有以下POJO:
For example, given a Student
entity and Teacher
entity bound by a many to many relationship, with the following POJOs:
@Entity
public class Teacher { // owner of bidirectional relationship
@Id
private int id;
private String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "teacher_student",
joinColumns = @JoinColumn(name = "teacher_id"),
inverseJoinColumns = @JoinColumn(name = "student_id"))
private Set<Student> students;
// Constructor, getters/setters...
}
@Entity
public class Student {
@Id
private int id;
private String name;
@ManyToMany(mappedBy = "students", fetch = FetchType.LAZY)
private Set<Teacher> teachers;
// Constructor, getters/setters...
}
为实体提供存储库:
@RepositoryRestResource(path = "teacher")
public interface TeacherRepository extends CrudRepository<Teacher, int> {}
// similar repository for student
当我将GET
发送到localhost:8080/teacher时,我得到了:
When I send a GET
to localhost:8080/teacher, I get:
"_embedded": {
"teacher": [
{
"name": "Bill Billie",
"_links": {
"self": { "href": "http://localhost:8080/teacher/1" },
"teacher": { ... },
"students": { "href": "http://localhost:8080/teacher/1/students" }
}},
(more teachers here...)
]
}
...
但,当我尝试GET
来 http://localhost :8080/teacher/1/学生,尽管老师"Bill Billie" 确实有一个与他相关的学生,但我还是得到 404未找到数据库.
BUT, when I try a GET
to http://localhost:8080/teacher/1/students, I get a 404 Not Found, even though the teacher "Bill Billie" does have a student associated with him in the database.
有趣的是,如果将FetchType
更改为FetchType.EAGER
,一切正常,我可以执行预期的GET
,PATCH
等.这有什么用?也许是一个错误,还是我搞砸了?
Interestingly, if I change the FetchType
to FetchType.EAGER
, everything works fine and I can perform the expected GET
, PATCH
, etc. What gives? Is this a bug, perhaps, or am I screwing something up?
tl; dr延迟获取无法正确显示很多关系,但是渴望获取可以很好地工作.我该如何懒惰地抓取它?
编辑:如果有关系,我将使用Spring 4.2.6和Spring Boot 1.3.5,并使用OpenJPA 2.4.1作为我的JPA提供程序.
Edit: If it matters, I am using Spring 4.2.6 with Spring Boot 1.3.5, and OpenJPA 2.4.1 as my JPA provider.
推荐答案
尝试使RestResources具有事务性.
Try making your RestResources transactional.
用@Transactional
这篇关于提取和在Spring Data REST中更新延迟加载的许多字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!