有 Java 编程相关的问题?

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

java在Spring Boot中使用生成的ID持久化一个OneToMany实体

我有一个实体,问题,我想将其保存到数据库中。每个问题都由一些答案通过问题ID字段引用

这两个实体都有一个ID字段,该字段在持久化时自动生成。以下是实体的简化代码:

问题。java

@Data
@Entity
public class Question {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    @Size(max=1000, message="Text too long")
    @NotNull(message="Field text cannot be null")
    private String text;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="id", referencedColumnName = "questionId")
    private List<Answer> answers;
}

回答。java

@Data
@Entity
public class Answer {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    @Size(max=255, message="Text too long")
    @NotNull(message="Field text cannot be null")
    private String text;

    @NotNull(message="Field questionId cannot be null")
    private Integer questionId;
}

因此,为了保存一个包含一些答案的问题对象,我创建了那些没有ID字段的对象,它将自动生成。问题对象是从QuestionController中的JSON序列化的:

@RestController
@RequestMapping(value="/questions")
public class QuestionController {
    @Autowired
    private QuestionRepository questionRepository;

    @PostMapping
    public void createQuestion(@RequestBody Question question){
        questionRepository.save(question);
    }
}

问题是,我还必须将questionId字段留空,因为在写入数据库之前我不知道它。这会导致事务抛出一个错误,请求该字段的值

到目前为止,我提出的唯一解决方案是从问题中删除答案,并在问题持续存在后,填写问题ID值并单独保存答案

有什么办法可以立即进行这些交易吗


共 (0) 个答案