【问题标题】:How to select data without relation如何选择没有关系的数据
【发布时间】:2017-09-16 18:31:32
【问题描述】:

我有一个名为 Product 的实体,它具有同一实体的外键,用于指示子产品。

我需要选择两种不同情况下的所有产品

首先,获取所有有关系的产品(工作中) 二、获取所有没有关系的产品(不工作)

@Entity
@Table(name = "product")
public class Product {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Integer id;

  private String name;

  private String description;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="product_id")
  private Product parentProduct;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public Product getParentProduct() {
    return parentProduct;
  }

  public void setParentProduct(Product parent_product_id) {
    this.parentProduct = parent_product_id;
  }

}

当我尝试时

public Product getProductByIdWithoutRelation(Integer id) {
    return productRepository.findById(id);
}

在存储库代码中使用以下方法

Product findById(Integer id);

我收到了这个错误

.w.s.m.s.DefaultHandlerExceptionResolver:无法写入 HTTP 消息:org.springframework.http.converter.HttpMessageNotWritableException:无法写入 JSON:没有找到类 org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 的序列化程序,也没有发现要创建的属性BeanSerializer(为避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS);嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 并且没有发现创建 BeanSerializer 的属性(为避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链: model.Product["parentProduct"]->model.Product_$$_jvst726_0["handler"])

感谢您的帮助!

【问题讨论】:

  • 你在使用Spring Data JPA吗?您正在通过 id 查找实体,那么您提到的具有约束的查找器在哪里?工作和不工作是什么意思?您是否只是将 DAO 的结果直接公开为 REST Web 服务?
  • 是的,我正在使用弹簧。获取所有显示其关系正常的产品。获取所有未显示其关系的产品,这是行不通的。 “您通过 id 查找实体,那么您提到的具有约束的查找器在哪里?”不明白你的意思

标签: spring spring-mvc spring-boot


【解决方案1】:

您需要使用 Jackson Hibernate datatype integration 来处理延迟加载的关系问题,这些问题通常伴随 Jackson 与 Hibernate 实体一起使用。你可以看看here在不同的答案,了解如何在不同的spring环境中进行配置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多