无法编写JSON:无法懒惰地初始化集合

时间:2018-06-01 11:18:40

标签: java spring hibernate spring-boot spring-data-jpa

我正在使用Spring Boot 1.5.10,Spring Data JPA和Hibernate。

当我通过Id搜索实体Person时,结果是正确的,但是当我尝试使用List构建查询时,我的请求会返回异常:

Failed to write HTTP message: 
org.springframework.http.converter.HttpMessageNotWritableException: 
Could not write JSON: failed to lazily initialize a collection of role: us.icitap.entities.tims.Person.otherNames, could not initialize proxy - no Session; 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: us.icitap.entities.tims.Person.otherNames, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->us.icitap.entities.tims.Person["otherNames"])

我正在处理的实体的代码:

@Entity
@Table(name="PERSON", schema = "TIMS")
@NamedQuery(name="Person.findAll", query="SELECT p FROM Person p")
public class Person extends PersonAbstract {

    private static final long serialVersionUID = 1L;

    //bi-directional many-to-one association to PersonOtherName
    @OneToMany(mappedBy="person")
    private List<PersonOtherName> otherNames;

    //bi-directional many-to-one association to Photo
    @OneToMany(mappedBy="person")
    private List<Photo> photos;

    //bi-directional many-to-one association to TravelDocument
    @OneToMany(mappedBy="person")
    private List<TravelDocument> travelDocuments;

    public Person() {
    }

    public List<PersonOtherName> getOtherNames() {
        return this.otherNames;
    }

    public void setOtherNames(List<PersonOtherName> otherNames) {
        this.otherNames = otherNames;
    }

    public PersonOtherName addOtherName(PersonOtherName otherName) {
        getOtherNames().add(otherName);
        otherName.setPerson(this);
        return otherName;
    }

    public PersonOtherName removeOtherName(PersonOtherName otherName) {
        getOtherNames().remove(otherName);
        otherName.setPerson(null);
        return otherName;
    }

    public List<Photo> getPhotos() {
        return this.photos;
    }

    public void setPhotos(List<Photo> photos) {
        this.photos = photos;
    }

    public Photo addPhoto(Photo photo) {
        getPhotos().add(photo);
        photo.setPerson(this);
        return photo;
    }

    public Photo removePhoto(Photo photo) {
        getPhotos().remove(photo);
        photo.setPerson(null);
        return photo;
    }

    public List<TravelDocument> getTravelDocuments() {
        return this.travelDocuments;
    }

    public void setTravelDocuments(List<TravelDocument> travelDocuments) {
        this.travelDocuments = travelDocuments;
    }

    public TravelDocument addTravelDocument(TravelDocument travelDocument) {
        getTravelDocuments().add(travelDocument);
        travelDocument.setPerson(this);
        return travelDocument;
    }

    public TravelDocument removeTravelDocument(TravelDocument travelDocument) {
        getTravelDocuments().remove(travelDocument);
        travelDocument.setPerson(null);
        return travelDocument;
    }
}

服务的相关部分:

@SuppressWarnings("unchecked")
@Override
public List<Person> searchByExpression(List<Criterion> expressions) {
    Session session = entityManager.unwrap(Session.class);
    List<Person> persons = null;
    try {
        Criteria criteria = session.createCriteria(Person.class);
        for (Criterion simpleExpression : expressions) {
            criteria.add(simpleExpression);
        }
        persons = criteria.list();                      
    }catch (Exception e) {
        e.printStackTrace();            
    }
    session.close();
    return persons;
}

@Override
public Person searchPersonById(Long id) {       
    return personRepository.findOne(id);
}

控制器:

@RestController
@RequestMapping("/tims/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @RequestMapping(value="/searchPersonById/{id}", method = RequestMethod.GET)
    public ResponseEntity<Person> searchById(@PathVariable("id") Long id) {
        try {
            Person person = this.personService.searchPersonById(id);
            if (person == null)
                return new ResponseEntity<Person>(null, null, HttpStatus.NOT_FOUND);
            else 
                return new ResponseEntity<Person>(person, null, HttpStatus.OK);
        }catch(Exception e){
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.set("Exception", e.getMessage());
            ResponseEntity<Person> respond = new ResponseEntity<Person>(null, httpHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
            return respond;
        }
    }

    @RequestMapping("/searchPersonByGenerality")
    public ResponseEntity<List<Person>> searchPersonByGenerality(String pid, String name, String surname, GenderEnum gender, String dateOfBirth){
        List<Person> persons = null;
        Date date = null;
        try {
            if(dateOfBirth != null) {
                SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
                date = df.parse(dateOfBirth);
            }
        }catch (Exception e) {
            System.err.println(e.getMessage());
        }

        try {
            if (pid != null && !pid.isEmpty()) {
                persons = this.personService.searchPersons(pid, name, surname, gender, date);
                return new ResponseEntity<List<Person>>(persons, null, HttpStatus.OK);
            }
            int valid = 0;
            List<Criterion> expressions = new ArrayList<>();
            if(name != null & !name.isEmpty()) {
                name = name.toUpperCase();
                valid = valid + 5;
                if (name.contains("%") || name.contains("_")) {                 
                    expressions.add(Restrictions.sqlRestriction("translate({alias}.name, 'ËÇ', 'EC') like '" + MyString.transformAccentsLetter(name) + "'"));
                }else 
                    expressions.add(Restrictions.sqlRestriction("translate({alias}.name, 'ËÇ', 'EC') = '" + MyString.transformAccentsLetter(name) + "'"));
            }
            if(surname != null & !surname.isEmpty()) {
                surname = surname.toUpperCase();
                valid = valid + 5;
                if (surname.contains("%") || surname.contains("_")) {
                    expressions.add(Restrictions.sqlRestriction("translate({alias}.surname, 'ËÇ', 'EC') like '" + MyString.transformAccentsLetter(surname) + "'"));
                }else 
                    expressions.add(Restrictions.sqlRestriction("translate({alias}.surname, 'ËÇ', 'EC') = '" + MyString.transformAccentsLetter(surname) + "'"));
            }
            if (gender != null) {
                valid = valid + 2;
                expressions.add(Restrictions.eq("gender", gender));
            }
            if (date != null) {
                valid = valid + 3;
                expressions.add(Restrictions.between("dateOfBirth", atStartOfDay(date), atEndOfDay(date)));
            }
            persons = personService.searchByExpression(expressions);
            return new ResponseEntity<List<Person>>(persons, null, HttpStatus.OK);
        } catch (Exception e) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.set("Exception", e.getMessage());
            ResponseEntity<List<Person>> respond = new ResponseEntity<List<Person>>(null, httpHeaders,
                    HttpStatus.INTERNAL_SERVER_ERROR);
            return respond;
        }
    }
}

任何人都可以帮我找到我的代码中出现的问题吗?

2 个答案:

答案 0 :(得分:1)

这是以@OneToMany关系从数据库中检索数据的默认策略,在首次访问数据时应该懒惰地获取数据,在这种情况下,您要在关闭会话后尝试序列化实体。尝试为此属性建立EAGER的提取策略(有关详细信息,请查看this

@OneToMany(fetch = FetchType.EAGER, mappedBy="person")
private List<PersonOtherName> otherNames;

或者,您可以在关闭会话之前对此特定服务强制进行代理初始化:

Hibernate.initialize(person.getOtherNames());

  

如果您不需要在界面中显示此数据,则效率更高   解决方案甚至不会序列化它们:

@JsonIgnore
@OneToMany(mappedBy="person")
private List<PersonOtherName> otherNames;

答案 1 :(得分:0)

检查您的例外,它说:could not initialize proxy - no Session。这意味着您的会话未正确初始化。

尝试调试您的应用,看看运行时会发生什么

Session session = entityManager.unwrap(Session.class);