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 layerproduct-sb-service
– Implementation layerproduct-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.
No comments:
Post a Comment