gpt4 book ai didi

java - 将产品保留在阔叶数据库中

转载 作者:行者123 更新时间:2023-11-30 02:53:26 27 4
gpt4 key购买 nike

我正在从其他来源获取产品和类别。我想将它们保存在阔叶数据库中。我不想要自动生成的 id。我想将 id 来自源(从我获取产品等的地方)保留到阔叶数据库。

为此,我创建了自定义 Controller :http://www.broadleafcommerce.com/docs/core/current/broadleaf-concepts/admin/admin-custom-controllers

我正在 MyController 中编写产品和类别持久代码。

我尝试过以下代码:

    Category category =  catalogService.createCategory();
Long categoryId = new Long(453510);
category.setId(categoryId);
category.setName("test category4");
category.setUrl("/test-category4");

catalogService.saveCategory(category);

Product p = catalogService.createProduct(ProductType.PRODUCT);

Sku newSku = catalogService.createSku();
Long skuId = new Long(453520);
newSku.setId(skuId);
p.setDefaultSku(newSku);
p.getDefaultSku().setDefaultProduct(p);

p.setName("test product4");
p.setUrl("/test-product4");
p.setCategory(category);
Long productId = new Long(453530);
p.setId(productId);
catalogService.saveProduct(p);

我收到以下堆栈跟踪:

Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "blc_sku" violates foreign key constraint "fk28e82cf77e555d75"
Detail: Key (default_product_id)=(453530) is not present in table "blc_product".
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2182)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1911)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:173)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:645)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:495)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:441)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)

如果我删除下面的代码片段,那么它会给我空指针,因为设置默认 sku 需要产品对象。

Sku newSku = catalogService.createSku();
Long skuId = new Long(453520);
newSku.setId(skuId);
p.setDefaultSku(newSku);
p.getDefaultSku().setDefaultProduct(p);

请帮助我将具有给定 ID(非自动生成)的产品保留在阔叶数据库中。

最佳答案

由于 Hibernate 配置为生成这些实体上 id 属性的值,因此即使您尝试覆盖该值,Hibernate 也会强制生成下一个值。看起来您的覆盖值正在用于外键,而 Hibernate 的生成值正在为主键设置,从而导致 FK 约束违规。

这些实体(类别、产品、SKU)的设计假设用户将从外部系统导入,因此,它们每个都定义了一个 externalId 属性。推荐的方法是让 Hibernate 通过生成器管理 pk/fk 值,然后使用 externalId 属性将外部系统映射到这些实体。

如果您的要求不允许使用 externalId,您可以考虑尝试使用加载时编织来覆盖这些属性上的生成器注释。没有 Broadleaf 机制可以覆盖属性上的现有注释,因此这将是您必须探索的自定义。

关于java - 将产品保留在阔叶数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37947895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com