Spring JPA与其他表一起引用一个表

时间:2019-02-21 10:59:15

标签: java spring hibernate jpa

我正在使用JPA在Spring中创建一个问答游戏,并且已经创建了一个用户,现在我正在创建问题和答案,问题是问题必须至少包含一个答案,因为它可以包含两个正确答案,我的疑问是如何创建表格来做到这一点?

这是我的Question类

@Entity(name = "question")
public class Question extends DateAudit {
    @Id
    @Column(name = "question_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "question_seq")
    @SequenceGenerator(name = "question_seq", allocationSize = 1)
    private Long id;

    @Column(name = "name")
    @NotBlank(message = "Question name can not be blank")
    private String name;

    @Column(name = "is_exam_question", nullable = false)
    private Boolean is_exam_question;

    @ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    private Set<Answer> answers = new HashSet<>();

}

我在这里缺少什么,因为我想知道哪个用户回答了该问题以及他成功了多少次。

我的Answer类也是

@Entity(name = "answer")
public class Answer {

    @Id
    @Column(name = "answer_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "answer_seq")
    @SequenceGenerator(name = "answer_seq", allocationSize = 1)
    private Long id;

    @Column(name = "answer_to_question")
    @NotBlank(message = "Answer to question name can not be blank")
    private String answer_to_question;

    @ManyToOne
    private Question question;
}

解释得更好

如何为问题添加多个答案以及如何将这个答案分配给问题?

1 个答案:

答案 0 :(得分:1)

创建一个新的类名称为Quiz.class

@Entity
public class Quiz{

@Id
private int id;

private String quizName;

private String quizDescription;

private int passingScore;

private int totalScore;

// Getter and setters
}

Question.class看起来像这样

@Entity(name = "question")
public class Question extends DateAudit {
    @Id
    @Column(name = "question_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "question_seq")
    @SequenceGenerator(name = "question_seq", allocationSize = 1)
    private Long id;

    @Column(name = "name")
    @NotBlank(message = "Question name can not be blank")
    private String name;

    @Column(name = "is_exam_question", nullable = false)
    private Boolean is_exam_question;

    @OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE },mappedBy="question")
    private Set<Answer> answers = new HashSet<>();

    @ManyToOne
    private Quiz quiz;

}

Tests.class看起来像这样

@Entity
public class Tests{

private int id;

@ManyToOne
private Quiz quiz;

@ManyToOne
private User user;

private int score;

private String status; // failed or passed

}

我认为这会对您有所帮助。随时问我更多问题。