当前位置: 首页 > 知识库问答 >
问题:

无联接表的JPA一对多

子车俊哲
2023-03-14

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

方法1

创建从问题到选项的OneToMany关系,如下所示

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

方法2

问题实体

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

选项实体

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

完整问题实体

@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;
    }

}

Option Entity@Entity@Table(Name=“Options”)公共类选项实现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);
    }

共有1个答案

苏硕
2023-03-14

我认为您的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;
}
 类似资料:
  • 我正在处理遗留系统,需要从数据库中读取一些信息。下面是表格关系 供应商(vendorid-pk,vendorEid,name) VendorContactBridge(bridgeid-pk,vendorEid,contactEid) 联系人(contactid-pk,contactEid,phone) vendorEid和contactEid不是表的主键,但用作联接表VendoContactBr

  • 我试图通过使用spring data JPA一对一关联来连接两个表并显示其结果。下面我要添加我的模型和存储库类,我的第一个模型类用户是, 而我需要加入的下一个模型类是: “意外标记:来自第1行附近的第74列[SELECT u.username FROM com.central.model.users u inner join p.privi_name FROM com.central.model.

  • 如何在JPA中使用相同的表执行左外部联接?当我试着这样做的时候: 我得到错误:“意外标记:在第1行附近,第122列[从com.homersoft.wh.db.entity.radius.radacct e1中选择e1在e1.username=e2.username和e1.radacctID ?1]”

  • 问题内容: 我有一个使用联接表建模的一对多关系: 这些表应该模拟一个t1与多个t2的关系。使用JPA为这些表建模的正确方法是什么? 问题答案: 一个T1到多个T2的典型表是在T2上有一个指向T1的外键。通常不需要T1_T2表。 这样,JPA结构将是一对多的,可能是双向的。 可能会有一些安排,以使您描述的结构起作用。您可以更改T1_T2: 在T2上添加唯一约束(以便仅允许一个T2) 那真的是你想要的

  • 我有两个JPA实体(账户和个人),具有双向关系: 当我持久化一个人时,我不想持久化所有帐户,但当我持久一个帐户时,我想更新Person属性hasAccounts,因此我还需要更新这个人。 我做了以下步骤: 创建人员 坚持该人 创建帐户 修改所有者(以前创建的 持久帐户(我希望它会自动合并该人) 我得到了这个例外: (我用JPA 1.0配合Hibernate)。

  • 我是spring框架的初学者, 我在存储库和SQL连接部分面临一些问题。我想使用联接查询从两个表中获取详细信息。 请找到下面的错误 存储库: POJO: 控制器: