Omkar Shetkar
Omkar Shetkar

Reputation: 3636

Saving entities with @ManyToOne relation in Spring JPA

I have an entity Request:

@Entity
public class Request {

    @Id
    @GeneratedValue
    private Long id;

    private Long candidate;

    @ManyToOne
    private ExamSchedule examSchedule;

...

Also, ExamSchedule :

@Entity
public class ExamSchedule {

    @Id
    @GeneratedValue
    private Long id;

    @NonNull
    private Instant start;

    @NonNull
    private Instant end;

...

Now, to save Request along with ExamSchedule :

  1. I will be checking whether an exam schedule present for the given request.
  2. If yes, store new Request by associating with existing ExamSchedule
  3. If no, store new Request by associating with newly created ExamSchedule

In second case above, it is associating newly created ExamSchedule with Request. Here, it is expected that, it should not create new instance of ExamSchedule and use existing one.

Please let me know what could be missing here. Thanks.


Optional<ExamSchedule> scheduleOptional = examScheduleRepository
                .findByStartAndEnd(schedule.getStart(), schedule.getEnd());

        ExamSchedule examSchedule = scheduleOptional
                .orElse(examScheduleRepository.save(schedule));

        Request request = new Request(scribe.getId(), candidate.getId(), examSchedule);
        return requestRepository.save(request);

Upvotes: 1

Views: 402

Answers (1)

Omkar Shetkar
Omkar Shetkar

Reputation: 3636

That was a silly mistake. orElse of optional executes its parameter irrespective of whether optional is empty or not. I needed to use orElseGet. This provides Supplier as input which executes only when optional is empty.

ExamSchedule examSchedule = scheduleOptional.orElseGet(() -> examScheduleRepository.save(schedule));

Upvotes: 1

Related Questions