Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - Specifying whether or not to lazily load with Spring Data

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

@Entity
public class Parent{
@Id
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:

  1. "children" should be null when fetching parent

    public Parent getParent(Long parentId){
        return repo.findOne(parentId);
    }
    
  2. "children" should be filled when fetching parent:

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

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

@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: 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: com.entity.Parent["children"])

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

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

https://spring.io/blog/2014/05/21/what-s-new-in-spring-data-dijkstra#projections-in-spring-data-rest


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...