Omkar Shetkar
Omkar Shetkar

Reputation: 3636

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 ?

Upvotes: 0

Views: 2355

Answers (1)

Andronicus
Andronicus

Reputation: 26026

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);

Upvotes: 3

Related Questions