Java 无法写入JSON:未能延迟初始化集合

Java 无法写入JSON:未能延迟初始化集合,java,spring,hibernate,spring-boot,spring-data-jpa,Java,Spring,Hibernate,Spring Boot,Spring Data Jpa,我正在使用SpringBoot1.5.10、SpringDataJPA和Hibernate 当我按Id搜索实体人员时,结果是正确的,但当我尝试使用列表构建查询时,我的请求返回异常: Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collect

我正在使用SpringBoot1.5.10、SpringDataJPA和Hibernate

当我按Id搜索实体人员时,结果是正确的,但当我尝试使用列表构建查询时,我的请求返回异常:

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;
    }
}
@实体
@表(name=“PERSON”,schema=“TIMS”)
@NamedQuery(name=“Person.findAll”,query=“从Person p中选择p”)
公共类人物扩展人物摘要{
私有静态最终长serialVersionUID=1L;
//双向多对一关联到PersonOtherName
@OneToMany(mappedBy=“person”)
列名;
//双向多对一关联到照片
@OneToMany(mappedBy=“person”)
私人名单照片;
//TravelDocument的双向多对一关联
@OneToMany(mappedBy=“person”)
私人旅行证件清单;
公众人士(){
}
公共列表getOtherNames(){
返回this.otherNames;
}
public void setOtherNames(列出其他名称){
this.otherNames=其他名称;
}
public PersonOtherName addOtherName(PersonOtherName otherName){
getOtherNames().add(otherName);
otherName.setPerson(本);
返回其他名称;
}
public PersonOtherName removeOtherName(PersonOtherName otherName){
getOtherNames().remove(otherName);
otherName.setPerson(空);
返回其他名称;
}
公共列表getPhotos(){
把这张照片还给我;
}
公众照片(列表照片){
this.photos=照片;
}
公共照片添加照片(照片){
getPhotos().add(照片);
照片:赛特佩森(本);
返回照片;
}
公众照片移除照片(照片){
getPhotos()。删除(照片);
photo.setPerson(空);
返回照片;
}
公共列表getTravelDocuments(){
归还此文件;
}
公共旅行证件(列出旅行证件){
this.travelDocuments=travelDocuments;
}
公共TravelDocument addTravelDocument(TravelDocument TravelDocument){
getTravelDocuments().add(travelDocument);
travelDocument.setPerson(本);
归还旅行证件;
}
公共TravelDocument删除TravelDocument(TravelDocument TravelDocument){
getTravelDocuments().remove(travelDocument);
travelDocument.setPerson(空);
归还旅行证件;
}
}
服务的相关部分:

@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);
}
@SuppressWarnings(“未选中”)
@凌驾
公共列表searchByExpression(列表表达式){
Session Session=entityManager.unwrap(Session.class);
列出人员=空;
试一试{
条件=session.createCriteria(Person.class);
for(标准simpleExpression:表达式){
添加(simpleExpression);
}
persons=criteria.list();
}捕获(例外e){
e、 printStackTrace();
}
session.close();
返回人员;
}
@凌驾
公众人物searchPersonById(长id){
返回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;
        }
    }
}
@RestController
@请求映射(“/tims/person”)
公共类个人控制器{
@自动连线
私人私人服务;
@RequestMapping(value=“/searchPersonById/{id}”,method=RequestMethod.GET)
公共响应searchById(@PathVariable(“id”)长id){
试一试{
Person=this.personService.searchPersonById(id);
if(person==null)
返回新的ResponseEntity(null,null,HttpStatus.NOT_FOUND);
其他的
返回新的ResponseEntity(person,null,HttpStatus.OK);
}捕获(例外e){
HttpHeaders HttpHeaders=新的HttpHeaders();
set(“异常”,例如getMessage());
ResponseEntity response=新的ResponseEntity(null,httpHeaders,HttpStatus.INTERNAL_SERVER_ERROR);
回复;
}
}
@请求映射(“/SearchPersonByGeneral”)
public ResponseEntity SearchPersonByGeneral(字符串pid、字符串名称、字符串姓氏、性别、字符串出生日期){
列出人员=空;
日期=空;
试一试{
if(出生日期!=null){
SimpleDataFormat df=新的SimpleDataFormat(“dd.MM.yyyy”);
date=df.parse(出生日期);
}
}捕获(例外e){
System.err.println(e.getMessage());
}
试一试{
if(pid!=null&&!pid.isEmpty()){
persons=this.personService.searchPersons(pid、姓名、姓氏、性别、日期);
返回新的ResponseEntity(persons,null,HttpStatus.OK);
}
int valid=0;
列表表达式=新的ArrayList();
if(name!=null&!name.isEmpty()){
name=name.toUpperCase();
有效=有效+5;
如果(name.contains(“%”)| | name.contains(“|”){
add(Restrictions.sqlRestriction(“translate({alias}.name,';
}否则
expressions.add(Restrictions.sqlRestriction(“translate({alias}.name,'ËËË','EC')='”+MyString.transformAccentsLetter(name)+“”));
}
if(姓氏!=null&!姓氏.isEmpty()){
姓氏=姓氏。toUpperCase();
有效=有效+5;
if(姓氏包含(“%”)| |姓氏包含(“|”)){
expressions.add(Restrictions.sqlRestriction(“translate({alias}.lasname,';
}否则
expressions.add(Restrictions.sqlRestriction(“translate({alias}.laname,'
Session session = entityManager.unwrap(Session.class);
@OneToMany(fetch = FetchType.EAGER, mappedBy="person")
private List<PersonOtherName> otherNames;
Hibernate.initialize(person.getOtherNames());
@JsonIgnore
@OneToMany(mappedBy="person")
private List<PersonOtherName> otherNames;