有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在hibernate中有多级结构吗

如果我要问有子问题的问题,并且所有问题和子问题都有各自的答案,那么如何设计bean的以下结构。结构就像

Structure

如何在hibernate中设计此结构以实现spring boot中的功能


共 (1) 个答案

  1. # 1 楼答案

    如果我们考虑到这是3个不同的表,我会认为是Question的实体

    @Entity
    @Table("question")
    public class Question
    

    然后是SubQuestion的实体

    @Entity
    @Table("sub_question")
    public class SubQuestion
    

    ManyToOne联合

      @ManyToOne(fetch=FetchType.LAZY)
      @JoinColumn(name="QUESTION_ID")
      private Question question;
    

    最后是一个泛型类GenericAnswer

    @Entity
    @Table(name = "answer")
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name = "question", discriminatorType = DiscriminatorType.STRING)
    public class GenericAnswer {
    

    它将扩展为两个类:QuestionAnswerSubQuestionAnswer

    这两个类有一个鉴别器列来区分它们所引用的表(问题或子问题)

    @DiscriminatorValue("question")
    @Entity
    public class QuestionAnswer extends GenericAnswer {
    
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="QUESTION_ID")
    private Question question;
    

    @DiscriminatorValue("sub_question")
    @Entity
    public class SubQuestionAnswer extends GenericAnswer {
    
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="QUESTION_ID")
    private SubQuestion subQuestion;
    

    希望这对你有帮助