Liferay

CRUD Operations in Liferay Portlet with custom entity

Bhargav Vaghasiya
Bhargav VaghasiyaOct 22, 2019
CRUD Operations in Liferay Portlet with custom entity

Introduction:

Service Builder is a code generation tool built by Liferay that allows developer to create custom entities. Service Builder generates necessary model, persistence and service layers based on service.xml. These layers provide a clean separation of concerns and allowing you to focus on the higher level aspects of the service design. All of Liferay’s services either local or remote services are generated by Service Builder.

Prerequisites:

  • Java
  • Liferay portal 7/7.x

Environment Requirement:

Assuming that you have already created a Liferay-workspace project in eclipse IDE.

Here we will create custom entity called “Student” and perform CreateReadUpdate and Delete operation on this custom entity.

Follow below steps to complete CRUD operation for your custom entity:

1. Create service-builder module for your custom entity

  1. Go to liferay workspace project  modules  new
  2. Select other  Liferay  Liferay Module Project and Click on “Next”
  3. Enter project name
  4. Select “Project Template Name” as “service-builder” and Click on “Next”
  5. Enter Package name and click on “Finish”. The necessary file structure for service-builder automatically get created as below.
Blog Image

2. Add student entity in xxx-service/service.xml like as below

1// service.xml //
2<?xml version="1.0"?>
3<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 7.2.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_7_2_0.dtd">
4
5<service-builder dependency-injector="ds" package-path="com.ignek.student">
6	<namespace>stud</namespace>
7	<entity local-service="true" name="Student" remote-service="true">
8
9		<!-- PK fields -->
10		<column name="studentId" primary="true" type="long"></column>
11
12		<!-- Group instance -->
13		<column name="groupId" type="long"></column>
14
15		<!-- Audit fields -->
16		<column name="companyId" type="long"></column>
17		<column name="createdby" type="long"></column>
18		<column name="modifiedby" type="String"></column>
19		<column name="createDate" type="Date"></column>
20		<column name="modifiedDate" type="Date"></column>
21
22		<!-- Other fields -->
23		<column name="enrollmentNo" type="String"></column>
24		<column name="firstName" type="String"></column>
25		<column name="lastName" type="String"></column>
26		<column name="contactNo" type="String"></column>
27		<column name="city" type="String"></column>
28
29	</entity>
30</service-builder>

3. Build the service-builder module

In terminal, navigate to the root directory of your service-builder project

Execute the below command to build the service-builder module

1blade gw buildService

The necessary file structure for service-builder automatically gets created as below. It will automatically generate model, persistence, and service layers

Blog Image

Execute below command to deploy the service-builder module

1blade gw deploy

4. Create MVC Portlet

  1. Go to liferay workspace project  modules  new
  2. Select other  Liferay  Liferay Module Project and Click on “Next”
  3. Enter project name
  4. Select “Project Template Name” as “mvc-portlet” and Click on “Next”
  5. Enter Package name and Click on “Finish”. The necessary file structure for mvc module will gets created as below
Blog Image

5. In order to add dependency of student-api in mvc portlet, add below line in “build.gradle” of your mvc portlet.

1// build.gradle //
2dependencies {
3	...
4	/*
5	compileOnly project(":modules:{your service-builder module name}:{your module-api}")
6	*/
7	compileOnly project(":modules:student:student-api")
8}

6. Now create add-student.jsp file in same directory as view.jsp. Add below code to add-student.jsp.

1<%@ include file="init.jsp"%>
2<portlet:defineObjects />
3<portlet:actionURL name="addStudent" var="addStudentActionURL"/>
4
5<h2>Add Student Form here !</h2>
6<aui:form action="<%=addStudentActionURL %>" name="studentForm" method="POST">
7	<aui:input name="enrollmentNo" >
8 		<aui:validator name="required"/>
9 		<aui:validator name="alphanum"/>
10	</aui:input>
11	<aui:input name="firstName" >
12 		<aui:validator name="required"/>
13 		<aui:validator name="alpha"/>
14	</aui:input>
15	<aui:input name="lastName" >
16 		<aui:validator name="required"/>
17 		<aui:validator name="alpha"/>
18	</aui:input>
19	<aui:input name="contactNo" >
20 		<aui:validator name="required"/>
21 		<aui:validator name="string"/>
22	</aui:input>
23	<aui:input name="city">
24 		<aui:validator name="required"/>
25 		<aui:validator name="alpha"/>
26	</aui:input>
27
28	<aui:button type="submit" name="" value="Submit"></aui:button>
29</aui:form>

Output of add-student.jsp

Blog Image

7. Now implement the process action method to add student in database

1// StudentCrudPortlet.java //
2package com.ignek.student.portlet;
3
4@Component(
5          ...
6)
7public class StudentCrudPortlet extends MVCPortlet {
8	private Log log = LogFactoryUtil.getLog(this.getClass().getName());
9
10	@Reference
11	CounterLocalService counterLocalService;
12	@Reference
13	StudentLocalService studentLocalService;
14
15	@ProcessAction(name = "addStudent")
16	public void addStudent(ActionRequest actionRequest,ActionResponse actionResponse) {
17		long studentId = counterLocalService.increment(Student.class.getName());
18		String enrollmentNo = ParamUtil.getString(actionRequest, "enrollmentNo");
19		String firstName = ParamUtil.getString(actionRequest, "firstName");
20		String lastName = ParamUtil.getString(actionRequest, "lastName");
21		String contactNo = ParamUtil.getString(actionRequest, "contactNo");
22		String city = ParamUtil.getString(actionRequest, "city");
23
24		Student student = studentLocalService.createStudent(studentId);
25		student.setStudentId(studentId);
26		student.setEnrollmentNo(enrollmentNo);
27		student.setFirstName(firstName);
28		student.setLastName(lastName);
29		student.setContactNo(contactNo);
30		student.setCity(city);
31
32		studentLocalService.addStudent(student);
33	}
34}

8. Now override render method of portlet to fetch all students and send students list to view.jsp

1// StudentCrudPortlet.java //
2package com.ignek.student.portlet;
3
4@Component(
5    ...
6)
7public class StudentCrudPortlet extends MVCPortlet {
8
9	@Reference
10	StudentLocalService studentLocalService;
11
12	@Override
13	public void render(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException{
14		List<Student> studentList = studentLocalService.getStudents(QueryUtil.ALL_POS, QueryUtil.ALL_POS);
15		renderRequest.setAttribute("studentList", studentList);
16		super.render(renderRequest, renderResponse);
17	}
18}

9. Now add below code in view.jsp

1// view.jsp //
2<%@ include file="init.jsp"%>
3<portlet:defineObjects />
4
5<%  List<Student> studentList = (List<Student>)request.getAttribute("studentList"); %>
6<portlet:renderURL var="addStudentRenderURL">
7    <portlet:param name="mvcPath" value="/add-student.jsp"/>
8</portlet:renderURL>
9
10<div class="mb-5">
11    <a href="<%= addStudentRenderURL %>" class="btn  btn-primary btn-default">
12        <i class="glyphicon glyphicon-plus"></i> Add Student
13    </a>
14</div>
15<table class="table table-striped">
16    <tr >
17        <th>Enrollment No</th>
18        <th>First Name</th>
19        <th>Last Name</th>
20        <th>Contact No</th>
21        <th>City</th>
22        <th colspan="2" style="width: 100px">Action</th>
23    </tr>
24    <c:forEach items="${studentList}" var="student">
25
26        <portlet:renderURL var="updateStudentRenderURL">
27            <portlet:param name="mvcPath" value="/update-student.jsp"/>
28            <portlet:param name="enrollmentNo" value="${student.enrollmentNo}"/>
29            <portlet:param name="firstName" value="${student.firstName}"/>
30            <portlet:param name="lastName" value="${student.lastName}"/>
31            <portlet:param name="contactNo" value="${student.contactNo}"/>
32            <portlet:param name="city" value="${student.city}"/>
33            <portlet:param name="studentId" value="${student.studentId}"/>
34        </portlet:renderURL>
35
36        <portlet:actionURL name="deleteStudent" var="deleteStudentActionURL">
37            <portlet:param name="studentId" value="${student.getStudentId()}"/>
38        </portlet:actionURL>
39
40        <tr>
41            <td>${student.getEnrollmentNo()}</td>
42            <td>${student.getFirstName()}</td>
43            <td>${student.getLastName()}</td>
44            <td>${student.getContactNo()}</td>
45            <td>${student.getCity()}</td>
46            <td class="text-center" style="width: 50px">
47                <a href="<%=updateStudentRenderURL%>" class="btn  btn-primary btn-default btn-sm px-2 py-1" >
48                <i class ="glyphicon glyphicon-edit"></i>
49                </a>
50            </td>
51            <td class="text-center" style="width:50px">
52                <a href="<%=deleteStudentActionURL%>"
53                    class="btn  btn-primary btn-default btn-sm px-2 py-1"
54                    onclick="return confirm('Are you sure you want to delete this item?');">
55                    <i class ="glyphicon glyphicon-remove"></i>
56                </a>
57            </td>
58         </tr>
59    </c:forEach>
60</table>

Output of view.jsp

Blog Image

10. Now create update-student.jsp file in same directory as view.jsp. Add below code to update-student.jsp

1// update-student.jsp //
2<%@ include file="init.jsp"%>
3<portlet:defineObjects/>
4<portlet:actionURL name="updateStudent" var="updateStudentActionURL"/>
5<aui:form action="<%=updateStudentActionURL%>" name="studentForm" method="POST"/>
6
7<%
8	String studentId = renderRequest.getParameter("studentId");
9	String enrollmentNo = renderRequest.getParameter("enrollmentNo");
10	String firstName = renderRequest.getParameter("firstName");
11	String lastName = renderRequest.getParameter("lastName");
12	String contactNo = renderRequest.getParameter("contactNo");
13	String city = renderRequest.getParameter("city");
14%>
15<aui:form action="<%= updateStudentActionURL %>" method="post" >
16	<aui:input name="studentId" type="hidden" value="<%=Long.parseLong(studentId)%>"/>
17	<aui:input name="enrollmentNo" type="text" value="${student.enrollmentNo}"/>
18	<aui:input name="firstName" type="text" value="${student.firstName}"/>
19	<aui:input name="lastName" type="text" value="${student.lastName}" />
20	<aui:input name="contactNo" type="text" value="${student.contactNo}" />
21	<aui:input name="city" type="text" value="${student.city}"/>
22	<aui:input type="submit" value="Update" name="update"></aui:input>
23</aui:form>

Output of update-student.jsp

Blog Image

11. Now implement the process action methods for update and delete actions

1// StudentCrudPortlet.java //
2package com.ignek.student.portlet;
3
4@Component(
5    ...
6)
7public class StudentCrudPortlet extends MVCPortlet {
8    private Log log = LogFactoryUtil.getLog(StudentCrudPortlet.class);
9
10    @Reference
11    StudentLocalService studentLocalService;
12
13	@ProcessAction(name = "addStudent")
14    public void addStudent(ActionRequest actionRequest,ActionResponse actionResponse) {
15            ...
16	}
17	@ProcessAction(name = "updateStudent")
18    public void updateStudent(ActionRequest actionRequest,  ActionResponse actionResponse) {
19        long studentId = ParamUtil.getLong(actionRequest,"studentId", GetterUtil.DEFAULT_LONG);
20        String enrollmentNo = ParamUtil.getString(actionRequest, "enrollmentNo", GetterUtil.DEFAULT_STRING);
21        String firstName = ParamUtil.getString(actionRequest, "firstName", GetterUtil.DEFAULT_STRING);
22        String lastName = ParamUtil.getString(actionRequest, "lastName", GetterUtil.DEFAULT_STRING);
23        String contactNo = ParamUtil.getString(actionRequest, "contactNo", GetterUtil.DEFAULT_STRING);
24        String city = ParamUtil.getString(actionRequest, "city", GetterUtil.DEFAULT_STRING);
25
26        Student student = null;
27        try {
28            student = studentLocalService.getStudent(studentId);
29        } catch (Exception e) {
30            log.error(e.getCause(), e);
31        }
32
33        if(Validator.isNotNull(student)) {
34            student.setEnrollmentNo(enrollmentNo);
35            student.setFirstName(firstName);
36            student.setLastName(lastName);
37            student.setContactNo(contactNo);
38            student.setCity(city);
39            studentLocalService.updateStudent(student);
40        }
41    }
42 	@ProcessAction(name = "deleteStudent")
43    public void deleteStudent(ActionRequest actionRequest, ActionResponse actionResponse){
44        long studentId = ParamUtil.getLong(actionRequest, "studentId", GetterUtil.DEFAULT_LONG);
45        try {
46            studentLocalService.deleteStudent(studentId);
47        } catch (Exception e) {
48            log.error(e.getMessage(), e);
49        }
50    }
51}


Output of delete action

Blog Image

© 2026 IGNEK. All rights reserved.

Ignek on LinkedInIgnek on InstagramIgnek on FacebookIgnek on YouTubeIgnek on X