---
title: "OpenJWeb平台数据库API调用手册(Spring+Hibernate)"
author: "cjc"
date: "2008-03-17T10:59:00Z"
tags: []
slug: "openjweb-api-spring-hibernate"
draft: false
lastmod: "2008-03-17T10:59:00Z"
id: 446897
url: "https://cjc.iteye.com/blog/446897"
---

**OpenJWeb平台数据库API调用手册**

**王保政**

**[Msn:baozhengw999@hotmail.com]()**

**QQ:29803446**

**一、 说明**

在OpenJWeb平台中主要使用Spring+Hibernate封装对数据库的访问。可使用ServiceLocator.getDBSupportService()获得一个数据库访问的业务逻辑对象。ServiceLocator是一个服务定位器，也可以说是大多数业务逻辑的门面类，getDBSupportService返回了一个IDBSupportService接口的实例，在此接口的实现类中封装了基于Hibernate的数据库访问。

在core-service.xml中这样配置IDBSupportService接口的一个bean实例:

&lt;?xml version="1.0" encoding="GB2312"?&gt;

&lt;beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"&gt;

**&lt;bean id="IDBSupportService" class="org.apache.easframework.core.service.impl.DBSupportServiceImpl"&gt;**

**&lt;constructor-arg&gt;&lt;ref local="IBaseDao"/&gt;&lt;/constructor-arg&gt;**

**&lt;/bean&gt;**

**&lt;bean id="INodeService" class="org.apache.easframework.core.service.impl.NodeServiceImpl"&gt;**

**&lt;constructor-arg&gt;&lt;ref local="IBaseDao"/&gt;&lt;/constructor-arg&gt;**

**&lt;/bean&gt;**

**&lt;bean id="IBaseDao" class="org.apache.easframework.core.dao.impl.DBSupportDaoImpl"&gt;**

**&lt;property name="hibernateTemplate"&gt;**

**&lt;ref bean="hibernateMysqlTemplate"/&gt;**

**&lt;/property&gt;**

**&lt;/bean&gt;**

&lt;!-- Timer Schedule config start --&gt;

&lt;!-- defime a business timer object--&gt;

&lt;bean id="EAITimerBean" class="org.openjweb.common.timer.JobSchedule"/&gt;

&lt;!--defime which method of class to be called in timer schedule --&gt;

&lt;bean id="EAITimerMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"&gt;

&lt;property name="targetObject" ref="EAITimerBean" /&gt;

&lt;property name="targetMethod" value="doTimerSchedule" /&gt;

&lt;property name="concurrent" value="false" /&gt; &lt;!--将并发设置为false--&gt;

&lt;/bean&gt;

&lt;!-- 设置定时器 --&gt;

&lt;bean id="eaiTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"&gt;

&lt;property name="jobDetail" ref="EAITimerMethod" /&gt;

&lt;!--每两分钟触发--&gt;

&lt;property name="cronExpression" value="0 1/2 * * * ?" /&gt;

&lt;/bean&gt;

&lt;bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"&gt;

&lt;property name="triggers"&gt;

&lt;list&gt;

&lt;!--EAI调度器,list下可加入其他的调度器--&gt;

&lt;ref bean="eaiTrigger"/&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;/bean&gt;

&lt;!-- Timer Schedule config end --&gt;

&lt;/beans&gt;

**二、 ServiceLocator服务定位器**

凡新增加的业务逻辑层的调用，都可以在这里注册声明一个业务逻辑接口的调用，在上文的core-service.xml中对应添加的声明来配置一个bean,下面是serviceLocator的代码：

package org.apache.easframework.core.service;

import org.apache.log4j.Logger;

import org.openjweb.common.IMailService;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.apache.easframework.core.service.ISysConfig;

public class ServiceLocator {

private static final Logger log = Logger.getLogger(ServiceLocator.class);

private static ApplicationContext context;

public static final ServiceLocator thisService = new ServiceLocator(); //单例类

private static final String\[] xmlFiles = new String\[] {

"/core-service.xml", "/datasource.xml" ,"/system-config.xml","/mailServer.xml"};

//public static ServiceLocator getInstance()

//{

// return thisService;

//}

public static IMailService getMailService()

{

String beanName = "IMailService";

IMailService service = null;

try

{

service = (IMailService) getBeanService(beanName);

}

catch(Exception ex)

{

ex.printStackTrace();

System.out.println("接口转换异常!");

}

return service;

}

/\**

\* 系统配置组件

\*

\* @return

\*/

public static ISysConfig getSysConfigService() {

String beanName = "ISysConfig";

ISysConfig service = (ISysConfig) getBeanService(beanName);

return service;

}

public static INodeService getNodeService()

{

String beanName ="INodeService";

INodeService service = (INodeService)getBeanService(beanName);

return service;

}

public static IDBSupportService getDBSupportService() {

**String beanName = "IDBSupportService"; // IDBSupportService****对应core-service.xml中的bean id,此xml文件中配置的IDBSupportService的实现类是org.apache.easframework.core.service.impl.DBSupportServiceImpl**

IDBSupportService service = (IDBSupportService) getBeanService(beanName);

return service;

}

private static IService getBeanService(String serviceName) {

IService bean = null;

try {

if (context == null) {

context = new ClassPathXmlApplicationContext(xmlFiles);

}

bean = (IService) context.getBean(serviceName);

} catch (Exception e) {

log.error("获取Service Bean对象失败！");

log.error(e.getMessage());

e.printStackTrace();

}

return bean;

}

}

在JSP,控制层，业务逻辑层，都可以使用ServiceLocator.getDBSupportService()的格式来调用增删改查等方法。

**三、** **如何使用ServiceLocator.getDBSupportService调用数据库相关的API:**

3．1、AbstractEntity抽象实体类

本平台所有的数据库实体类都继承了org.apache.easframework.core.entity. AbstractEntity,这样在增删改查过程中通过实体传递参数时，只需要传递一个AbstractEntity类型的变量，不要传递具体类变量，这样就保证了所有的实体类都可以使用相同的调用方法。AbstractEntity的代码如下：

package org.apache.easframework.core.entity;

import java.io.Serializable;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

/\**

\* 基础抽象实体类

\* @author bzwang

\*

\*/

public abstract class AbstractEntity implements Serializable

{

/\**

\* 在列表页面显示的记录行号,注意设计表时注意表字段映射后的列名不要与这个重复

\*/

protected long lr = -1;

protected String rowId="";

private String createDt;

private String createUid;

private String updateDt;

private String updateUid;

private String objId;

private String treeCode;//用于树形的实体

public void setTreeCode(String code)

{

this.treeCode = code;

}

public String getTreeCode()

{

return this.treeCode;

}

public void setObjId(String id)

{

this.objId = id;

}

public String getObjId()

{

return this.objId;

}

public void setR(long lr)

{

this.lr = lr;

}

public long getR()

{

return this.lr;

}

public void setRowId(String rowId)

{

this.rowId = rowId;

}

public String getRowId()

{

return this.rowId;

}

public String getCreateDt() {

return this.createDt;

}

public void setCreateDt(String createDt) {

this.createDt = createDt;

}

public String getCreateUid() {

return this.createUid;

}

public void setCreateUid(String createUid) {

this.createUid = createUid;

}

public String getUpdateDt() {

return this.updateDt;

}

public void setUpdateDt(String updateDt) {

this.updateDt = updateDt;

}

public String getUpdateUid() {

return this.updateUid;

}

public void setUpdateUid(String updateUid) {

this.updateUid = updateUid;

}

public Object getFieldValueByName(String fieldName) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException

{

Object obj = null;

String methodName = "get"+fieldName.toUpperCase().substring(0,1)+fieldName.substring(1);

System.out.println("AbstractEntity中计算的方法名:"+methodName);

System.out.println("类名："+this.getClass().getName());

Method method = null;

method = this.getClass().getMethod(methodName, null);

obj = method.invoke(this, null);

return obj;

}

/\**

\* 为指定的字符串类型的列赋值,此方法暂未测试

\* @param fieldName

\* @param fieldValue

\* @throws SecurityException

\* @throws NoSuchMethodException

\* @throws IllegalArgumentException

\* @throws IllegalAccessException

\* @throws InvocationTargetException

\*/

public void setProperty(String fieldName,String fieldValue) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException

{

String methodName="set"+fieldName.toUpperCase().substring(0,1)+fieldName.substring(1);

Method method = null;

method = this.getClass().getMethod(methodName,new Class\[]{String.class});

method .invoke(this, new Object\[]{fieldValue});

}

}

3．2、增删改查示例

以Blog(博客)表为例，表名cms\_blog,对应的实体类为CmsBlog.java实体类的代码:

package org.apache.easframework.core.entity;

/\**

This POJO generated by OpenJWeb - Hibernate Tools

\*/

public class CmsBlog extends org.apache.easframework.core.entity.AbstractEntity implements java.io.Serializable {

//….

}

**插入实例：**

在JSP文件中使用增加一个实体类:

&lt;%@ page contentType="text/html; charset=GBK"%&gt;

&lt;%@ page import="org.apache.easframework.core.service.\*"%&gt;

&lt;%@ page import="org.apache.easframework.core.entity.\*"%&gt;

&lt;%@ page import="org.apache.easframework.common.StringUtil"%&gt;

&lt;%

CmsBlog entity = **new** CmsBlog();

entity.setObjId(StringUtil.*getUUID*());//创建唯一ID

entity.setBlogName("梦之城");

entity.setBlogClass("CMS");

entity.setRowId(StringUtil.*getUUID*());//创建唯一行号

**try**

{

ServiceLocator.*getDBSupportService*().insert(entity,**null**);

System.*out*.println("成功!");

}

**catch**(Exception ex)

{

System.*out*.println("----------------");

ex.printStackTrace();

System.*out*.println("----------------");

}

%&gt;

上面也可以使用saveOrUpdate来替代insert,saveOrUpdate既支持增加实体，又支持修改实体:

ServiceLocator.getDBSupportService().saveOrUpdate(entity,null);

**修改实例:**

**try**

{

CmsBlog entity =(CmsBlog)ServiceLocator.*getDBSupportService*().findById("org.apache.easframework.core.entity.CmsBlog",