四、spring集成ibatis进行项目中dao层基类封装
Apache iBatis(现已迁至Google Code下发展,更名为MyBatis)是当前IT项目中使用很广泛的一个半自动ORM框架,区别于Hibernate之类的全自动框架,iBatis对数据库的操作拥有更加灵活的控制,对于那些经常需要调用本地数据库函数自定义SQL语句,或是喜欢自己优化SQL执行效率的开发者来说,iBatis是一个非常不错的选择。而得到广泛应用的开源企业架构SpringFramework,也很好的将其进行了集成,使得iBatis在 SpringFramework中的使用更加便利、快捷。开发者所要做的就是继承SpringFramework中提供的SqlMapClientDaoSupport类即可。下面将简单介绍使用spring中集成的ibatis进行项目中dao层基类封装,以方便开发。
1、SqlMapClientFactoryBean 的装配
SqlMapClientFactoryBean是SqlMapClientTemplate使用的基础,如果在SpringFramework应用中没有装配SqlMapClientFactoryBean,那么SqlMapClientTemplate将不可用,报空指针错误。其配置信息如下:(关于数据源、事务管理、url拦截器等更多配置请参看博文https://www.cnblogs.com/jiarui-zjb/p/8710361.html)
<bean id="sqlMapClient"
class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<!-- iBatis sqlmap config 文件位置 -->
<property name="configLocation">
<value>
/WEB-INF/classes/org/bussiness/config/ibatis/SqlMapConfig.xml
</value>
</property>
<!-- 在SpringFramework配置文件中使用的数据源 -->
<property name="dataSource">
<ref local="dataSource" />
</property>
<!-- 如果需要读写Lob字段,需要注入在SpringFramework配置文件中配置好的Handler,这里是Oracle的数据库 -->
<property name="lobHandler" ref="oracleLobHandler"/>
</bean>
2、继承使用SqlMapClientDaoSupport类
2.1)首先定义一个IBaseDao接口提供各种场景的查询、修改、删除、分页查询的各种抽象功能方法
package org.biframework.dao.ibatis;
import com.ibatis.common.util.PaginatedList;
import java.util.List;
import org.biframework.exception.DaoException;
public abstract interface IBaseDao
{
public abstract Object getObject(String paramString, Object paramObject)
throws DaoException; @SuppressWarnings("unchecked")
public abstract List getList(String paramString, Object paramObject)
throws DaoException; public abstract PaginatedList getPgntList(String paramString1, Object paramObject, String paramString2)
throws DaoException; public abstract PaginatedList getPgntList(String paramString1, Object paramObject, String paramString2, int paramInt)
throws DaoException; @SuppressWarnings("unchecked")
public abstract List getListUseSameStmt(String paramString, Object[] paramArrayOfObject)
throws DaoException; public abstract int update(String paramString, Object paramObject)
throws DaoException; public abstract int transUpdateSameOpt(String paramString, Object[] paramArrayOfObject)
throws DaoException; public abstract int transUpdate(Object[][] paramArrayOfObject)
throws DaoException; @SuppressWarnings("unchecked")
public List getList(String statementName, Object parameterObject,
int skipResults, int maxResults) throws DaoException;
}
备注:该层也可以不写
2.2)继承使用SqlMapClientDaoSupport类并实现IBaseDao接口
package org.biframework.dao.ibatis;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.biframework.exception.DaoException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.ibatis.common.util.PaginatedList; public class BaseDao extends SqlMapClientDaoSupport implements IBaseDao { @SuppressWarnings("unused")
private static Log log;
protected static final int PAGE_SIZE = 15;
@SuppressWarnings("unchecked")
static Class class$0; /* synthetic field */ public BaseDao() {
}
/*
使用spring中集成的ibatis实现数据的查询、修改、删除
1)当请求参数被封装为一个普通对象,查询结果为List集合:
使用queryForList返回List 源码方法如下:getSqlMapClientTemplate(),获取SqlMapClientTemplate对象,
参数说明:a、statementName sql声明;b、parameterObject请求参数对象 queryForList方法源码如下
public List queryForList(String statementName, Object parameterObject)
throws DataAccessException
{
executeWithListResult(new SqlMapClientCallback()
{
private final String val$statementName;
private final Object val$parameterObject;
public Object doInSqlMapClient(SqlMapExecutor executor)
throws SQLException
{
return executor.queryForList(this.val$statementName, this.val$parameterObject);
}
});
}
*/
@SuppressWarnings("unchecked")
public List getList(String statementName, Object parameterObject)
throws DaoException {
List list = getSqlMapClientTemplate().queryForList(statementName,
parameterObject);
return list;
} /*
2)当请求参数被封装为一个数组对象时:
即使用数组存放多个传参对象(obj1、obj2...)而后使用相同sql,进行多次查询,将多次查询的结果list1、list2...放到结果集List中)
使用queryForList返回List 封装的方法如下:
*/
@SuppressWarnings("unchecked")
public List getListUseSameStmt(String statementName, Object objectParam[])
throws DaoException {
List list = null;
List temp = null;
if (statementName == null || objectParam == null|| objectParam.length == 0){
return list;
}else{
for (int i = 0; i < objectParam.length; i++) {
if (list == null){
list = new ArrayList();
temp = getSqlMapClientTemplate().queryForList(statementName,objectParam[i]);
}
if (temp != null){
list.addAll(temp);
}
}
}
return list;
} /*
3)当请求参数被封装为一个普通对象,查询结果为Object对象
*/
@SuppressWarnings("unchecked")
public Object getObject(String statementName, Object parameterObject)
throws DaoException {
Object result = null;
List list = getSqlMapClientTemplate().queryForList(statementName,parameterObject);
if (list != null && list.size() > 0){
result = list.get(0);
}
return result;
} /*
4)ibatis-common-2.jar、使用ibatis自身封装的PaginatedList工具类进行分页查询,每页15条数据。
public PaginatedList queryForPaginatedList(String statementName, Object parameterObject, int pageSize)
throws DataAccessException
{
if (((this.sqlMapClient instanceof ExtendedSqlMapClient)) && (((ExtendedSqlMapClient)this.sqlMapClient).getDelegate().getTxManager() == null)) {
throw new InvalidDataAccessApiUsageException("SqlMapClient needs to have DataSource to allow for lazy loading - specify SqlMapClientFactoryBean's 'dataSource' property");
}
(PaginatedList)execute(new SqlMapClientCallback()
{
private final String val$statementName;
private final Object val$parameterObject;
private final int val$pageSize; public Object doInSqlMapClient(SqlMapExecutor executor)
throws SQLException
{
return executor.queryForPaginatedList(this.val$statementName, this.val$parameterObject, this.val$pageSize);
}
});
}
*/
public PaginatedList getPgntList(String statementName,
Object parameterObject, String pageDirection) throws DaoException {
PaginatedList list = getSqlMapClientTemplate().queryForPaginatedList(
statementName, parameterObject, 15);
if ("next".equals(pageDirection))
list.nextPage();
else if ("previous".equals(pageDirection))
list.previousPage();
else if ("first".equals(pageDirection))
list.isFirstPage();
else if ("last".equals(pageDirection))
list.isLastPage();
return list;
} /*
4)自己指定分页查询的数量
*/
public PaginatedList getPgntList(String statementName,
Object parameterObject, String pageDirection, int pageSize)
throws DaoException {
PaginatedList list = getSqlMapClientTemplate().queryForPaginatedList(
statementName, parameterObject, pageSize);
if ("next".equals(pageDirection)) {
System.out.println("下一页");
list.nextPage();
} else if ("previous".equals(pageDirection)) {
System.out.println("上一页");
list.previousPage();
} else if ("first".equals(pageDirection)) {
System.out.println("首页");
list.isFirstPage();
} else if ("last".equals(pageDirection)) {
System.out.println("末页");
list.isLastPage();
}
return list;
} /*
5)该方法暂时未理解其主要是处于何种场景使用
*/
public int update(String statementName, Object parameterObject)
throws DataAccessException
{
Integer result = (Integer)execute(new SqlMapClientCallback()
{
private final String val$statementName;
private final Object val$parameterObject;
public Object doInSqlMapClient(SqlMapExecutor executor)
throws SQLException
{
return new Integer(executor.update(this.val$statementName, this.val$parameterObject));
}
});
return result.intValue();
}
*/
public int transUpdate(Object statementAndparameter[][])
throws DaoException {
Object statements[] = statementAndparameter[0];
Object parameters[] = statementAndparameter[1];
int result = 0;
for (int i = 0; i < statements.length; i++) {
String name = (String) statements[i];
Object param = parameters[i];
result += getSqlMapClientTemplate().update(name, param);
}
return result;
} /*
6)请求参数被封装为一个数组对象,返回结果为成功更新的记录数使用spring封装的update方法进行更新操作
*/
public int transUpdateSameOpt(String statementName, Object objectParam[])
throws DaoException {
int result = 0;
if (statementName == null || objectParam == null
|| objectParam.length == 0)
return result;
for (int i = 0; i < objectParam.length; i++)
result += getSqlMapClientTemplate().update(statementName,
objectParam[i]);
return result;
}
/*
7)请求参数被封装为一个普通对象,返回结果为成功更新的记录数
*/
public int update(String statementName, Object parameterObject)
throws DaoException {
int result = getSqlMapClientTemplate().update(statementName,
parameterObject);
return result;
} static {
log = LogFactory.getLog(org.biframework.dao.ibatis.BaseDao.class);
} /*
8)请求参数被封装为一个普通对象,并对查询的结果记录指定跳跃数和最大结果集
*/
@SuppressWarnings("unchecked")
public List getList(String statementName, Object parameterObject,
int skipResults, int maxResults) throws DaoException {
return getSqlMapClientTemplate().queryForList(statementName,
parameterObject, skipResults, maxResults);
}
}
3、进行dao层配置,并进行查询等操作
3.1)所有的dao层都继承BaseDao类
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.biframework.dao.ibatis.BaseDao;
import org.biframework.exception.DaoException;
import org.bussiness.product.detailquery.bo.StPolicyBean; public class StPolicyDao extends BaseDao {
protected static Log log = LogFactory.getLog(StPolicyDao.class); @SuppressWarnings("unchecked")
public List getStPerm(StPBean param) throws DaoException{
return super.getList("getShortPrem", param);
} public Object getStPermCount(StPBean param) throws DaoException{
return super.getObject("getShortPremCount", param);
}
}
}
3.2)进行dao装配 detailQuery-applicationContext.xml
<bean id="nstpDao" class="org.bussiness.product.detailquery.dao.NstPolicyDao">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="sqlMapClient">
<ref bean="sqlMapClient" />
</property>
</bean>
参看博文:http://sharkl.iteye.com/blog/745615
四、spring集成ibatis进行项目中dao层基类封装的更多相关文章
- salesforce 零基础学习(四十八)自定义列表分页之Pagination基类封装 ※※※
我们知道,salesforce中系统标准列表页面提供了相应的分页功能,如果要使用其分页功能,可以访问http://www.cnblogs.com/zero-zyq/p/5343287.html查看相关 ...
- Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作
Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作 1>. 创建一个控制台程序2>. 添加一个 ADO.NET实体数据模型,选择对应的数据库与表(Studen ...
- 设计模式(一)单例模式:创建模式 ASPNET CORE WEB 应用程序的启动 当项目中 没有STARTUP.CS 类如何设置启动 配置等等
设计模式(一)单例模式:创建模式 先聊一下关于设计的几个原则(1)单一原则(SRP):一个类应该仅有一个引起它变化的原因 :意思就是 (一个类,最好只负责一件事情,并且只有一个引起它变化的原因(2)开 ...
- C++派生类中如何初始化基类对象(五段代码)
今天收到盛大的面试,问我一个问题,关于派生类中如何初始化基类对象,我在想派生类对于构造函数不都是先构造基类对象,然后在构造子类对象,但是如果我们在成员初始化列表先初始化派生类的私有成员,在函数内去调用 ...
- moviepy音视频剪辑:moviepy中的剪辑基类Clip的属性和方法详解
专栏:Python基础教程目录 专栏:使用PyQt开发图形界面Python应用 专栏:PyQt+moviepy音视频剪辑实战 专栏:PyQt入门学习 老猿Python博文目录 老猿学5G博文目录 一. ...
- 【转载】 C++多继承中重写不同基类中相同原型的虚函数
本篇随笔为转载,原文地址:C++多继承中重写不同基类中相同原型的虚函数. 在C++多继承体系当中,在派生类中可以重写不同基类中的虚函数.下面就是一个例子: class CBaseA { public: ...
- Spring Scope:Web项目中如何安全使用有状态的Bean对象?
Web系统是最常见的Java应用系统之一,现在流行的Web项目多使用ssm或ssh框架,使用spring进行bean的管理,这为我们编写web项目带来了很多方便,通常,我们的controler层使用注 ...
- IoC之Spring.Net在Mvc项目中的使用
MVC中使用Spring.net 前面学习了使用Autofac来实现控制反转,这里简单记录Spring.Net实现IoC和DI的步骤 第一步:安装如下Nuget包 (Spring.Web.Mvc) i ...
- 【redis】3.Spring 集成注解 redis 项目配置使用
spring-data-redis 项目,配合 spring 特性并集成 Jedis 的一些命令和方法. 配置redis继承到spring管理项目,使用注解实现redis缓存功能. 参考:http: ...
随机推荐
- ASP.NET Core搭建多层网站架构【10-使用JWT进行授权验证】
2020/01/31, ASP.NET Core 3.1, VS2019, Microsoft.AspNetCore.Authentication.JwtBearer 3.1.1 摘要:基于ASP.N ...
- [SUCTF 2019]Pythonginx
贴出源码 @app.route('/getUrl', methods=['GET', 'POST']) def getUrl(): url = request.args.get("url&q ...
- .NET中的字符串(4):字符串 - 特殊的引用类型
字符串驻留 看一下这段代码: 1using System; 2 3namespace Demo4 4{ 5 /**//// <summary> 6 /// String的驻留 7 /// ...
- 移除微信昵称中的emoji字符
移除微信昵称中的emoji字符: /** * 移除微信昵称中的emoji字符 * @param type $nickname * @return type */ function removeEmoj ...
- 吴裕雄 python 神经网络——TensorFlow 图像预处理完整样例
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt def distort_color(image, ...
- 炼金术(1): 识别项目开发中的ProtoType、Demo、MVP
软件开发是很分裂的,只有不断使用原则和规律,才能带来质量. 只要不是玩具性质的项目,项目应该可以大概划分为0-1,1-10,10-100,100-1000四个种重要阶段.其中,0-1是原型验证性的:1 ...
- Python学习第二十三课——Mysql 表记录的一些基本操作 (查)
查(select * from 表名) 基本语法: select <字段1,字段2,...> from <表名> where <表达式>; 例如,查询student ...
- Kafka 消息的消费原理
https://www.cnblogs.com/huxi2b/p/6061110.html 1.老版本的kafka的offset是维护在zk上的,新版本的kafka把consumer的offset维护 ...
- 【SSM 下载】下载文件
111111111 /** * 导出客户数据 */ @RequestMapping("exportCustomer") public ResponseEntity<Objec ...
- apache 配置虚拟目录
#注释掉apache默认的网站目录地址 #DocumentRoot "c:/Rrogram Files/Apache/htdocs" #配置一个虚拟目录 <ifModule ...