栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring JPA创建问题

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring JPA创建问题

因此,主题可以是“自引用”实体,即可以具有可选的父主题和可选的子主题集合。

主题可以嵌套到任何级别:TopicA> TopicA_1> Topic_A_1_1等。

通过在Topic中编写一个递归函数,我们可以走到树上,并在层次结构中任何级别的Topic上获取该主题及其所有子主题的问题。

话题:

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 topicSet<Question> questions = topic.getQuestions();//all questions linked to this topic and its sub-topics to *n* levels.Set<Question> questions = topic.getAllQuestions();


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/412149.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号