specifying whether or not to lazily load with spring data

specifying whether or not to lazily load with spring data  using -'java,spring,hibernate,jpa,spring-data'

I have a lazy fetch type collection in an entity. And I am using Spring Data (JpaRepository) for accessing the entities.

public class Parent{
private Long id;

    @OneToMany(mappedBy = "parentId", fetch = FetchType.LAZY)
    private Set<Child> children;

I want two functions in service class and current implementation are as following:

"children" should be null when fetching parent

public Parent getParent(Long parentId){
    return repo.findOne(parentId);

"children" should be filled when fetching parent:

 public Parent getParentWithChildren(Long parentId){
     Parent p = repo.findOne(parentId);
     return p;

When returning "Parent" entity from a RestController, following exception is thrown:

public Parent getParent(@PathVariable("parentId") Long id)
    Parent p= parentService.getParent(id);//ok till here
    return p;//error thrown when converting to JSON

  Could not write content: failed to lazily initialize a collection of
  role: com.entity.Parent.children, could not initialize proxy - no
  Session (through reference chain: com.entity.Parent["children"]);
  nested exception is
  com.fasterxml.jackson.databind.JsonMappingException: failed to lazily
  initialize a collection of role: com.entity.Parent.children, could not
  initialize proxy - no Session (through reference chain:


asked Oct 6, 2015 by patelnikul321
0 votes

3 Answers

0 votes

If you are looking to allow for different JSON representations of the same domain model depending on use case, then you can look at the following which will allow you to do so without requiring DTOs:


Alternatively, see also the 'Projections in Spring Data REST' section in the following


answered Oct 6, 2015 by android_master
0 votes

The exception is thrown because the JSON serializer requires all properties to be already initialized. So, all REST Controllers that need to return a Parent, have to initialize the properties first:

public Parent getParent(@PathVariable("parentId") Long id) {
    return parentService.getParentWithChildren(id);

The getParentWithChildren Service method is run inside a transaction, and associated Hibernate Session is closed when the transaction is committed. This means you have to initialize all properties while the Hibernate Session is still open (inside the Service method).

You can also use the Spring Data entity graph support:

@NamedEntityGraphs(@NamedEntityGraph(name = "Parent.children", attributeNodes = @NamedAttributeNode("children")))
public class Parent{
private Long id;

    @OneToMany(mappedBy = "parentId", fetch = FetchType.LAZY)
    private Set children;

And the getParentWithChildren method becomes:

public interface ParentRepository extends CrudRepository {

    @EntityGraph(value = "Parent.children", type = EntityGraphType.LOAD)
    Parent getParentWithChildren(Long parentId);

So, you don't even need to implement the:

  1. getParent
  2. getParentWithChildren

These methods can be supplied by Spring Data.

answered Oct 6, 2015 by balvant maurya
0 votes

First of all, you did not show us the Child Java class: I hope the property is called parentId and not parent:

public class Child {
    private Parent parentId;

Solution 1: your code is actually correct, just that you MUST use a second layer of DTOs (simple POJO classes) for transporting your domain layer to the client/browser. If you do not do so, after you will solve your Lazy Exceptions you will get a problem with the circular dependency from Parent to Child and the JSON marshaller (Jackson) will try to encode a Child, then its Parent, then again its children, then again their Parent and so on. An example of DTO would be:

public class ParentDto {
    private Long id;
    private String prop1;

    public ParentDto(Parent parent) {
            this.id = parent.id;
            this.prop1 = parent.prop1;
            //...other properties

    //here come all getters for the properties defined above.

Solution 2: Use @JsonIgnore for your public property Parent.getChildren(), so that the Jackson does not try to encode the children when marshalling the Parent instance.

answered Oct 6, 2015 by patilkiran.101