zoukankan      html  css  js  c++  java
  • @JsonIgnore @JsonIdentityInfo 处理Hibernate 循环引用的问题

    enterprise和user一对一的关系:

    @Entity
    @Table(name = "enterprise")
    public class Enterprise extends BaseEntity {
    
        private static final long serialVersionUID = 1L;
    
        private User user;
    
        private String name;
    
        @OneToOne(mappedBy = "enterprise")
        public User getUser() {
            return user;
        }
    
        public void setUser(User user) {
            this.user = user;
        }
    
        ...setter/getter
    }
    @Entity
    @Table(name = "APP_USER")
    public class User extends BaseEntity {
        @NotEmpty
        @Column(name = "FIRST_NAME", nullable = false)
        private String firstName;
    
        @Column(name = "LAST_NAME", nullable = true)
        private String lastName;
    
        @OneToOne
        private Enterprise enterprise;
    }

    在controller中,使用ResponseEntity来返回enterprise转换为json之后的字符串。如果不做任何处理,因为enterprise拥有user字段,而user也拥有enterprise字段,自此出现了循环引用的问题,程序将会出错。

    使用@JsonIgnore

    @JsonIgnore
    @OneToOne(mappedBy = "enterprise")
    public User getUser() {
        return user;
    }

    在getUser方法上添加@JsonIgnore注释,返回的enterprise json对象中,将不包括user对象。
    但是如果我们希望在enterprise json对象中包括user的json对象该怎么办呢?

    使用@JsonIdentityInfo

    Annotation used for indicating that values of annotated type or property should be serializing so that instances either contain additional object identifier (in addition actual object properties), or as a reference that consists of an object id that refers to a full serialization. In practice this is done by serializing the first instance as full object and object identity, and other references to the object as reference values.

    在user类或者enterprise类上增加该注解即可。

    @Entity
    @Table(name = "enterprise")
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    public class Enterprise extends BaseEntity

    原文地址:https://blog.csdn.net/jiangshanwe/article/details/72994159

  • 相关阅读:
    Borland C++ Builder Practical learning series
    vmware打开vmx文件不能创建虚拟机的问题
    c3p0 连接数据库失败的问题
    外在 挺直背和走路的问题
    JAVAWEB tomcat服务器启动错误原因总结
    JAVAWEB 项目注册登录模块问题总结
    JAVA eclipse Maven项目红叹号解决方案
    JAVA 文件读取写入后 md5值不变的方法
    Git的安装配置(win环境)
    JAVA 静态方法和实例方法的区别 (图表)
  • 原文地址:https://www.cnblogs.com/jpfss/p/11064247.html
Copyright © 2011-2022 走看看