如何解决班级中出现的一对多循环?

时间:2019-07-13 00:08:42

标签: java spring-boot jpa gson

在部门类中,它具有一个父部门和多个子部门。我希望JPA从数据库查询的实体包含上级部门信息和子部门信息,但是上级部门信息不需要包含其子部门的信息,并且子部门集合也不需要包含上级部门的信息。

我正在尝试在父系属上添加注释,但是它不起作用。 JPA返回的实体类型是HibernateProxy,我正在尝试将HibernateProxyTypeAdapter添加到gson并添加此代码

new GsonBuilder().excludeFieldsWithoutExposeAnnotation().registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY)

最后,我从邮递员那里得到的结果是{},是的,是一个空对象。这不是我想要的。

这是部门课程:

@Setter
@Getter
@Entity
@Table(name = "department")
public class Department implements Serializable {

    private static final long serialVersionUID = -3360650322926476819L;

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SnowFlakeIdGenerator")
    @GenericGenerator(name = "SnowFlakeIdGenerator", strategy = "cn.lmt.id.SnowFlakeIdGenerator")
    private Long id;

    @Column(name = "create_time", updatable = false)
    private LocalDateTime createTime;

    @Column(name = "update_time", insertable = false)
    private LocalDateTime updateTime;

    @PrePersist
    private void onPersist() {
        this.setCreateTime(LocalDateTime.now());
    }

    @PreUpdate
    private void onUpdate() {
        this.setUpdateTime(LocalDateTime.now());
    }

    @Column(name = "dept_name", length = 16)
    private String deptName;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Department parent;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<Department> children;
}
public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {

   public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
       @Override
       @SuppressWarnings("unchecked")
       public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
           return (HibernateProxy.class.isAssignableFrom(type.getRawType()) ? (TypeAdapter<T>) new HibernateProxyTypeAdapter(gson) : null);
       }
   };
   private final Gson context;

   private HibernateProxyTypeAdapter(Gson context) {
       this.context = context;
   }

   @Override
   public HibernateProxy read(JsonReader in) throws IOException {
       throw new UnsupportedOperationException("Not supported");
   }

   @SuppressWarnings({"rawtypes", "unchecked"})
   @Override
   public void write(JsonWriter out, HibernateProxy value) throws IOException {
       if (value == null) {
           out.nullValue();
           return;
       }
       // Retrieve the original (not proxy) class
       Class<?> baseType = Hibernate.getClass(value);
       // Get the TypeAdapter of the original class, to delegate the serialization
       TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
       // Get a filled instance of the original class
       Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer()
               .getImplementation();
       // Serialize the value
       delegate.write(out, unproxiedValue);
   }
}

我想要父母和孩子的信息, 但我不希望partment.chidren和children.parent信息。

2 个答案:

答案 0 :(得分:0)

比方说,你不能吃蛋糕和吃蛋糕!

JPA可以管理循环连接,但是在序列化序列时,一切都变得毫无意义。

因此,您必须跳过两个字段之一的序列化!

@ManyToOne
@JoinColumn(name = "parent_id")
//@JsonIgnore @XmlTransient //commented out   ------------------------1
private Department parent;

@JsonIgnore @XmlTransient  //optionally comment out this line instead of 1 ---2
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<Department> children;

答案 1 :(得分:0)

将代码更改为

    @ManyToOne
    @JoinColumn(name = "parent_id")
    @JsonIgnoreProperties("children")
    private Department parent;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    @JsonIgnoreProperties("parent")
    private List<Department> children;

它有效!