ofbiz框架入门例子详解(首篇)-------插入篇

来源:互联网 发布:.sit域名 无法备案 编辑:程序博客网 时间:2024/06/05 18:31

目前在一家公司实习,该公司用的是ofbiz框架,我便放下SSH,投身上ofbiz的学习上去,一开始是很抵触的,但是学着学着发现其实框架道理是相似的,为了将代码解耦,每个框架都有自己的独特解耦之道和精妙之处,万事开头难,所以不要轻易放弃。


熟悉了一周大概摸清了ofbiz的轮廓,顺手开发一个ofbiz入门的例子(对user的增删改查,以及分页展示)

开发过程中也遇到了很多问题,经过一番推敲,已经摸到问题的缘由,之后会有介绍


列出一个目录:关于ofbiz框架的crud以及分页都是简单的demo供入门者学习一下

  • 增:其实就是本篇博文
  • 删:ofbiz框架入门例子---删除篇
  • 改:ofbiz框架入门例子---修改篇
  • 查:ofbiz框架入门例子---查询篇
  • 分页:ofbiz框架入门例子---分页篇

(原创作品,请勿抄袭)


下面进入正题:

开发环境:jdk6+mysql5.5+ofbiz9+eclipse

首先,安装好ofbiz,把数据库配置到本地mysql,可用参照:配置ofbiz连接本地mysql

  • 创建component

配置好之后,可以开始进行开发了,将ofbiz项目的build.xml添加到eclipse中的ant面板                                                                                                                                                   

点击create-component,会出现一些对话框,分别是component-name,component-resource-name,webapp-name,base permission,confirm 


  • 创建好component后,可以进行开发了

在数据库中建好user表,在你的component根目录里找到entitydef目录下的entitymodel.xml(该文件是配置entity实体类,与数据库中的表对应)


user表:

字段名 类型 长度   是否主键 idint10Yusernamevarchar50Npasswordvarchar50Nnicknamevarchar50Nregisterdatedatetime0N

配置entity:

<entity entity-name="User" package-name="com.model.user" title="" copyright="" author=""             version="">        <field name="id" type="numeric"></field>        <field name="username" type="short-varchar"></field>        <field name="password" type="short-varchar"></field>        <field name="nickname" type="short-varchar"></field>        <field name="registerdate" type="date-time"></field>        <prim-key field="id"/>    </entity>


  • 配置entity,entitygroup,datasource

配好entity后,还需修改entitydef目录entitymodel.xml文件(创建一个entity-group),把entity附属到这个group中,在ofbiz-component.xml注册这个group配置文件然后在entityengine.xml配置好entity-group与datasource的映射,使entity-group和datasource对应起来,这样在java类中就可以操作user表了

在entitygroup.xml配置文件中<entitygroup>标签中添加一句:

<entity-group group="com.model.user" entity="User"/>

在entityengine.xml文件中的default delegator中配置entitygroup与datasource的映射

<group-map group-name="com.model.user" datasource-name="helloworld"/>

datasource:

<datasource name="helloworld"                helper-class="org.ofbiz.entity.datasource.GenericHelperDAO"                field-type-name="mysql"                check-on-start="true"                add-missing-on-start="true"                check-pks-on-start="true"                use-foreign-keys="true"                join-style="ansi-no-parenthesis"                alias-view-columns="true"                drop-fk-use-foreign-key-keyword="true"                table-type="InnoDB"                character-set="utf8"                collate="utf8_general_ci">        <read-data reader-name="seed"/>        <read-data reader-name="seed-initial"/>        <read-data reader-name="demo"/>        <read-data reader-name="ext"/>        <inline-jdbc                jdbc-driver="com.mysql.jdbc.Driver"                jdbc-uri="jdbc:mysql://localhost/helloworld?autoReconnect=true&useUnicode=true&characterEncoding=utf8"                jdbc-username="root"                jdbc-password="root"                isolation-level="ReadCommitted"                pool-minsize="2"                pool-maxsize="250"/>    </datasource>

现在,已经java类中可以操作User表了


  • 编写java类,(event和service)

在src目录下创建UserService.java和UserEvent.java(分别放在com.service和com.event包下)

这里的service和event中的方法必须是static的否则会报错,请参考:ofbiz调用服务报错

UserService.java

public class UserService {public static Map<String, Object> registerUser(DispatchContext ctx, Map<String, ? extends Object> context){<span style="white-space:pre"></span><span style="white-space:pre"></span>Map<String, Object> result = ServiceUtil.returnSuccess();<span style="white-space:pre"></span><span style="white-space:pre"></span> //取得实体引擎实例       <span style="white-space:pre"></span>GenericDelegator delegator = ctx.getDelegator();        <span style="white-space:pre"></span>        //创建一条Uom记录的对象        <span style="white-space:pre"></span>GenericValue user = delegator.makeValue("User");<span style="white-space:pre"></span>user.set("username", context.get("username"));<span style="white-space:pre"></span>user.set("password", context.get("password"));<span style="white-space:pre"></span>user.set("nickname", context.get("nickname"));<span style="white-space:pre"></span>//取得当前时间戳<span style="white-space:pre"></span>Timestamp currentTime = UtilDateTime.nowTimestamp();<span style="white-space:pre"></span>user.set("registerdate", currentTime);<span style="white-space:pre"></span><span style="white-space:pre"></span><span style="white-space:pre"></span>try {<span style="white-space:pre"></span>//插入数据<span style="white-space:pre"></span>user.create();<span style="white-space:pre"></span>} catch (GenericEntityException e) {<span style="white-space:pre"></span>e.printStackTrace();<span style="white-space:pre"></span><span style="white-space:pre"></span>return ServiceUtil.returnFailure();<span style="white-space:pre"></span>}<span style="white-space:pre"></span><span style="white-space:pre"></span>return result;<span style="white-space:pre"></span>}}

UserEvent.java

public class UserEvent {//方法必须是static public static String register(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {<span style="white-space:pre"></span> <span style="white-space:pre"></span> LocalDispatcher dispatcher = (LocalDispatcher) req.getAttribute("dispatcher");<span style="white-space:pre"></span> Map<String, Object> results = null;<span style="white-space:pre"></span> Map<String, Object> contexts = UtilMisc.toMap();<span style="white-space:pre"></span> //从请求中得到参数<span style="white-space:pre"></span> String username = req.getParameter("username");<span style="white-space:pre"></span> String password = req.getParameter("password");<span style="white-space:pre"></span> String nickname = req.getParameter("nickname");<span style="white-space:pre"></span> //判断参数是否为空<span style="white-space:pre"></span> username = username == null || "".equals(username) ? "test" : username;<span style="white-space:pre"></span> password = password == null || "".equals(password) ? "test" : password;<span style="white-space:pre"></span> nickname = nickname == null || "".equals(nickname) ? "test" : nickname;<span style="white-space:pre"></span> //contexts为传入service的参数列表<span style="white-space:pre"></span> contexts.put("username", username);<span style="white-space:pre"></span> contexts.put("password", password);<span style="white-space:pre"></span> contexts.put("nickname", nickname);<span style="white-space:pre"></span> <span style="white-space:pre"></span> try {<span style="white-space:pre"></span> //调用注册的service<span style="white-space:pre"></span> results = dispatcher.runSync("registerUser", contexts);<span style="white-space:pre"></span> <span style="white-space:pre"></span> } catch (GenericServiceException e) {<span style="white-space:pre"></span>e.printStackTrace();<span style="white-space:pre"></span>return "error";<span style="white-space:pre"></span> }<span style="white-space:pre"></span> <span style="white-space:pre"></span> return "success";<span style="white-space:pre"></span> } }


  • 配置service和event

service.xml

<service name="registerUser" engine="java" location="com.diyagea.service.UserService" invoke="registerUser">    <span style="white-space:pre"></span><!-- INOUT输入输出参数 --><span style="white-space:pre"></span><attribute name="username" mode="IN" type="String" optional="false"/><span style="white-space:pre"></span><attribute name="password" mode="IN" type="String" optional="false"/><span style="white-space:pre"></span><attribute name="nickname" mode="IN" type="String" optional="false"/><span style="white-space:pre"></span><!-- OUT输出参数 --><span style="white-space:pre"></span><attribute name="result" mode="OUT" type="java.util.Map" optional="true"/><span style="white-space:pre"></span></service>

controller.xml中配置request-map

<request-map uri="register">    <span style="white-space:pre"></span><security https="true" auth="false"/>    <span style="white-space:pre"></span><event type="java" path="com.diyagea.event.UserEvent" invoke="register"></event>    <span style="white-space:pre"></span><response name="success" type="request-redirect" value="show"/>    </request-map>

这里的response是返回数据的时候映射到view层的配置,对应着<view-map>


  • 配置和编写view层

注册的view

<view-map name="registerPage" type="screen" page="component://test/widget/testScreens.xml#register"/>

<screen name="register">        <section>            <actions>            <property-map resource="testUiLabels" map-name="uiLabelMap" global="true"/>            </actions>            <widgets>                <platform-specific>                    <html>                        <html-template location="component://test/webapp/test/page/register.ftl"/>                    </html>                </platform-specific>                            </widgets>        </section>    </screen>

register.ftl

<body><form action="register" method="post"><table border="1"><tr><td>username</td><td><input type="text" id="username" name="username" /></td></tr><tr><td>password</td><td><input type="text" id="password" name="password" /></td></tr><tr><td>nickname</td><td><input type="text" id="nickname" name="nickname" /></td>    <tr>  <td><input type="submit" value="submit" /></td>  </tr></table></form>




显示结果的view

<view-map name="showUser" type="screen" page="component://test/widget/testScreens.xml#show"/>


这里映射到screen中的show组件
<screen name="show">        <section>            <actions>            </actions>            <widgets>                <platform-specific>                    <html>                        <html-template location="component://test/webapp/test/page/show.ftl"/>                    </html>                </platform-specific>                            </widgets>        </section>    </screen>

这里只是简单的screen直接对应到show.ftl


show.ftl

<!DOCTYPE html PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>hello world.</title></head><body>${request.getAttribute("mes")?default("")}    <table border="1"><tr><td>username</td><td>password</td><td>pickname</td><td>registerDate</td></tr><#assign users = request.getAttribute("users")?if_exists><#list users as user>  <tr><td>${user.username}</td><td>${user.password}</td>  <td>${user.nickname}</td>  <td>${user.registerdate}</td>  <tr>  </#list></table></body></html>

freemaker不再过多解释


在user表中添加两条数据


运行结果截图:









0 0
原创粉丝点击