'org.hibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs) when using @Lazy Anottaion in AuditTrailListener

AuditTrailListener

@Component
public class AuditTrailListenerSchedule {

private final NotificationService notificationService;
private final EmployeeService employeeService;

@Autowired
@Lazy
public AuditTrailListenerSchedule(NotificationService notificationService, EmployeeService employeeService) {
    this.notificationService = notificationService;
    this.employeeService = employeeService;
}


@PostPersist
public void afterAnyCreateSchedule(Schedule schedule) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Employee employee = employeeService.findByUsername(auth.getName());


    Notification newNotification = Notification.builder()
            .employee(schedule.getEmployee())
            .date(dateCreated())
            .message(String.format("%s added new schedule form %s to %s ", employee.getFullName(), schedule.getFrom(), schedule.getTo()))
            .build();

    notificationService.save(newNotification);
}

When I use employeeService.findByUsername(auth.getName()) I end up with this exception:

rg.hibernate.AssertionFailure: null id in com.mikedev.HRMSystem.model.Schedule entry (don't flush the Session after an exception occurs)

If I use employeeService.findById(1L) I got no problems it's find the user without exception, everything is same in repository for the find by username is Optional and throw exception when is not entity with that username found. I think this may be from the @Lazy annotation. How can I get around this problem and find the employee with the given logged user username.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source