hibernate entity to json

后端 未结 4 855
伪装坚强ぢ
伪装坚强ぢ 2021-01-06 05:06

i use Hibernate 4 and Spring 3.

i have two entity.

Book entity

@Entity
@Table(name = \"book\")
public class Book implements Serializable {

          


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 05:40

    Generally, when you call getter methods of entity classes(which returns relation object) out of transaction, then you get LazyInitializationExceptions.

    That's what might be happening in your case if you are converting entity class objects(retrieved from query) to json out of transaction.

    I had same issue, I converted my entity object retrieved by hibernate to json in controller. As controller was out of transaction(Transaction at service layer), while converting to json, getter methods of entity class objects are called and I got LazyInitializationException. Which obstructed object conversion to json, and response was not returned.

    My solution, Try this :

    @SuppressWarnings("unchecked")
    @RequestMapping( method = RequestMethod.GET )
    public @ResponseBody List getBook() {
        List res = bookService.findAll();
        for(Book book : res) {
           book.getAuthor().setBooks(null);
        }
        return res;
    }
    

提交回复
热议问题