0

I use jHipster with Spring Data JPA and have the following method:

@Transactional(propagation=Propagation.REQUIRES_NEW)
public void doSomeWork(EntityA entityA) {
  // some code
  List<EntityB> entityBList = new ArrayList<EntityB>();
  entityBList.add(new EntityB());
  entityA.addAllEntityB(entityBList);
}

At the last line I get an org.hibernate.LazyInitializationException excption which I don't understand.

  • Why is it throwing this excption although the method is run in its own transaction?
  • Should it not just lazy load the list as the session is still open?
2
  • why do you use REQUIRES_NEW? Commented Sep 25, 2016 at 15:36
  • I use REQUIRE_NEW because this method is called from another class in a loop and i want after each iteration that the entities are getting persisted. In case one transaction fails in the loop, I want to have the previous iterations already persisted. Commented Sep 25, 2016 at 16:23

1 Answer 1

1

It might be that LazyInitializationException is thrown because a new transaction is started and entityA becomes "detached" as the result.

One can use something like this:

@Transactional
public void addEntityB(long entityAId, entityB) {
  EntityA entityA = loadEntityA(entityAId);
  addEntityBToEntityA(entityA, entityB);
  saveEntity(entityB);
}

called from outside in this manner:

for (EntityB entityB : entityBList) {
  try {
    addEntityB(entityAId, entityB);
  }
  catch(Exception e){
    log(e);
  }
} 

It is true that you load each time entityA, though.

Sign up to request clarification or add additional context in comments.

1 Comment

Thx a lot, you brought me to the right track. As EntityA is passed in to this transactional method, but fetched outside it gets detached. Hence fetching it first inside the transactional method solved the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.