Showing posts with label CRUD. Show all posts
Showing posts with label CRUD. Show all posts

Tuesday, 29 August 2017

Creating Service Builder in Liferay 7

Creating Service Builder in Liferay 7

We can create service builder module to perform various CRUD operation in liferay. This post includes creating and building service module in liferay 7.

In service module we just need to specify table structure in service.xml file and all methods for CRUD operation will generate automatically.

Today we will create basic service module with only one table i.e one entity using Liferay IDE

Goto File→New→Liferay Module Project

Give ProjectName→product-registration-service
Select ServiceBuilder as project template and Click Next


Give Package Name →com.liferay.product.service and click finish

This will create product-registration-service module as shown here.

product-registration-service will include 
  1. product-registration-service-api 
  2. product-registration-service-service
Now open service.xml file located in product-registration-service-service and click on Overview.

For this tutorial change namespace to pr. 

Click on Entities,here you can add any number of entities you want using + symbol shown in figure,each entity will be store as a separate table in you database.


Now add one Entity→ Product.
Click on Product here their are various properties available which you can set.
Enter product_details in table property and click on local service as shown below

Click on columns here you can add various columns for your entity with datatype. 
Now Add 4 fields  
  1. productId
  2. companyId
  3. productName
  4. productPrice
Set primary =true and id type ="increment" for productId filed

Now click on source this will generate following code.

<?xml version="1.0"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 7.0.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_7_0_0.dtd">

<service-builder package-path="com.liferay.product.service">
<namespace>pr</namespace>
<entity local-service="true" name="Product" table="product_details" remote-service="false" uuid="true">
<column name="productId" primary="true" type="long" id-type="increment"/>
<column name="companyId" type="long" />
<column name="productName" type="String" />
<column name="productPrice" type="long" />

</entity>
</service-builder>

Now its all done, just we require to build service and deploy our service module and this will create product_details table in our mysql database and it will also generate  required CRUD methods for Product Entity.

For Building Service and deploying service module we will be using gradle task

Note we need to build and deploy both 
  1. product-registration-service-api 
  2. product-registration-service-service
First go to Gradle Task→product-registration-service-service and perform
  • build service
  • build
  • deploy
Then go to Gradle Task→product-registration-service-api and perform
  • build
  • deploy

Note if you have not set liferay.workspace.home.dir and liferay.workspace.modules.default.repository.enabled in your gradle.properties visit my previous blog Deploying liferay module to tomcat

Congratulations you have successfully created service module with entity Product ,now check your module it has generated lots of packages and classes.Also check your database here you will find product_details is generated.



Final Project Structure




Also we can create various finder methods in service builder.My future post on service builder will include creating finder and writing custom sql in liferay 7.

CRUD Operations in Liferay 7

CRUD Operations in Liferay 7


Following are some simple step to execute CRUD operation in LiferayDXP.

Step1 Create mvc portlet module with name ProductRegistration and Component class name ProductRegistrationPortlet and package name com.liferay.product.portlet.
For more information read my previous blog on creating mvc module portlet 



Step 2 Create Service Builder Module with name product-registration-service and package name com.liferay.product.service. and run build service gradle task. For more information on this visit my previous blog on creating service builder module

Step 3 Open build.gradle file of ProductRegistration module and add gradle dependencies of the api module generated after building service.

compileOnly project(":modules:product-registration-service:product-registration-service-api")

Step 4 Refresh your gradle project using ctrl+f5 so that above dependencies get resolved.

Step 5 Create addProduct.jsp in /META-INF/resources/ folder of your MVC portlet.

Step 6 Create renderURL in view.jsp as shown below.

view.jsp

<%@ include file="init.jsp" %>
<portlet:renderURL var="addProductURL">
<portlet:param name="mvcPath" value="/addProduct.jsp"/>
</portlet:renderURL>


<aui:button onClick="${addProductURL}" value="add-product"></aui:button>

Step 7 Create aui-form for user input in  addProduct.jsp as shown below

<%@ include file="init.jsp"%>
<portlet:actionURL name="addProduct" var="addProductURL">
</portlet:actionURL>

<aui:form action="${addProductURL}">
<aui:input name="productName" label="productName"></aui:input>
<aui:input name="productPrice" label="productPrice"></aui:input>
<aui:input name="" type="submit" value="add-product"></aui:input>
</aui:form>

Step 8 Create render method and process action method with name addProduct to scan user input in your controller as shown below.

package com.liferay.product.portlet;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.product.service.service.ProductLocalServiceUtil;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletException;
import javax.portlet.ProcessAction;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.osgi.service.component.annotations.Component;

@Component(
immediate = true,
property = {
"com.liferay.portlet.display-category=category.sample",
"com.liferay.portlet.instanceable=true",
"javax.portlet.display-name=ProductRegistration Portlet",
"javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp",
"javax.portlet.resource-bundle=content.Language",
"javax.portlet.security-role-ref=power-user,user"
},
service = Portlet.class
)
public class ProductRegistrationPortlet extends MVCPortlet {
private static final Log log=LogFactoryUtil.getLog(ProductRegistrationPortlet.class);
@Override
public void render(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
// TODO Auto-generated method stub
super.render(renderRequest, renderResponse);
}
@ProcessAction(name="addProduct")
public void addProduct(ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {

}
}

Step 9 Create a saveProduct method in ProductLocalServiceImpl located in service module inside package com.liferay.product.service.service.impl as shown below

package com.liferay.product.service.service.impl;
import aQute.bnd.annotation.ProviderType;
public class ProductLocalServiceImpl extends ProductLocalServiceBaseImpl {

public void saveProduct(String productName,long productPrice){

Product product=new ProductImpl();
product.setProductId(counterLocalService.increment());
product.setProductName(productName);
product.setProductPrice(productPrice);
updateProduct(product);

}
}

Step 10 Goto gradle task execute following task.

  • For product-registration-service-service and perform
               build service
               build 
               deploy
  • For product-registration-service-api
              build
              deploy

Then refresh your gradle project to resolve dependencies 

Step 10 Scan user input and saveProduct method in controller as shown below.

package com.liferay.product.portlet;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.product.service.service.ProductLocalServiceUtil;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletException;
import javax.portlet.ProcessAction;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.osgi.service.component.annotations.Component;

@Component(
immediate = true,
property = {
"com.liferay.portlet.display-category=category.sample",
"com.liferay.portlet.instanceable=true",
"javax.portlet.display-name=ProductRegistration Portlet",
"javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp",
"javax.portlet.resource-bundle=content.Language",
"javax.portlet.security-role-ref=power-user,user"
},
service = Portlet.class
)
public class ProductRegistrationPortlet extends MVCPortlet {
private static final Log log=LogFactoryUtil.getLog(ProductRegistrationPortlet.class);
@Override
public void render(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
// TODO Auto-generated method stub
super.render(renderRequest, renderResponse);
}
@ProcessAction(name="addProduct")
public void addProduct(ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
String productName=ParamUtil.getString(actionRequest,"productName");
long productPrice=ParamUtil.getLong(actionRequest,"productPrice");
ProductLocalServiceUtil.saveProduct(productName, productPrice);
}
}

We are all done build and deploy ProductRegistration MVC Module then add portlet on any page .

MyOutput

Final Project Structure

Summary in this post we see how to add record in database using Liferay 7.
In my future post we will learn how to fetch all records from database and display them on jsp using SearchContainer in liferay 7.

In case of any query please let me know.

Search Container in Liferay 7


Search Container in Liferay 7


Here we will learn how to display all records of Product table created in my previous post which include three cloumns.
  1. productId
  2. productName
  3. productPrice
Step1 Open view.jsp page.Goto Windows→Show View→Snippets as shown here


Now navigate to Liferay UI Search Container → Model Search Container→Browse


From here select Product Entity as shown below.


This will insert liferay-ui:search-container code in your view.jsp as shown below.

<liferay-ui:search-container delta="5" deltaConfigurable="true" emptyResultsMessage="no-products">
<liferay-ui:search-container-results results="<%= ProductLocalServiceUtil.getProducts(searchContainer.getStart(), searchContainer.getEnd()) %>" />

<liferay-ui:search-container-row
className="com.liferay.product.service.model.Product"
modelVar="aProduct">
<liferay-ui:search-container-column-text property="productId"/>
<liferay-ui:search-container-column-text property="productName"/>
<liferay-ui:search-container-column-text property="productPrice"/>
  </liferay-ui:search-container-ow>

<liferay-ui:search-iterator />
</liferay-ui:search-container>

Here we use various tags which are explained as follow.
  1. <liferay-ui:search-container delta="" deltaConfigurable="" emptyResultsMessage=""/>  

This tag conatins following attributes

delta-This attribute is used to specify how many records per page we want to display.

deltaConfigurable--This attribute is used to specify whether user can change no of records displayed on page.It takes boolean value.

emptyResultsMessage--This is message that will be displayed when there are no records available to display

     2<liferay-ui:search-container-results results="" />

It take following attribute.

results--This attribute contains all records between start and end index which can be specified using searchContainer object as follows.

<liferay-ui:search-container-results results=
         "<%= ProductLocalServiceUtil.getProducts(searchContainer.getStart(), searchContainer.getEnd()) %>" />

   3<liferay-ui:search-container-row className="" modelVar="">

This tag contains following tags.

className--This attribute takes full path of your model attribute.

modelVar--This variable holds current object for each row.We can use this variable to get attribute values of object.

    4 <liferay-ui:search-container-column-text property="" name=""/>

property--this should be same as various fields of your Model Class (i.e Product) who's getter setter is already available.If match is found then it will display attribute value each time for current object.

name--This will be used to specify header name for each column.

href:- We can pass URL if we want some action to trigger on click of this field

    5 <liferay-ui:search-iterator />


  • This tag is used to iterate over list and generates row based on no of records in list.This must come after row tag.

View.jsp

<%@page
import="com.liferay.product.service.service.ProductLocalServiceUtil"%>
<%@ include file="init.jsp"%>
<portlet:renderURL var="addProductURL">
<portlet:param name="mvcPath" value="/addProduct.jsp" />
</portlet:renderURL>

<aui:button onClick= "${addProductURL}" value="add-product"></aui:button>

<liferay-ui:search-container delta="5" deltaConfigurable="true" emptyResultsMessage="no-products">
<liferay-ui:search-container-results results="<%= ProductLocalServiceUtil.getProducts(searchContainer.getStart(), searchContainer.getEnd()) %>" />

<liferay-ui:search-container-row
className="com.liferay.product.service.model.Product"
modelVar="aProduct">
<liferay-ui:search-container-column-text property="productId" name=""/>
<liferay-ui:search-container-column-text property="productName"/>
<liferay-ui:search-container-column-text property="productPrice"/>
</liferay-ui:search-container-row>

<liferay-ui:search-iterator />
</liferay-ui:search-container>

O/P