因此主题可以是一个“自引用”实体,即可以有一个可选的父主题和一个可选的子主题集合。
主题可以嵌套到任何级别:TopICA和TopICA1和G.
通过在主题中编写递归函数,我们可以遍历树,并且在层次结构中的任何级别上的主题获得该主题及其所有子主题的问题。
主题:
Entity
@Table(name = "topics")
public class Topic{
@Id
private Long id;
@OneToMany(mappedBy = "parent")
private Set<Topic> subTopics;
@ManyToOne
@JoinColumn(name = "parent_id")
private Topic parent;
@OneToMany(mappedBy = "topic")
private Set<Question> questions;
//questions for this exact topic
public Set<Question> getQuestions(){
return questions;
}
//questions for this topic and all its sub-topics
public Set<Question> getAllQuestions(){
return getAllQuestions(this);
}
//recursive function to walk the topic tree and get all questions for each sub-topic
private Set<Question> getAllQuestions(Topic topic){
Set<Question> questions = new HashSet<>(topic.getQuestions());
for(Topic subTopic : topic.getSubTopics()){
questions.addAll(getAllQuestions(subTopic));
)
return questions;
}
}
问题:
@Entity
@Table(name = "questions")
public class Question {
@ManyToOne
@JoinColumn(name = "topic_id")
private Topic topic;
}
因此,通过对一个主题的引用,我可以得到它的直接问题或者它的所有问题加上它的所有子主题的问题(以及它们的所有子主题…)
Topic topic = topicRepository.findOne(someId);
//only questions directly linked to this topic
Set<Question> questions = topic.getQuestions();
//all questions linked to this topic and its sub-topics to *n* levels.
Set<Question> questions = topic.getAllQuestions();