3

Basically I'm trying to get an entity that has a LAZY relation to another entity. Below are 2 things I tried. The first one works, the second one does not and I don't understand why. All I want is to get the entity from database. The reason why I put this in other method is I don't want the first one to be @Transactional because it can take some time to execute. Note that I'm not saving or even accessing the database again in the first method, I just need to read from db once.

Method 1 (Works as expected):

@Override
@Transactional
public void sendEmailToUser(Long exhibitorId) {
    EmailExhibitorTO exhibitorTO = findExhibitorById(exhibitorId);     
}

private EmailExhibitorTO findExhibitorById(Long id){
    return converter.convert(exhibitorRepository.findById(id), EmailExhibitorTO.class);
}

Everything here is fine, I'm getting the entity and the lazy initialized entity as well.

Method 2 (Doesn't work):

@Override
public void sendEmailToUser(Long exhibitorId) {
    EmailExhibitorTO exhibitorTO = findExhibitorById(exhibitorId);     
}

@Transactional
private EmailExhibitorTO findExhibitorById(Long id){
    return converter.convert(exhibitorRepository.findById(id), EmailExhibitorTO.class);

This however does not work. Error:enter image description here
There's a mapping exception but that's because lazy entity could not be fetched.
I'm probably just being stupid but if theres something I don't understand, please explain.
Thanks in advance.

Sikor
  • 11,628
  • 5
  • 28
  • 43

2 Answers2

5

The @Transactional in your private method has no effect because you are calling it from another method of the class, bypassing the Proxy that handles the transaction.

Ruben
  • 3,986
  • 1
  • 21
  • 34
  • 1
    Sounds reasonable, could you please elaborate a little on this topic? Is there any workaround? – Sikor Oct 08 '15 at 18:11
  • 1
    You can find an explanation [here](http://stackoverflow.com/questions/32994544/spring-cacheable-not-caching/32999744#32999744) – Ruben Oct 08 '15 at 18:13
0

you cannot propagate transactions on private methods, you can see it here: Does Spring @Transactional attribute work on a private method?

Community
  • 1
  • 1
  • On the first example that you said that works, you annotated jus the public method, and on the second one you made it on the private one. The @transactional works only on public methods, private and protected will not work, if you have problems with public methods throwing the LazyInitializationException, you need to check the scope of session that you are using. Can you send the piece of code that is throwing the error, if it is the case? – Joel Santos Oct 08 '15 at 18:17
  • The problem was exactly what @Ruben mentioned but thanks a lot for your interest in this question. Appreciate that. – Sikor Oct 08 '15 at 19:09