darrachequesne / spring-data-jpa-datatables

Spring Data JPA extension to work with the great jQuery plugin DataTables (https://datatables.net/)
Apache License 2.0
450 stars 172 forks source link

Fetch Lazy Field Not Initialized #108

Closed jamesavilla closed 1 year ago

jamesavilla commented 5 years ago

@OneToMany(cascade = {CascadeType.ALL}, orphanRemoval=true, fetch = FetchType.LAZY) @JoinColumn(name = "user_id",nullable=false) public Set userContacts;

Throws this error com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.APP.model.User.userContacts, could not initialize proxy - no Session (through reference chain: org.springframework.data.jpa.datatables.mapping.DataTablesOutput["data"]

How do I initialize this join without using FetchType.EAGER?

darrachequesne commented 1 year ago

Added in the documention here: https://github.com/darrachequesne/spring-data-jpa-datatables#fetch-lazy-fields

@RestController
public class MyController {

  @RequestMapping(value = "/entities", method = RequestMethod.GET)
  public DataTablesOutput<MyEntity> list(@Valid DataTablesInput input) {
    return myRepository.findAll(input, (root, query, criteriaBuilder) -> {
      if (query.getResultType() != Long.class) {
        root.fetch("relatedEntity", JoinType.LEFT);
      }
      return null;
    });
  }
}