在Spring JPA中添加来自主实体的实体
我正在尝试进行 ORM 并从父实体(Batch)添加到子实体(Candidate),
我建立了如下关系:
Batch Class:
@OneToMany(mappedBy = "batch", cascade = CascadeType.ALL)
private List<Candidate> candidates;
Candidate Class:
@ManyToOne
@JoinColumn(name = "BatchID")
private Batch batch;
我尝试使用来自 BatchRepository 和 CandidateRepository 的 JPA 存储
库我尝试通过父实体添加它,但它不起作用:
public void addCandidateToBatch(int batchId, int candidateId) {
Batch batch = batchRepository.findById(batchId).get();
Candidate candidate = candidateRepository.findById(candidateId).get();
batch.getCandidates().add(candidate);
batchRepository.save(batch);
}
或者也尝试从子实体添加它,它实际上起作用了:
public void addBatchToCandidate(int batchId, int candidateId) {
Candidate candidate = candidateRepository.findById(candidateId).get();
Batch batch = batchRepository.findById(batchId).get();
candidate.setBatch(batch);
candidateRepository.save(candidate);
}
有人可以帮助启发我为什么它在一侧起作用,但是不会对另一个起作用吗? 有没有办法让它们都工作?
I am trying to do ORM and add from a parent entity (Batch) to the child entity (Candidate),
I made the relations as below:
Batch Class:
@OneToMany(mappedBy = "batch", cascade = CascadeType.ALL)
private List<Candidate> candidates;
Candidate Class:
@ManyToOne
@JoinColumn(name = "BatchID")
private Batch batch;
I tried to use JPA Repository from the BatchRepository and from the CandidateRepository
Here I tried to add it via the parent entity, but it didn't work:
public void addCandidateToBatch(int batchId, int candidateId) {
Batch batch = batchRepository.findById(batchId).get();
Candidate candidate = candidateRepository.findById(candidateId).get();
batch.getCandidates().add(candidate);
batchRepository.save(batch);
}
Alternatively also tried to add it from the child entity, and it actually worked :
public void addBatchToCandidate(int batchId, int candidateId) {
Candidate candidate = candidateRepository.findById(candidateId).get();
Batch batch = batchRepository.findById(batchId).get();
candidate.setBatch(batch);
candidateRepository.save(candidate);
}
Can someone help enlighten me why did it work on one side, but wont work on the other?
And is there a way to make both of them work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论