javaspringjpaspring-bootspring-data

Spring Data JPA - Lazy Loaded collection fetched without @Transactional


My expectation is that a lazy loaded collection should be fetched when the collection is accessed within a transactional scope. For example, if I want to fetch a collection I can call foo.getBars.size(). The absence of an active transaction should result in an exception with an error message like

failed to lazily initialize a collection of bars: .... could not initialize proxy - no Session

However, I noticed that the behavior is different in my latest application. I'm using Spring Boot 1.5.1 with the "data-jpa" starter. I have used Spring Boot in the past, but the data-jpa starter is new for me.

Consider the following case. I have a lazy loaded ManyToMany collection.

@SuppressWarnings("serial")
@Entity
@Table(name = "foo")
public class Foo implements java.io.Serializable {
    ....
    private Set<Bar> bars = new HashSet<Bar>(0);
    ....

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "foo_bar_map",
        joinColumns = {@JoinColumn(name = "foo_id", nullable = false, updatable = false)},
        inverseJoinColumns = {@JoinColumn(name = "bar_id", nullable = false, updatable = false)})
    public Set<Bar> getBars() {
        return this.bars;
    }

    public void setBar(Set<Bar> bars) {
        this.bars = bars;
    }

My service method is NOT marked as Transactional but I am accessing a lazy loaded collection

@Service
public class FooServiceImpl implements FooService {

    @Autowired
    private FooRepository fooRepo;


    @Override
    public FooDTO findById(int fooId) {
        Foo foo = fooRepo.findOne(fooId);
        // The FooDTO constructor will access foo.getBars()  
        return new FooDTO(foo);
    }

And for context on the FooDTO constructor

public FooDTO(Foo foo) {
    ...
    for (Bar bar : foo.getBars()) {
        this.bars.add(bar);
    }
}

Contrary to my expectation and past experience, this code executes successfully and fetches the collection. Further, if I throw a breakpoint in my service method, I can step through the code and see the SQL statements in my logs that fetch the bars after my call to the fooRepo. After my call to fooRepo, I expect the transaction to be closed.

What's happening here?


Solution

  • Spring Boot uses an OpenEntityManagerInView interceptor by default. You can turn it off by setting the property spring.jpa.open-in-view to false.

    See the documentation for the reference about this (and other) JPA properties.