Saturday, 17 May 2025

Using Service Builder in Modular Liferay Projects (OSGi Modules)

Using Service Builder in Modular Liferay Projects (OSGi Modules)

Service Builder is one of the most powerful tools provided by Liferay for generating database interaction layers. In modular OSGi-based Liferay projects, it allows you to define entities and auto-generate service layers that are ready for use across modules.

๐Ÿงฐ Prerequisites

  • Liferay 7.x or Liferay DXP workspace
  • Blade CLI installed
  • Basic understanding of OSGi modular structure

๐Ÿ“ฆ Step 1: Create Service Builder Module

blade create -t service-builder -p com.example.sb -c Product product-sb

This creates 3 modules:

  • product-sb-api – Interface layer
  • product-sb-service – Implementation layer
  • product-sb – Portlet or UI module (optional)

๐Ÿ“ Step 2: Define Entity in service.xml

Edit product-sb-service/src/main/resources/META-INF/service.xml

<?xml version="1.0"?>
<service-builder package-path="com.example.sb">

  <author>YourName</author>

  <namespace>SB</namespace>

  <entity name="Product" local-service="true" remote-service="false">
    <column name="productId" type="long" primary="true" />
    <column name="name" type="String" />
    <column name="price" type="double" />
  </entity>

</service-builder>

⚙️ Step 3: Build Services

./gradlew buildService

This will generate:

  • Persistence layer
  • Local service interfaces and implementations
  • ServiceUtil classes for easy access

๐Ÿ”Œ Step 4: Use the Generated Services

In any other OSGi module, include a dependency on the API module:

dependencies {
    compileOnly project(":modules:product-sb:product-sb-api")
}

Inject the local service using OSGi annotations:

@Reference
private ProductLocalService productLocalService;

Then you can use the service like this:

Product product = productLocalService.createProduct(counterLocalService.increment());
product.setName("Phone");
product.setPrice(499.99);
productLocalService.addProduct(product);

๐Ÿš€ Step 5: Deploy and Test

Deploy all the modules using:

./gradlew deploy

Use Gogo shell or custom portlet to test service calls.

๐Ÿงช Example Gogo Shell Test

:load com.example.sb.service.ProductLocalService
productLocalService.getProducts(0, 10)

๐Ÿ“˜ Summary

  • Service Builder works well in modular OSGi Liferay projects.
  • You can generate entities and services with a simple XML.
  • Split code into clean layers: API and SERVICE.
  • Can be consumed from any OSGi portlet or module.

๐Ÿ”— Useful Resources

No comments:

Post a Comment