简体   繁体   English

在 JPA 中保存具有一对一关系的实体

[英]Saving an entity with one-to-one relation in JPA

I have an entity Request :我有一个实体Request

@Entity
public class Request {

    @Id
    @GeneratedValue
    private Long id;

    @OneToOne
    private Candidate candidate;

    ...
}

To create and save above entity into JPA repository, I will be doing something like following:要创建上述实体并将其保存到 JPA 存储库中,我将执行以下操作:

Candidate candidate = candidateRepository.findById(requestUpdate.getCandidate()).orElse(null);

Request request = new Request(candidate);
Request save = requestRepository.save(request);

As Request table in DB stores FK for candidate, I think it should be enough to set an id.由于 DB 中的Request表存储了候选人的 FK,我认为设置一个 id 就足够了。 But JPA expects me to set candidate object.但是 JPA 希望我设置候选 object。 This forces me to query candidate repository.这迫使我查询候选存储库。

Is it necessary to query for candidate from candidate repository to save Request or If I have candidate id available, can't I set it directly?是否需要从候选存储库中查询候选以保存Request ,或者如果我有可用的候选 ID,我不能直接设置它吗?

You need to use EntityManager#getReference or JpaRepository#getOne .您需要使用EntityManager#getReferenceJpaRepository#getOne It does not fetch the entire entity from the database, but rather wraps an id that you already have into a proxy to synchronize the relationships:它不会从数据库中获取整个实体,而是将您已经拥有的 id 包装到代理中以同步关系:

Candidate candidate = candidateRepository.getOne(requestUpdate.getCandidate());

Request request = new Request(candidate);
Request save = requestRepository.save(request);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM