Specifying whether to lazily load data using Spring

I have a collection of lazy fetch types in essence. And I use Spring Data (JpaRepository) to access the objects.

@Entity
public class Parent{
@Id
private Long id;

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

I want the two functions in the service class and current implementation to be as follows:

  • "children" must be null when receiving the parent

    public Parent getParent(Long parentId){
        return repo.findOne(parentId);
    }
    
  • "children" must be completed upon receipt of the parent:

     public Parent getParentWithChildren(Long parentId){
         Parent p = repo.findOne(parentId);
         Hibernate.initialize(p.children);
         return p;
    }
    

When returning a Parent object from RestController, the following exception occurs:

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

org.springframework.http.converter.HttpMessageNotWritableException: : role: com.entity.Parent.children, - ( : com.entity.Parent [ "children" ]); com.fasterxml.jackson.databind.JsonMappingException: : com.entity.Parent.children, - ( : com.entity.Parent [ "" ])

+4
4

RestController ParentDTO Parent. ParentDTO .

+2

, JSON , . , REST, , :

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

getParentWithChildren , Hibernate , . , , Hibernate ( ).

Spring Data entity graph:

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

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

getParentWithChildren :

@Repository
public interface ParentRepository extends CrudRepository<Parent, Long> {

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

, :

  • GetParent
  • getParentWithChildren

Spring Data.

+2

, Child Java: , parentId, parent:

public class Child {
    @ManyToOne
    private Parent parentId;
}

1: , DTO ( POJO) /. , , , , JSON () Child, parent, , parent . DTO :

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.
}

2. @JsonIgnore Parent.getChildren(), parent.

+1
source

All Articles