hibernate entity to json

后端 未结 4 885
伪装坚强ぢ
伪装坚强ぢ 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:41


    As others have suggested, I would really not advise you to try to JSON serialize (or actually perform any serialization) of hibernate entities.
    You must remember that the fetched entities are actually "proxified" objects (Hibernate uses ASM, CGLIB and other "dynamic proxiy" frameworks).
    As a result for example, collections get replaced with [PersistenceBags] which may be initialized "lazily" , and cause you hibernate exceptions 1.

    But the problems do not stop there, you may see issues when trying to serialize an Hibernate custom type
    I know this might sound you like writing "boillerplate" code but you might end up coding DTOs - data transfer objects which will take the entity returned from your DAL, and transform them to an object that can be serialized.

    You can use a framework like dozer in order to ease development of serialization between an entity to a DTO.

提交回复
热议问题