I have an emailsenderservice to manage email notification asynchronously. There are 2 async methods, one method works, but another one throws LazyInitializationException:
@Service
public class EmailSenderService {
// working
@Async
public void sendNewBidRequestEmail(BidRequest bidRequest) {
this.sendNewBidRequestEmailToSupplier(bidRequest);
}
@Transactional
public void sendNewBidRequestEmailToSupplier(BidRequest bidRequest) {
sendNewBidRequestEmailToSupplier(bidRequest, bidRequest.getHotels());
}
@Transactional
public void sendNewBidRequestEmailToSupplier(BidRequest bidRequest, List<Hotel> hotelList) {
for (Hotel hotel : hotelList) {
...
this.sender.send()
}
}
// not working, throw exception
@Async
public void sendCancelledBidRequestEmail(BidRequest bidRequest, String reason) {
this.sendCancelledBidRequestEmailToSupplier(bidRequest, bidRequest.getHotels(), reason);
}
@Transactional
public void sendCancelledBidRequestEmailToSupplier(BidRequest bidRequest, List<Hotel> hotelList, String reason) {
for (Hotel hotel : hotelList) { // throw exception here
...
this.sender.send();
}
}
I'm totally following this thread.
You can see both async methods have almost the same structure. Async method calls a transactional method. But the second one throws org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.corpobids.server.entity.BidRequest.hotels, could not initialize proxy - no Session
.
I even imitate the first async method structure to modify the second one to:
@Async
public void sendCancelledBidRequestEmail(BidRequest bidRequest, String reason) {
this.sendCancelledBidRequestEmailToSupplier(bidRequest, reason);
}
@Transactional
public void sendCancelledBidRequestEmailToSupplier(BidRequest bidRequest, String reason) {
this.sendCancelledBidRequestEmailToSupplier(bidRequest, bidRequest.getHotels(), reason);
}
@Transactional
public void sendCancelledBidRequestEmailToSupplier(BidRequest bidRequest, List<Hotel> hotelList, String reason) {
for (Hotel hotel : hotelList) { // exception in this line
...
this.sender.send();
}
}
}
This time, it gives me java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@fce9b7b is closed
.
I would like to know the missing point in my code, any help would be appreciated.