OneToMany未加载到二级实体中

时间:2016-03-05 20:59:33

标签: java spring mongodb spring-data lazy-loading

我使用的是spring-data-mongodb 1.8.2(spring-boot-starter 1.3.1),我手边有一个相当容易的案例(我在绝望中添加了fetch):

@Document(collection = "class_room")
public class ClassRoom implements Serializable {

@Id
private String id;

@NotNull
@Field("name")
private String name;

@ManyToOne**(fetch = FetchType.EAGER)**
@JoinColumn(name = "school_id")
private School school;
[...]
}

@Document(collection = "school")
public class School implements Serializable {

@Id
private String id;

@NotNull
@Field("name")
private String name;

@OneToMany(mappedBy = "school"**, fetch = FetchType.EAGER**)
private Set<Article> articles = new HashSet<>();
[...]
}

存储库:     public interface SchoolRepository扩展了MongoRepository {

}

public interface ClassRoomRepository extends MongoRepository<ClassRoom,String> {

 }

资源:

    @RequestMapping(value = "/schools",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<School> getAllSchools() {
    return schoolRepository.findAll();
        }

    @RequestMapping(value = "/classRooms",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<ClassRoom> getAllClassRooms() {
    return classRoomRepository.findAll();
        }

现在,当我执行“schoolRepository.findAll()&#39;”时,有人可以向我解释为什么文章被正确加载了。 但是当我执行&#39; classRoomRepository.findAll()&#39;?

我怎样才能实现呢?

TL; DR 学校有一套文章 classRoom有一所学校。 当我直接进入学校时:我看到了一套文章 通过classRoom访问学校时,文章集为空。

1 个答案:

答案 0 :(得分:0)

您使用对象关联的方法有点过时了。在使用Mongo的Spring Data中,定义注释以描述关联如何发生的概念不是标准方法。

如果您在此处查看文档http://docs.spring.io/spring-data/data-mongo/docs/1.4.2.RELEASE/reference/html/mapping-chapter.html,则有助于提高清晰度。

但是要强调,Mongo使用嵌入对象的概念,理想情况下,您的数据结构可能类似于:

@Document(collection = "class_room")
public class ClassRoom implements Serializable {

@Id
private String id;
private String name;

private School school;
// Where School has the following fields and structure:
// private String id;
// private String name;
// private Set<Article> articles = new HashSet<>()
}

如果您希望将学校嵌入到ClassRoom中,您可以将其保留在上面,否则您可以将School作为其自己的单独集合。所以:

@Document(collection = "school")
public class School implements Serializable {

@Id
private String id;

private String name;

private Set<Article> articles = new HashSet<>();
[...]
}

在上面的学校中,它是一个自己的集合,并没有嵌入ClassRoom。

通常,在处理Mongo或NoSQL / Graph数据库时,您必须与传统的ORM方法有所不同。

相关问题