Model service create method vs new operator

When we try to create a new instances of an item type programmatically, we have two options, using the java way, using new operator or the hybris way, using the model service.

ProductModel product1 = new ProductModel();

ProductModel product2 = modelService.create(ProductModel.class);

The advantages of using model service method are below:

  1. The model service create method will generate and assign the pk for product object.
  2. The create method will initialize the default values, defined in items.xml for mandatory attributes.
  3. While calling save all method, the object is already attached to context, and will be saved. While product1 needs to attach explicitly.

So we should always go for model service way in hybris.

Why models are generated in platform extensions?

Hybris is build over the concepts of extensions. Each extension has it’s own data model. Any extension can use an item type from other extension and extend it as per requirement.

For example, the itemtype  product defined in core extension. The catalog extension has extended the product itemtype, and added vendor to it.

While building the hybris, the frameworks builds according to dependencies. Since core is build before catalog extension, it is not aware of the vendor attribute defined in catalog extension. If we keep model class in extensions, then there will e chance of build failures. Like in our case, vendor attribute will not find a place in ProductModel class.

blog1

Hybris build framework, creates model classes, even before, building any extension. The platform is the best place to keep them, as every extension is built upon it only. So it is not logical to create model classes in particular extensions, when we can define same data model in various extensions.

When to use modelService.refresh() method?

The OOB Hybris Model Service provides a method, to refresh the model. Usually we use this method to refresh the data, before saving the data in database, using save method.

There might be conditions, where some other thread or operation would be updating the same model instance. Br doing a refresh, we can be sure of not loosing those changes. This is of more importance, if we are going through a time consuming transaction like payment.

refresh model

 

Also transaction like, stock update, may happen simultaneously from multiple users, so we should always refresh the model, before saving it.