Service builder is an automated tool to construct service and persistence layer in Liferay. We need to define business models (entities) and rest is taken care by service builder.
Service Builder is one of the most powerful, time saver, proven and peace of mind feature of Liferay.
what is Liferay Service Builder ?
Liferay provide nice way of creating service and persistence layer. Liferay Service Builder is a tool to create service-persistence layer in Liferay. It generates set of classes and interfaces which is used to interact with Database (CRUD operation). This way it saves development time of building service-persistence layer manually. You can refer my previous blog on Liferay Service Builder concept to get little more background bout it.
Liferay Service Builder uses Spring for providing Service layer implementation and Hibernate for persistence layer implementation. Both of these frameworks (Spring & Hibernate) are industry standard and proven to construct scale-able web applications.
Let us see how to develop service-persistence layer in liferay by simple example. First we need to create custom Liferay MVC Portlet.
Give project name as service-builder-test and eclipse will append -portlet at the end so that final project name will become service-builder-test-portlet.Create portlet class call called TestServiceBuilderPortlet under package com.opensource.techblog.portlet. Also update portlet class entry in portlet.xml file. After this the project structure will look like below screenshot.
We want to create service and persistence layer that will actually provide CRUD operations.
In Real life, the business objects are encapsulated by Entity classes. From an object-oriented perspective, an entity object represents an object in the real-world problem domain (Business Object). Each Business object will have attributes and behaviour (instance variable and methods in Object Oriented perspective).
In our case we will take Student as business object. In real world Student will have following attributes
- Father Name
- Mother Name
Service layer by Service Builder
Package Path :- the location where the generated service-persistence classes will resides.
Namespace :- Back end side, liferay will create SQL script for each entity. We can group the tables generated for entities by giving Name Space value.
- If we give Name space as education and if we defined 3 entities (soon we see how to define the entities) then there will be 3 tables created (each for individual entity).
- Name of these (3) tables will start with education_.
- Suppose the entities are Student, Marks and Leave then the corresponding table name would be education_student, education_marks and education_leave.
The generated Tables for each entities defined in service.xml file will have common namespace defined in that service.xml file
Author :- Name of the author who is going to create the services.
We can define multiple entity in service.xml. For simplicity, we took just one entity. Give the value for Package Name, Namespace and Author name as below.
Package path:- com.opensource.techblog.myservice
Author:- <<Your Name>> (I gave mine)
Click on Finish button. You will observe that a new file called service.xml will be created under WEB-INF folder as shown in below screenshot.
You can observe that the package-path, author and namespace will be defined as elements in service.xml. Now we will start defining our entity – Student. Add the following snippet (for Student entity) in service.xml file.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.0.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_0_0.dtd"> <service-builder package-path="com.opensource.techblog.myservice"> <author>nilang</author> <namespace>education</namespace> <entity name="Student" local-service="true" remote-service="false"> <column name="studentId" type="long" primary="true"/> <column name="name" type="String"/> <column name="age" type="int"/> <column name="fatherName" type="String"/> <column name="motherName" type="String"/> <column name="standard" type="int"/> </entity> </service-builder>
- Liferay service builder can generate local or remote or both types of services. Local service can be used by client code running in same VM(Virtual Machine) where liferay instance is running. Liferay also supports remote service which can be accessed as a web service (SOAP or JSON) over internet / intranet. In our case we have created Student entity by defining local-service as true and remote-service as false so it will generate only local service.
- Child elements of Student element’s are columns which exactly reflect the column in the DB table.
- Each column will have name and type. We can declare the primary key by giving primary=”true”. If more than one column defined as primary=”true” then compound key will be generated.
- The available column types are
- Blob etc.
go to command prompt up to service-builder-test-portlet and give command ant build-service. It should show the below text in console and at the end it will show the message “Build Successful”.
Now come back to the portlet in eclipse and right-click on project service-builder-test-portlet and click on Refresh. At this stage, the project structure looks like below screenshot.
You will observe that a few classes/files are added to the project as shown below screenshot. They all are related to the service-persistence layer. Let’s see all of them in detail.
As shown in the screenshot, the generated service classes are located at following two places
- Which contains util classes and interface.
- All the interface / classes resides under this location will be packed in JAR file. This jar file will be generated after each service build (through ant build-service command).
- So the interfaces and util classes can be available directly to outer world.
- which contains the implementation of interfaces defined under folder /WEB-INF/service/com/opensource/techblog/myservice.
- It will be part of class path (under src folder) and will not be directly available to outer word.
- StudentPersistence.java (under /WEB/INF/service/com/opensource/techblog/myservice)
- Student persistence interface which defines CRUD methods related to Student entity like create, remove, countAll, find, findAll etc
- StudentPersistenceImpl.java (under /WEB-INF/src/com/opensource/techblog/myservice)
- This is the implementation class, which implements StudentPersistence.
- StudentUtil.java (under /WEB/INF/service/com/opensource/techblog/myservice)
- This util class, which having the instance of StudentPersistenceImpl class
- local service interface for Student entity.
- local service implementation which implements StudentLocalService interface. Basic CRUD methods will be added by liferay service builder. If you want to add any additional service methods then must be added to this class.
- However you can’t directly access them from this class. You have to re-run the service builder (through ant build-service command) and service builder will create corresponding (same method signature) static method in StudentLocalSerivceUtil class. You can then access StudentLocalSeriviceUtil class which internally make call to corresponding (same signature) method of StudentLocalServiceImpl.
- This class implements StudentLocalSerivce interface and provides all basic CRUD methods. StudentLocalServiceImpl where we can define additional service methods extends this class.
- All service Impls and persistence Impls classes related to Student entity are injected into this class. Additionally, if you give reference to any other entity, it’s service impls and persistence impls classes are also injected in this class.
- The object of type StudentLocalServiceImpl is injected in StudentLocalServiceUtil class by Liferay service builder through spring injection. Out of all the above service classes, only this class is accessible to other API (outside of service layer) for CRUD operation.
- StuddentLocalServiceUtil has all static methods. Each method of StudentLocalServiceUtil will make a call to the corresponding (same signature) method in StudentLocalSerivceImpl class.
- Base model (interface) for Student.
- This interface and its corresponding implementation (StudentModelImpl) exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in (StudentImpl)
- Base model impl which implements StudentModel interface
- This implementation and its corresponding interface (StudentModel) exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in (StudentImpl).
- extends studentModel.java
- By default, there is no method defined.
- Whenever any new (custom) method added to StudentImpl, they will be added to this interface on the next service build.
- extends StudentBaseImpl.java.
- implements Student.java interface.
- Helper methods and all application logic should be put in this class.
- Whenever custom methods are added in this class, the corresponding methods will be added to the Student interface on the next service build.
Relations among Model interfaces / classes :-
Out of these model classes / interfaces, only StudentImpl.java is allowed to add additional (custom) methods at model level to developer. Relations among Service interfaces / classes :-
The following diagram shows the relation between service interface and classes
Out of these service classes / interfaces, only StudentLocalServiceImpl is allowed to add additional (custom) methods at service level to developer.
Relations among Persistence interfaces / classes :-
You will observe that this class have various CRUD methods like
- Liferay Service Builder concept
- Create Finder method for Service builder in Liferay
- Call service from one portlet to another portlet in liferay
- Service builder is used to create service and persistence layer in Liferay
- We need to define business model and service builder will take care for rest.
- Service builder creates set of service and persistence classes and interface.
- Go to Liferay documentation and search for Service Builder to get more idea.
51 Comments to “Creating Service layer in Service Builder in Liferay”
Nice very helpful to me…. Thanks nilang patel
at service layer I build two entities successfully and related table also created in Database but at third entity service builder run successfully but related entity table not created in Database. I am create table as manually in Database.Please help me.
Welcome to Techblog. Follow below steps
1) You need to build the service first and then have to deploy. Until you deploy, there won’t be any changes done on database side.
2) Are you using service-ext.properties file ? If yes, then you have to manually increase the build numbers, build the service and have to deploy it again to reflect your changes in DB.
By the way which Liferay version you are using ?
when i try to do building service error occures :”build fail” how to fix the error.
Hello Prasanna, pls give full log to analyze
Thanks you!!! 😀
Thanks for appreciation and welcome to Tech blog. Feel free to ask questions / give suggestions.
I tried and still things are not working 🙁 Do you have the complete war or rar file, which does the image upload to cusotm table in DB? I meant any working custom portlet. I am using Liferay 6.1.1 GA3 version with SDK version liferay-plugins-sdk-6.1.1
Currently, I don’t have any code ready. But I will try from my end and let you know or else write separate blog to upload images in liferay and will give you link to follow.
But I am wondering. Storing images in DB will create performance issues.Instead you can use document library api to store it in document library. Its very easy. Also Admin can manage uploaded images from document library portlet directly.
Thanks Nilang for the information. I was finally able to upload the images into DB using custom table 🙂 But now i want to display as slide images with description dynamically changing. I meant, if there are 10 images in DB, then all those images should run as slideshow with description changing accordingly in the custom portlet. So now iam finding how to retrieve the List of images and display on the page. Any inputs on how to get the list from DB? Should i use DynamicQuery in this case?
nice to hear you that you are able to save and retrieve images from DB. However, if your purpose it just to set up slideshow with those images, then your approach is not efficient. You can use Web content-structure and template to display slideshow and upload images in Document library which is more efficient and provide greater level of flexibility. Let me know if you need any further help on this.
Thanks a lot for your explanation. Really it helped me a lot. I have tried refreshing the project & still could not find those files. Actually i created the service.xml file manually and edited the contents and then ran the ant->build-service command in eclipse to build the jar (service-builder-test-portlet-service.jar) . When i extract the jar file, i could not find those files too. Ok let me try again.
To elaborate on my requirement, i am trying to create a custom table in existing liferay DB (say such as “customImage” table) wherein i will have imageFile (blob) and imageDescription (String) as columns so that i could insert first and then retrieve the content on view.jsp page. So as said i am trying to create this table using the above steps as mentioned in your blog. Am i in the right direction? Or is there any alternative for doing this in liferay? Kindly let me know.
You are on right direction. To be safer side, just delete all generated files / java classes by service builder,JAR file under portlet/lib folder ,sql script (under service folder under WEB-INF) from the project. Then re build service. Let me know if you still face any trouble by following it.
I was finally able to insert images into DB using custom table. In my case it was “PhotoImg” table with columns such as photoname (String), description (String), data (blob). Now i want to retrieve the content from DB, how to go about it? Iam using DynamicQuery like this, but it is not working.
DynamicQuery dq = DynamicQueryFactoryUtil.forClass(PhotoImg.class). addOrder(OrderFactoryUtil.desc(“photoname”));
Can you please point me how to retrieve the image and image contents using jsp ?
Thanks for all the steps mentioned for creating service layer. As pointed out by other person, i have a small query wrt classes built when i run ant build-service. I do not get these files either on local system (WEB-INF) or eclipse.
Am i missing out anything? Also afterr the ant build, i can see that the service-builder-test-portlet-service.jar generated under WEB_INF/lib folder. So how to proceed after this step? When will the table creation happen after this step (table education_student) ? I am new to liferay development, please help me.
First of all welcome to Tech blog and thanks for appreciations. The above said classed will be generated in respective folder, I mentioned in image no 6 (Starting form top). You need to refresh the project after service build. You can also verify from File system.
Liferay service builder will create service JAR which will be used to access service layer. When we build service, it will only generate tables SQL. Actual tables will be generated once we deploy the portelt first time after running service builder. Let me know if you need more information. I am planning to write separate blog soon on how to perform actual CRUD operation to save / update /delete data from page to DB. so stay tuned.
Feel free to ask questions / give suggestion.
This comment has been removed by a blog administrator.
gr8 blog u’ve written.
Welcome to Tech blog and thanks for appreciation. Feel free to ask questions / give feedback.
appreciate on this sort of blog
Thanks for appreciation and welcome to Tech blog, Feel free to ask questions / give suggestions
Your blogs are excellent. I dont think we can find any cleaner approach than this to explain writing code in liferay.
I recently started learning liferay and the requirement is to integrate it with Broadleaf (open source ecommerce framework). After much struggle i was able to place broadleaf related jars in a portlet and start the application without any exception.But the problem is that I need to use services created in Broadleaf in this portlet. The service i use in portlet always seems to be null no matter how ever I try to inject them.
Can you please post an example to show how to autowire/inject services available through jars in Spring MVC Portlet? Thanks in advance
Thanks for appreciation. The scenario you mentioned, I assume that you are putting Broadleaf’s JAR under lib folder of your portlet. If that JAR contains util class, it can be directly accessed from portlet class itself.
There is one more alternative for this. You can create liferay service builder. Refer my blog https://www.opensource-techblog.com/2013/03/creating-service-layer-in-service.html for the same. You can then create custom method in your XXXLocalServiceImpl class from where you can make call to Broadleaf’s Service.
If you need to access this JAR from more than one portlet, then you need to put those jars under / lib folder from where its accessible to all portlet / plugin.
You many need to point those jars in class path so that it won’t give any error while compiling portlet.
Let me know if you need any further assistance.
Just correction to above comment. In case you wish the JARs to be accessed by all portlets/plugin then you need to put that jar in lib folder of Tomcat
Thank you super man…gr8 post..:)
Thanks for appreciation and welcome to Tech blog. Feel free to ask questions / give suggestions.
I am new to Liferay i am referring all your blogs they are very very helpful for me.
please write one another blog on Form Portlet Development and View Portlet Development.
It seems you can put service.xml in the source code inside the package of your part, thus you can have many service.xml inside the same project !
First of welcome to Techblog. Actually its not possible to have more than one service.xml in one plugin project. I will sure check this and let you know
Nice article. I wish you explain more about the Service layer and what they do.
And there are some typos:
tern –> turn
outer word –> outer world (I guess)
is allow –> is allowed
Hi Nilang I am trying to study Liferay and with this example I am not sure on how to see the client side form that will try to get all the service working like an example of actual adding of Student from the JSP page to the Service Layer
Thanks for appreciation and welcome to Tech blog. I am planning to write separate blog called CRUD operation in Liferay with Service Builder. I am sure you will get all what you are searching for from next blog. I will let you know once its done.
Very good posts and very helpful in learning liferay.
I have a question,
I’m getting error”CreateProcess error=206, The filename or extension is too long” when i run the “ant build-service” command.I tried to shorten the name but still the problem persists.
Is there any alternate way to generate the entity classes, or how can we achieve the same using maven tools.
Thanks & Regards,
Thanks for appreciation and welcome to Tech blog. Can you please check whether you placed your plugin SDK under too long folder hieracthy. Ex. D:/Folder1/Folder2/Folder3/Folder4…../Folder20/Plugin-sdk. There is limitation of window os to put the restriction of folder hierarchy after certain limit.
You can recheck by putting plugin SDK just under drive (ex. d:/plugin-sdk) and re-build the potlet.
Nilang I Patel
ServiceBuilder could be very useful, but how can we generate services and entities in differents packages ?
isn’t aware about “package” attribute from children imports…
Thanks for writing to Tech blog. I understand that you wanted to know how to write different entities in different pacakge ?
The answer to this is, you can enter more that one entities in single package. Package is nothing but the generated Java package after the service get build.
Liferay service builder is designed to create one service xml file per portlet. (If they are in different plugin project). And hence you can add multiple entities under single pacakge. If you need to change the package, you need to create new service.xml file in different portlet.
Feel free to ask questions / give feedback
Thanks for all ur blogs.
i have a small question while following these steps i am not being able to see following classes after building the project-
Infact i cant see src folder inside /WEB-INF location.
I want know if i have missed some step to follow or if it’s something else.
Thanks for appreciation and welcome to Tech blog. Actually those classes will be inside service JAR file located under WEB-INF/lib folder.
Also if you are using eclipse then by default the src folder will be shown as Java source in eclipse. If you see actual file system, you will observe that the src folder will be under WEB-INF folder.
Let me know if you have any other queries
Welcome to Techblog and thanks for appreciation. Feel free to ask questions / give feedback
Thanks and Regards
Nilang I Patel
i am beginners.
it will me lot if attach source code
First of all welcome to Tech blog. For this blog, you can refer the thing what I have mentioned and all the code will be generating by liferay service builder. I can definitely put the source code, but for this blog, you can better understand the code if you follow all the steps mentioned here.
Nilang I Patel
can you attach source code?
Could you please do an example of crud with JSPs pages.
if you already have an example please share it.
I can give steps to achieve this. As per my blog, we need to user XXXLocalServiceUtil class for any CRUD operation. So you can do one thing. You can call this method in controller, get the list of models and pass to JSP. In JSP you can put the loop and from each model, you can show its attribute from its property.
Let me know if this is sufficient for you. If you feel difficulty, let me know I will create sample application and will share it with you.
Nilang I Patel
thanks for feedback, i hope if there is juste sample example to undersand things.
Current I don’t have such detailed sample example. But yes I can create it. Give me 1-2 days time. Will revert back.
Hi again Thanks for the effort and take your time.
The article for finder method is now available :- https://www.opensource-techblog.com/2013/03/create-finder-method-for-service.html
Thanks for appreciation. Sure I am going to write approx 5-6 other blogs related to Service builder which covers most of the things that required in day to day development.
Nice post…. It will help a lot to beginners… 1 suggestion you can also write a post for making the finder methods