简体   繁体   中英

Saving an entity with one-to-one relation in JPA

I have an entity 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:

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. But JPA expects me to set candidate 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?

You need to use EntityManager#getReference or JpaRepository#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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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