2

The below code triggers a Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.model.entity.WorkflowProcessEntity.workstations, no session or session was closed error. So I wrapped the method with @Transactional within a service class and it still throws the error.

    WorkstationService workstationService = (WorkstationService) ApplicationContextProvider.getApplicationContext().getBean("workstationService");
    for (WorkstationEntity workstationEntity : workstationService.getWorkstations(getEntity())) {
        registerWorkstation(new ImpositionWorkstation(workstationEntity));
    }

WorkstationService.java

@Transactional(readOnly = true)
public Collection<WorkstationEntity> getWorkstations(WorkflowProcessEntity workflowProcessEntity) {
    return workflowProcessEntity.getWorkstations();
}

WorkflowProcessEntity.java

@OneToMany(mappedBy = "workflowProcess")
@JsonIgnore
public Collection<WorkstationEntity> getWorkstations() {
    return workstations;
}

How can I query this relationship correctly?

4

1 回答 1

6

You have two problems in your code.

First, you're passing a detached entity to a transactional service, and expect the entity to become attached automatically. That isn't the case, a detached entity is detached, and whether you're inside a transaction or not, trying to load some lazy property from a detached entity will lead to an exception. To load it, you would have to reload the entity, by ID, from the session, and then load the lazy collection from this attached entity.

Second, you're assuming that getting the collection fro the entity loads it. That's not the case either. The collection is implemented as lazy-loaded proxy, and getting the collection and returning it does nothing more than getting the proxy (unitilialized) and returning it. It's only when calling a method on the collection that the proxy will initialize itself. For example, when iterating over the collection. And that is done outside of the transaction. The stack trace, if you had provided it, would probably have confirmed that the exception io not thrown from inside the servce, but from the iteration, outside the service.

于 2013-07-15T21:55:17.453 回答