Page 1 of 1

Create Product with REST api (4.0.2) - no ID assigned

Posted: Sun Aug 02, 2015 7:59 am
by soee
I am trying to expand the rest endpoints with the ability to create products, so i can manage products from another application.
But in the response there is no id assigned.

I have added the following code in CatalogEndpoint:

Code: Select all

    @RequestMapping(value = "product", method = RequestMethod.POST)
    public ProductWrapper createProduct(HttpServletRequest request,
                                        @RequestBody() ProductWrapper productWrapper) throws BroadleafWebServicesException {
        Product product = catalogService.createProduct(ProductType.PRODUCT);
        Sku defaultSku = catalogService.createSku();
        defaultSku.setRetailPrice(new Money(0));
        product.setDefaultSku(defaultSku);
        product.setName("New product");
        catalogService.saveProduct(product);
        ProductWrapper wrapper;
        wrapper = (ProductWrapper) context.getBean(ProductWrapper.class.getName());
        wrapper.wrapDetails(product, request);
        return wrapper;
    }


It works well enough, in the sense that it returns the new product:

Code: Select all

{
  "name": "New product",
  "retailPrice": {
    "amount": "0.00",
    "currency": "USD"
  },
  "active": false
}


But the returned product is without an ID, which makes it a bit hard to work with afterwards.
From my previous experiences with Hibernate, this looks like a need to flush the session, so the ID can be assigned, but it has so far eluded me how to do this.

Any clues ?

Re: Create Product with REST api (4.0.2) - no ID assigned

Posted: Sun Aug 16, 2015 2:48 am
by dlavoie
I think you are not getting the ID because you are not reassigning the service response to your entity.

The following should fix your problem.

Code: Select all

product = catalogService.saveProduct(product);


BTW, thanks for the snippet of code, I'm going to need it for an automatic feed from my POS system to Broadleaf.

Re: Create Product with REST api (4.0.2) - no ID assigned

Posted: Thu Aug 20, 2015 12:31 am
by soee
I ended up overriding CatalogService, and calling em.flush() myself.
That seemed to work.

Code: Select all

  @Transactional(value = "blTransactionManager")
    @Override
    public Category saveCategory(Category category) {
        Category res = super.saveCategory(category);
        em.flush();
        return res;
    }