在使用JPA将记录插入多个表中。

huangapple go评论104阅读模式
英文:

Insert a record into multiple Table using JPA

问题

我有三个实体,分别是

  1. 产品(product)
  2. 产品详细信息(product details)
  3. 库存(stock)
  4. 类别(category)

当我尝试获取产品的详细信息时,一切正常,但当我尝试保存时,在控制台中显示以下错误:

2020-08-12 13:17:22.279  WARN 18612 --- [nio-9002-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.eMart.main.entity.Product]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.List) not compatible with managed type (com.eMart.main.entity.Product)

我的问题是如何将产品添加到数据库中以及如何优化我的实体。

输入

{
    "skuId": "2",
    "category": {
        "categoryId": 2,
        "categoryName": "食品"
    },
    "description": "牛奶",
    "stock": {
        "stockId": 1,
        "inventoryCount": 5,
        "selfCount": 5
    },
    "productDetails": [
        {
            "productDetailId": 1,
            "cost": 10.0,
            "currency": "inr",
            "expiryDate": "2020-08-11T18:30:00.000+00:00",
            "supplierCode": 1
        }
    ]
}

控制器方法

@PostMapping(value = "/test")
public ResponseEntity<Product> test(@RequestBody Product product) throws Exception {
    productRepositry.save(product);
    return new ResponseEntity(productRepositry.findAll(), OK);
}

产品类(Product)

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
public class Product {
    @Id
    @Column(name = "SKU_ID")
    String skuId = null;

    @ManyToOne
    @JoinColumn(name = "category_id")
    @JsonManagedReference
    Category category;

    @Column(name = "description")
    String description = null;

    @JsonManagedReference
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "stock_id", referencedColumnName = "id")
    Stock stock = null;

    @JsonManagedReference
    @OneToMany(mappedBy = "product", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    Set<ProductDetails> productDetails;
}

库存类(Stock)

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
public class Stock {
    @Id
    @Column(name = "id")
    Integer stockId;

    @Column(name = "inventory_count")
    Integer inventoryCount;

    @Column(name = "self_count")
    Integer selfCount;

    @JsonBackReference
    @OneToOne(mappedBy = "stock", cascade = CascadeType.ALL)
    Product product;
}

类别类(Category)

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Category {
    @Id
    @Column(name = "category_id")
    Integer categoryId;

    @Column(name = "category_name")
    String categoryName;

    @OneToMany(mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JsonBackReference
    List<Product> product;

    @Override
    public String toString() {
        return "Category{" +
                "categoryId=" + categoryId +
                ", categoryName='" + categoryName + '\'' +
                ", product=" + product +
                '}';
    }
}

产品详细信息类(ProductDetails)

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
public class ProductDetails {
    @Id
    @Column(name = "id")
    Integer productDetailId;

    @Column(name = "cost")
    Double cost;

    @Column(name = "currency")
    String currency;

    @Column(name = "expiry_date")
    Date expiryDate;

    Integer supplierCode;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY)
    Product product;
}

请让我知道如果你还需要其他信息。

英文:

I have three entities namely

  1. product
  2. product details
  3. stock
  4. category
    reference is given below

when I try to get the details of product it works fine when I try to save it shows below error in the console

2020-08-12 13:17:22.279  WARN 18612 --- [nio-9002-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.eMart.main.entity.Product]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference &#39;defaultReference&#39;: back reference type (java.util.List) not compatible with managed type (com.eMart.main.entity.Product)

My question is how to add the product into the database and how did I need to optimize my entities

Input

{
        &quot;skuId&quot;: &quot;2&quot;,
        &quot;category&quot;: {
            &quot;categoryId&quot;: 2,
            &quot;categoryName&quot;: &quot;food&quot;
        },
        &quot;description&quot;: &quot;cow milk&quot;,
        &quot;stock&quot;: {
            &quot;stockId&quot;: 1,
            &quot;inventoryCount&quot;: 5,
            &quot;selfCount&quot;: 5
        },
        &quot;productDetails&quot;: [
            {
                &quot;productDetailId&quot;: 1,
                &quot;cost&quot;: 10.0,
                &quot;currency&quot;: &quot;inr&quot;,
                &quot;expiryDate&quot;: &quot;2020-08-11T18:30:00.000+00:00&quot;,
                &quot;supplierCode&quot;: 1
            }
        ]
    }

controller method

@PostMapping(value = &quot;/test&quot;)
	public ResponseEntity&lt;Product&gt; test(@RequestBody Product product) throws Exception {
productRepositry.save(product);
		return new ResponseEntity(productRepositry.findAll(),OK);

	}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
public class Product {
    @Id
    @Column(name = &quot;SKU_ID&quot;)
    String skuId=null;
    @ManyToOne
    @JoinColumn(name = &quot;category_id&quot;)
    @JsonManagedReference
    Category category;

    @Column(name = &quot;description&quot;)
    String description=null;

   @JsonManagedReference
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = &quot;stock_id&quot;, referencedColumnName = &quot;id&quot;)
    Stock stock=null;

    @JsonManagedReference
    @OneToMany(mappedBy = &quot;product&quot;, fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    Set&lt;ProductDetails&gt; productDetails;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
     @Entity
    public class Stock {
    @Id
    @Column(name = &quot;id&quot;)
    Integer stockId;
    @Column(name = &quot;inventory_count&quot;)
    Integer inventoryCount;
    @Column(name = &quot;self_count&quot;)
    Integer selfCount;
    @JsonBackReference
    @OneToOne(mappedBy = &quot;stock&quot;,cascade = CascadeType.ALL)
    Product product;
    }
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor

public class Category {
    @Id
    @Column(name = &quot;category_id&quot;)
    Integer categoryId;

    @Column(name = &quot;category_name&quot;)
    String categoryName;



    @OneToMany(mappedBy = &quot;category&quot;, fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonBackReference
    List&lt;Product&gt; product;

    @Override
    public String toString() {
        return &quot;Category{&quot; +
                &quot;categoryId=&quot; + categoryId +
                &quot;, categoryName=&#39;&quot; + categoryName + &#39;\&#39;&#39; +
                &quot;, product=&quot; + product +
                &#39;}&#39;;
    }
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
public class ProductDetails {
    @Id
    @Column(name = &quot;id&quot;)
    Integer productDetailId;
    @Column(name = &quot;cost&quot;)
    Double cost;
    @Column(name = &quot;currency&quot;)
    String currency;
    @Column(name = &quot;expiry_date&quot;)
    Date expiryDate;

    Integer supplierCode;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY)
    Product product;
}

答案1

得分: 0

我认为您忘记在“ProductDetails”实体中的“Product”上添加`@JoinColumn`。

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SKU_ID")
Product product;


另外,您可以尝试从“Category”或“Stock”中移除@JsonManagedReference。
英文:

I think you have missed adding @JoinColumn on Product in ProductDetails entity

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = &quot;SKU_ID&quot;)
Product product;

Also, you can try be removing @JsonManagedReference from Category or Stock

huangapple
  • 本文由 发表于 2020年8月12日 20:45:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63376812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定