不传入catalogType通过编码查询产品的可行性及报错修复咨询
1. Can I retrieve products without passing catalogType?
In Hybris, ProductModel is tightly linked to CatalogVersionModel, which in turn belongs to a CatalogModel with a specific catalogType (like product or content).
You might be able to retrieve products without explicitly specifying catalogType only if:
- Your DAO's
findProductsByCodemethod is hardcoded to query against a specific CatalogVersion (unlikely in most standard setups) - There's already a valid, persisted CatalogVersion added to the current session that covers the product you're targeting
But this approach is risky:
- Multiple catalogs (even of the same type) can have products with identical
codevalues - Without specifying the catalog/version, you might end up fetching the wrong product or no results at all
It’s always better to explicitly target the correct CatalogVersion for your use case. If you don’t know the catalogType upfront, you could fetch all catalogs of type product via CatalogService and iterate through their versions—but this isn’t ideal for production code (you should ideally have clear context on which catalog you need to query).
2. Fixing the "cannot be serialized due to being modified, new or removed" Error
The root cause of your exception is that you’re using a transient (unsaved) CatalogVersionModel in your session. Hybris requires persisted models (with a valid PK) when interacting with FlexibleSearch, as it needs to serialize model identifiers to execute queries properly.
Here’s how to fix it:
- Instead of creating a new
CatalogVersionModelmanually, useCatalogVersionServiceto fetch an existing, persisted version from the database.
Modified Code Example
@Resource private ProductDao productDao; @Resource private CatalogVersionService catalogVersionService; List<ProductModel> getProductsByCode(String code) { // Replace "yourProductCatalogId" with the actual ID of your product catalog (e.g., "electronicsProductCatalog") CatalogVersionModel catalogVersionModel = catalogVersionService.getCatalogVersion("yourProductCatalogId", "Online"); // Add the persisted CatalogVersion to the session catalogVersionService.addSessionCatalogVersion(catalogVersionModel); // Now the DAO query will work with a valid, serializable model return productDao.findProductsByCode(code); }
Key Explanations:
catalogVersionService.getCatalogVersion(catalogId, version)fetches a pre-existing CatalogVersion that’s already saved in the database (so it has a valid PK).- Using a persisted model ensures Hybris can serialize it correctly when running the FlexibleSearch query behind
productDao.findProductsByCode.
内容的提问来源于stack exchange,提问作者john

