一.什么是Service Builder?
Service Builder是liferay IDE提供的一种代码生成方案,开发人员只需编辑一个数据库实体的描述文件(XML),即可根据XML文件生成Spring层代码、Hibernate层代码、SQL、SQL索引创建文件、Spring和Hibernate的配置文件等,可以提高开发效率
二.使用Service Builder
1.service.xml
<?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.sample.portlet.liferay">
<author>laiwanshan</author>
<namespace>Liferay</namespace>
<entity name="Book" local-service="true" remote-service="true">
<!-- PK fields -->
<column name="bookId" type="long" primary="true"/>
<!-- Group instance -->
<column name="groupId" type="long"/>
<!-- Audit fields -->
<column name="companyId" type="long"/>
<column name="userId" type="long"/>
<column name="userName" type="String"/>
<column name="createDate" type="Date"/>
<column name="modifiedDate" type="Date"/>
<!-- Other fields -->
<column name="title" type="String"/>
</entity>
</service-builder>
配置说明:
<service-builder package-path="com.sample.portlet.liferay">
依据这个配置生成目录
WEB-INF/src/com/sample/portlet/library/
<namespace>Liferay</namespace>
Table的前缀,表名为namespace_tablename
<entity name="Book" local-service="true" remote-service="true">
name即为表名;
local-service默认为false,设为true将自动生成本地接口;
remote-service默认为false,设为true将自动生成远程接口。
<column name="title" type="String"/>
column配置表中的字段
2.生成Service
![](http://static.oschina.net/uploads/space/2013/0125/204414_5HN9_589482.jpg)
点击按钮即自动生成相应的目录及文件
![](http://static.oschina.net/uploads/space/2013/0125/204740_DYKt_589482.jpg)
注意:生成了一大堆类,但,我们只需要关注这4个类
1)BookLocalServiceImpl:这个类中写我们自己的业务逻辑,添加新的方法
2)BookLocalServiceUtile:通过该类调用方法
3)BookServiceImpl:安全检测代码
4)BookImpl:添加方法
3.实现自己的方法
BookLocalServiceImpl类中添加新方法
public class BookLocalServiceImpl extends BookLocalServiceBaseImpl {
public Book addBook(long userId,String title)
throws PortalException,SystemException {
User user = UserUtil.findByPrimaryKey(userId);
Date now = new Date();
long bookId = CounterLocalServiceUtil.increment(Book.class.getName());
Book book = bookPersistence.create(bookId);
book.setTitle(title);
book.setCompanyId(user.getCompanyId());
book.setUserId(user.getUserId());
book.setCreateDate(now);
book.setModifiedDate(now);
return bookPersistence.update(book, false);
}
}
4.重新生成Servcie,步骤同2
5.调用自己的方法
ThemeDisplay themeDisplay =(ThemeDisplay)actionRequest.getAttribute("THEME_DISPLAY");
User u = themeDisplay.getUser();//取得当前用户
Book b = BookLocalServiceUtil.addBook(u.getUserId(), title);