Reputation: 3636
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
:
Request
by associating with existing ExamSchedule
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
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