java - 如何解决类中出现的一对多循环?

标签 java spring-boot jpa gson

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

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

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

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

这是部门类:

@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);
   }
}

我想要家长和 child 的信息, 但我不需要partment.chidren和children.parent信息。

最佳答案

比方说,鱼和熊掌不可兼得!

JPA 可以管理循环连接,但是当您序列化它时,整个事情就失去了意义。

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

@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;

关于java - 如何解决类中出现的一对多循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57015193/

相关文章:

java - 在访问器上方放置@Id 注释会导致创建元素集合表失败

java - 如何更新由 openFileOutput 创建的文件

java - 从 Core Java 中的数组中删除重复元素

java - Spring boot 中的请求是如何生成 JSON 值的?

java - 在 Spring boot security 中使用公钥/私钥创建和验证 JWT 签名

jpa - IntelliJ 2019.1 找不到 persistence.xml (添加到项目的类路径)

java - 浏览器重启java后保持 session

java - 从 AsyncTask 添加新的 MenuItem

java - 是否可以创建我自己的自定义注释来充当 Spring @Controller 注释?

java - JPA EntityManager 注入(inject)失败