0

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 ?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
Omkar Shetkar
  • 3,488
  • 5
  • 35
  • 50

1 Answers1

3

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);
Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • Thanks for the answer. This works for simple entitites. For entitiies with nested relationships, will get an error during deserialization https://stackoverflow.com/questions/52656517/no-serializer-found-for-class-org-hibernate-proxy-pojo-bytebuddy-bytebuddyinterc – Omkar Shetkar Dec 18 '20 at 00:03
  • @Omkar it's not a problem with `getOne` or `getReference`. You have simply wrong mapping somewhere – Andronicus Dec 18 '20 at 05:04