【问题标题】:Hibernate - Entity to JSONHibernate - 实体到 JSON
【发布时间】:2020-10-05 15:42:23
【问题描述】:

我需要将具有 JsonManagedReference 和 JsonBackReference 实现的实体转换为 json:

@Entity
@Table(name = "myparenttable", schema = "myschema", catalog = "mydb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Parent implements Serializable {
    private Integer id_parent;
    private String name;

    @JsonManagedReference
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private List<Child> children;
    
    //getters and setters
    
    
}


@Entity
@Table(name = "mychildtable", schema = "myschema", catalog = "mydb")
public class Child implements Serializable {
    private Integer id_child;
    private String description;
   

    @JsonBackReference
    private Parent parent;
    
    //getters and setters
    
}

有了这个设置,persist 函数就很简单了,我只是执行一个

em.persist(父);

两个实体都被插入到数据库中;但我还需要将这些实体转换为 json 用于审计目的。执行此操作时出现无限递归错误:

ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper
                    .writerWithDefaultPrettyPrinter()
                    .writeValueAsString(parent);

有没有办法做到这两点?

【问题讨论】:

  • 最好使用 DTO(数据传输对象)而不是实体,以避免泄露实体实现细节和使用 Json 注释使实体混乱,并提供更简单的视图。
  • RestRepositories 可能是您下一次技术审查的候选对象。
  • 这很奇怪。您不应该收到错误,@JsonBackReferences 不应该被序列化。 childrenParent 中的唯一关联吗?

标签: java json hibernate


【解决方案1】:

您可能希望将您的父对象注释到子类中

@JsonIgnore
private Parent parent;

这样父对象的引用不会被放入序列化的json对象中。

检查是否真的需要实现 Serializable 接口

【讨论】:

    【解决方案2】:

    这是将 DTO 与 Blaze-Persistence Entity Views 结合使用的完美用例。

    我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您按照自己喜欢的方式定义目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

    使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:

    @EntityView(Parent.class)
    public interface ParentDto {
        @IdMapping
        Integer getId();
        String getName();
        List<ChildDto> getChildren();
    
        @EntityView(Child.class)
        interface ChildDto {
            @IdMapping
            Integer getId();
            String getDescription();
        }
    }
    

    查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。

    ParentDto a = entityViewManager.find(entityManager, ParentDto.class, id);

    Spring Data 集成让您可以像使用 Spring Data Projections 一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

    除了解决您的序列化问题外,使用 Blaze-Persistence Entity-Views 还可以提高性能,因为它只选择实际需要的列。

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 1970-01-01
      • 2013-04-05
      • 2013-08-08
      • 1970-01-01
      相关资源
      最近更新 更多