JPA一对多没有联接表

时间:2018-05-21 16:20:56

标签: hibernate jpa orm spring-data-jpa hibernate-mapping

我正在尝试为quiz数据库创建JPA实体类,其中我有两个实体问题和选项。

方法1

从问题到选项的创建和OneToMany关系,如此

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Option> options = new HashSet<>();

和ManyToOne关系从这个选项实体创建

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

它工作正常,除了它创建了一个额外的表question_options和问题 - 选项关系在该表中管理。此外,Option有questionId列,所有记录都为null。

我想避免那个额外的表,并希望在选项表中填充questionid.So经过一点点谷歌搜索后,我才知道我需要使用mappedBy属性。

方法2

问题实体

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy="question")
private Set<Option> options = new HashSet<>();

选项实体

@ManyToOne(fetch = FetchType.LAZY)
private Question question;

现在不创建连接表,而是将question_questionId列添加到Options表中,但同样将其作为null。因此,我的端点没有返回带有问题的选项。

我希望我的问题很明确。如何在选项表中填充questionId。

  

编辑

完整问题实体

@Entity
@Table(name="questions")
public class Question implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int questionId;

    private String author;

    private boolean expired;

    private String questionText;

    //bi-directional many-to-one association to Option
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy="question")
    private Set<Option> options = new HashSet<>();

    public Question() {
    }

    public int getQuestionId() {
        return this.questionId;
    }

    public void setQuestionId(int questionId) {
        this.questionId = questionId;
    }

    public String getAuthor() {
        return this.author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public boolean isExpired() {
        return expired;
    }

    public void setExpired(boolean expired) {
        this.expired = expired;
    }

    public String getQuestionText() {
        return this.questionText;
    }

    public void setQuestionText(String questionText) {
        this.questionText = questionText;
    }

    public Set<Option> getOptions() {
        return this.options;
    }

    public void setOptions(Set<Option> options) {
        this.options = options;
    }

    public Option addOption(Option option) {
        getOptions().add(option);
        option.setQuestion(this);

        return option;
    }

    public Option removeOption(Option option) {
        getOptions().remove(option);
        option.setQuestion(null);

        return option;
    }

}

选项实体     @实体     @table(名称= “选项”。)     public class Option实现Serializable {     private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int optionId;

private boolean correctAnswer;

private String optionText;

//bi-directional many-to-one association to Question
@ManyToOne(fetch = FetchType.LAZY)
private Question question;

public Option() {
}

public int getOptionId() {
    return this.optionId;
}

public void setOptionId(int optionId) {
    this.optionId = optionId;
}

public boolean isCorrectAnswer() {
    return correctAnswer;
}

public void setCorrectAnswer(boolean correctAnswer) {
    this.correctAnswer = correctAnswer;
}

public String getOptionText() {
    return this.optionText;
}

public void setOptionText(String optionText) {
    this.optionText = optionText;
}

public Question getQuestion() {
    return this.question;
}

public void setQuestion(Question question) {
    this.question = question;
}

}

  

存储库

@Repository
public interface QuestionRepository extends CrudRepository<Question,Long>{

}
  

服务类

@Autowired
    private QuestionRepository questionRepository;
    public Question getQuestion(Long id) {
        Question  question= questionRepository.findOne(id);
        Set<Option> options = question.getOptions();
        options.forEach(s -> s.setCorrectAnswer(false));
        return question;
    }

    public Question addQuestion(Question question) {
        return questionRepository.save(question);
    }
  

控制器

@GetMapping
    @RequestMapping(method = RequestMethod.GET, value="/questions/{id}")
    public ResponseEntity<Question> getQuestion(@PathVariable long id) {
        return new ResponseEntity<Question>(questionService.getQuestion(id),HttpStatus.OK);
    }

    @PostMapping
    @RequestMapping(method = RequestMethod.POST, value= "/questions")
    @Transactional
    public ResponseEntity<Question> addQuestion(@RequestBody Question question) {
        logger.info("Request recieved from client : " + question.toString());
        return new ResponseEntity<Question>(questionService.addQuestion(question),HttpStatus.OK);
    }

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您的addQuestion方法应如下所示:

public Question addQuestion(Question question) {
   Question newQuestion = questionRepository.save(question);
   question.getQuestions().forEach(option -> {
      Option newOption = new Option();
      newOption.setQuestion(newQuestion); // need to reference managed (attached to JPA session) entity
      newOption.setOptionText(option.getOptionText());
      newOption.setCorrectAnswer(Optional.ofNullable(option.isCorrectAnswer()).orElse(false)));
      newQuestion.getOptions().add(optionRepository.save(newOption));
   });

   // it's done implicitly here because your controller's (or service's) method 
   // is marked with @Transactional, otherwise it must be done explicitly
   // newQuestion = questionRepository.save(newQuestion);

   return newQuestion;
}