今天闲着无聊把项目拆解开,抽出了spring与mybatis部分.做了个demo,希望对初学者有些帮助,另外整个demo是从项目中完整剥离下来的,里面的架构大家也可以参考一下.

先是完整的项目图

首先是用户类 用户类中目前就只包含sava方法,update,find方法

package com.user;

import com.dao.IDaoUtil;

public class User {
	private String id;
	private String xm;

	/**
	 * 保存,2014-4-16
	 */

	public void save(IDaoUtil dao)  {
		dao.addObject("UserMapper.insert", this);
	}
        //省略get/set方法
 }

再下来就是usermap  为了简单我只写了insert, 至于别的操作大家自己写

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="UserMapper">

	<insert id="insert" parameterType="UserModel">
        INSERT INTO
        user (id,xm)
        	  VALUES (
        	#{id,jdbcType=VARCHAR},
        	#{xm,jdbcType=VARCHAR}
         )
	</insert>
</mapper>

抽象出所有与数据库相关的工作

做成IDaoUtil

package com.dao;

import java.util.List;
import java.util.Map;

public interface IDaoUtil {

	public void addObject(String mapperStr, Object model);

	public void deleteObjectByID(String mapperStr, String id);

	@SuppressWarnings("rawtypes")
	public void deleteObjectByMap(String mapperStr, Map map);

	public void deleteObject(String mapperStr, Object model);

	public void updateObject(String mapperStr,Object model);

	public Object getObjectByID(String mapperStr,String keyValue);

	@SuppressWarnings("rawtypes")
	public Object getObjectByMap(String mapperStr,Map map);

	@SuppressWarnings("rawtypes")
	public List findListByMap(String mapperStr, Map map);

	@SuppressWarnings("rawtypes")
	public List findListByID(String mapperStr, String id);

	@SuppressWarnings("rawtypes")
	public Integer countByMap(String countSql,Map map);

}

在写出它的实现类

而下面这个类 我认为是这篇博客的精髓 希望对大家有帮助

package com.dao;

import java.util.List;
import java.util.Map;

//import org.apache.ibatis.builder.xml.dynamic.ForEachSqlNode;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Scope("prototype")
@Service
public class DaoUtil extends SqlSessionDaoSupport implements IDaoUtil{

	@Override
	@Autowired
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		super.setSqlSessionFactory(sqlSessionFactory);
	}

	public static int daocount=0;
	public DaoUtil(){
		daocount++;
		System.out.println("DaoUtil已创建:"+daocount+"次;");
	}
	 public static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
	 public static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY =
	                                                         new DefaultObjectWrapperFactory();  

	public static Logger logger = LoggerFactory.getLogger(DaoUtil.class); 

	@Override
	public void addObject(String mapperStr, Object model) {
		try {
			getSqlSession().insert(mapperStr, model);
		//	System.out.println(this.getSql(getSqlSession(),mapperStr, model));
		} catch (RuntimeException re) {
            logger.error("DaoUtil.addObject(); sqlmapper: "+ mapperStr
            		+ ";\r\n### class name:" +model.getClass().getName()
           // 		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, model)
            		+ " failed  end\r\n",re);
            throw re;
        }
	}

	@Override
	public void deleteObjectByID(String mapperStr, String id) {

		try {
		//	System.out.println("sql  "+this.getSql(getSqlSession(),mapperStr, id));
			getSqlSession().delete(mapperStr, id);   

	     } catch (RuntimeException re) {
	    	 logger.error("DaoUtil.addObject(); sqlmapper: "+ mapperStr
	            		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, id)
	            		+ " failed  end\r\n",re);
	            throw re;
	     }
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void deleteObjectByMap(String mapperStr, Map map) {

		try {  

			getSqlSession().delete(mapperStr, map);   

	     } catch (RuntimeException re) {
	    	 logger.error("DaoUtil.addObject(); sqlmapper: "+ mapperStr
	            		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, map)
	            		+ " failed  end\r\n",re);
	            throw re;
	     }
	}     

	@Override
	public void deleteObject(String mapperStr, Object model) {
		try {
			getSqlSession().delete(mapperStr, model);   

	     } catch (RuntimeException re) {
	    	 logger.error("DaoUtil.addObject(); sqlmapper: "+ mapperStr
	            		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, model)
	            		+ " failed  end\r\n",re);
	            throw re;
	     }  

	}

	/**
	 * 更新数据
	 */
	@Override
	public void updateObject(String mapperStr,Object model){

		 try {
			 getSqlSession().update(mapperStr, model);
	     } catch (RuntimeException re) {
	    	 logger.error("DaoUtil.addObject(); sqlmapper: "+ mapperStr
	            		+ ";\r\n### class name:" +model.getClass().getName()
	            		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, model)
	            		+ " failed  end\r\n",re);
	         throw re;
	     }
	}

	/**
	 * 根据ID获取一个对象
	 */
	@Override
	public Object getObjectByID(String mapperStr,String keyValue){

		 try {
	   	//	 System.out.println("sql  "+this.getSql(getSqlSession(),mapperStr, keyValue));
			 Object entity = getSqlSession().selectOne(mapperStr, keyValue);
			 return entity;
		 } catch (RuntimeException re) {
			 re.printStackTrace();
	    	 logger.error("DaoUtil.addObject(); sqlmapper: "+ mapperStr
	            		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, keyValue)
	            		+ " failed  end\r\n",re);
	         throw re;
	     }
	}

	/**
	 * 根据map获取一个对象
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Object getObjectByMap(String mapperStr,Map map){

		 try {
			 Object entity = getSqlSession().selectOne(mapperStr, map);
			 return entity;
		 } catch (RuntimeException re) {
	    	 logger.error("DaoUtil.addObject(); sqlmapper: "+ mapperStr
	            		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, map)
	            		+ " failed  end\r\n",re);
	         throw re;
	     }
	}

	/**
	 * 根据mapper获取数据列表
	 */
	@Override
	@SuppressWarnings({ "rawtypes" })
	public List findListByMap(String mapperStr, Map map) {
		try {
           // float a= 2/0;
			List list = getSqlSession().selectList(mapperStr, map);
			return list;
		} catch (RuntimeException re) {
			logger.error("DaoUtil.findListByMap(); sqlmapper: "+ mapperStr
            		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, map)
            		+ " failed  end\r\n",re);
			throw re;
		}
	}

	/**
	 * 根据mapper获取数据列表
	 */
	@SuppressWarnings({ "rawtypes" })
	@Override
	public List findListByID(String mapperStr, String keyValue) {
		try {
           // float a= 2/0;
			List list = getSqlSession().selectList(mapperStr, keyValue);

			return list;

		} catch (RuntimeException re) {
			logger.error("DaoUtil.findListByID(); sqlmapper: "+ mapperStr
            		+";\r\n### sql:" +this.getSql(getSqlSession(),mapperStr, keyValue)
            		+ " failed  end\r\n",re);
			throw re;
		}
	}

	public Integer countByMap(String countSql,Map map){
		Integer count=(Integer)getSqlSession().selectOne(countSql,map);
		if(count==null)
			count=0;
		return count;
	}

	/**获取sql String*/
	public String getSql(SqlSession sqlSession,String sqlid, Object parameterObject) {                  

		Configuration cfg = sqlSession.getConfiguration();
		MappedStatement ms = cfg.getMappedStatement(sqlid);
		if (null == ms) {
			return "";
		}                  

		//BoundSql bs = ms.getBoundSql(obj);
		BoundSql boundSql = ms.getBoundSql(parameterObject); 

		String parameterStr="";
		List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();  

	    if (parameterMappings != null) {
	        //Object[] parameterArray = new Object[parameterMappings.size()];

	        MetaObject metaObject = parameterObject == null ? null : MetaObject.forObject(parameterObject, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
	        for (int i = 0; i < parameterMappings.size(); i++) {
	          ParameterMapping parameterMapping = parameterMappings.get(i);
	          if (parameterMapping.getMode() != ParameterMode.OUT) {
	            Object value;
	            String propertyName = parameterMapping.getProperty();
	            PropertyTokenizer prop = new PropertyTokenizer(propertyName);
	            if (parameterObject == null) {
	              value = null;
	            } else if (ms.getConfiguration().getTypeHandlerRegistry().hasTypeHandler(parameterObject.getClass())) {
	              value = parameterObject;
	            } else if (boundSql.hasAdditionalParameter(propertyName)) {
	              value = boundSql.getAdditionalParameter(propertyName);
	            } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)
	                && boundSql.hasAdditionalParameter(prop.getName())) {
	              value = boundSql.getAdditionalParameter(prop.getName());
	              if (value != null) {
	                value = MetaObject.forObject(value, null, null).getValue(propertyName.substring(prop.getName().length()));
	              }
	            } else {
	              value = metaObject == null ? null : metaObject.getValue(propertyName);
	            }
	            //parameterArray[i] = value;
	            parameterStr+=value+"; ";
	          }
	        }
	        //ibatisSql.setParameters(parameterArray);
	    }  

		return boundSql.getSql()+";\r\n### parameters: "+parameterStr;
		//return "没有测试";
	}
}

再下来就是学生的facade类 同样的我只写了add方法

package com.facade.xuesheng;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.dao.IDaoUtil;
import com.user.User;

/**
 * 学生模块facade类
 *
 * @version V1.0 ,2013-11-10
 * @author xiahui
 *
 */

@Service
public class XueShengFacade {

	@Resource
	private IDaoUtil daoUtil;
	/**
	 * 添加一个学生记录
	 *
	 */
	public String addDkRecord(User user){
		user.save(daoUtil);
		return "success";
	}
}

再下来就是整个程序的关键spring的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- ====================================================================================== -->
	<!-- 启用基于注解(Annotation-based)的配置 -->
	<!-- ====================================================================================== -->
	<context:annotation-config />

	<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
    		<property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
    		<property name="url" value="jdbc:oracle:thin:@203.218.132.153:1521:orcl" />
    		<property name="username" value="hasdfp" />
    		<property name="password" value="sdfd" />
  	</bean>      

	<!-- ====================================================================================== -->
	<!-- 配置 SqlMapClient -->
	<!-- ====================================================================================== -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:config/sqlMapConfig.xml" />
	</bean>

	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />

	<context:component-scan base-package="com.dao"/>
	<context:component-scan base-package="com.facade.xuesheng"/>
</beans>

最后测试类

package com.facade.xuesheng;

import org.example.Country;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

import com.dao.IDaoUtil;

import com.facade.xuesheng.XueShengFacade;
import com.user.User;

@ContextConfiguration(locations = { "classpath:test/UserApplicationContext.xml" })
public class XueShengFacadeTest extends AbstractJUnit4SpringContextTests {

	@Autowired
	private XueShengFacade xueShengFacade;

        /**
	 *
	 * @throws Exception
	 */
	@Test
	public void testAddDkRecord() throws Exception {

		User user = new User();
		user.setId("123");
		user.setXm("郭靖");

		String result = xueShengFacade.addDkRecord(user);
		System.out.println(result);
	}

	}

}

测试结果

DaoUtil已创建:1次;

success

spring与mybatis(oracle)整合的更多相关文章

  1. SSM框架整合(Spring+SpringMVC+MyBatis+Oracle)

    1.开发环境搭建以及创建Maven Web项目 参看之前的博文[确保maven web项目不报错]:http://www.cnblogs.com/cainiaomahua/p/6306476.html ...

  2. (4)Maven快速入门_4在Spring+SpringMVC+MyBatis+Oracle+Maven框架整合运行在Tomcat8中

    利用Maven 创建Spring+SpringMVC+MyBatis+Oracle 项目 分了三个项目  Dao   (jar)   Service (jar)   Controller (web) ...

  3. 关于Spring和mybatis的整合

    Spring同Mybatis的整合 1.引入相应的jar包.(Mybatis的jar包,Spring的jar包,mybatis-spring-1.1.1.jar). 2.编写相应的包(三层的包).搭建 ...

  4. 如约而至,Java 10 正式发布! Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十四)Redis缓存正确的使用姿势 努力的孩子运气不会太差,跌宕的人生定当更加精彩 优先队列详解(转载)

    如约而至,Java 10 正式发布!   3 月 20 日,Oracle 宣布 Java 10 正式发布. 官方已提供下载:http://www.oracle.com/technetwork/java ...

  5. 基于maven进行spring 和mybatis的整合(Myeclpise)

    学习日记:基于maven进行spring和mybatis的整合,进行分页查询 什么是maven:maven是一个项目管理工具,使用maven可以自动管理java项目的整个生命周期,包括编译.构建.测试 ...

  6. Spring+SpringMVC+MyBatis+easyUI整合基础篇(六)maven整合SSM

    写在前面的话   承接前文<Spring+SpringMVC+MyBatis+easyUI整合基础篇(五)讲一下maven>,本篇所讲述的是如何使用maven与原ssm项目整合,使得一个普 ...

  7. Spring+SpringMVC+MyBatis+easyUI整合基础篇(八)mysql中文查询bug修复

    写在前面的话 在测试搜索时出现的问题,mysql通过中文查询条件搜索不出数据,但是英文和数字可以搜索到记录,中文无返回记录.本文就是写一下发现问题的过程及解决方法.此bug在第一个项目中点这里还存在, ...

  8. Spring+SpringMVC+MyBatis+easyUI整合基础篇(十一)SVN服务器进阶

    日常啰嗦 上一篇文章<Spring+SpringMVC+MyBatis+easyUI整合基础篇(十)SVN搭建>简单的讲了一下SVN服务器的搭建,并没有详细的介绍配置文件及一些复杂的功能, ...

  9. Spring+SpringMVC+MyBatis+easyUI整合基础篇(十二)阶段总结

    不知不觉,已经到了基础篇的收尾阶段了,看着前面的十几篇文章,真的有点不敢相信,自己竟然真的坚持了下来,虽然过程中也有过懒散和焦虑,不过结果还是自己所希望的,克服了很多的问题,将自己的作品展现出来,也发 ...

随机推荐

  1. 解决使用web开发手机网页关于分辨率被缩放的坑

    问题的产生 因为各方面原因,要用网页做界面,开发一个APP.内核使用的是腾讯的x5内核. 把外壳交给前端和设计测试的时候,都汇报:状态栏的颜色太不搭配了,要求可修改 遂启用了安卓4.4版本开始支持的沉 ...

  2. 服务器&阵列卡&组raid 5

    清除raid信息后,机器将会读不到系统, 后面若进一步操作处理, raid信息有可能会被初始化掉,那么硬盘数据就有可能会被清空, 导致数据丢失, 否则如果只是清除raid信息,重做raid是可以还原系 ...

  3. 安卓高级Fresco图片框架的时候

    Fresco:2015FaceBook推出的 及其强大 支持webp图片格式 和渐进式图片加载 中文文档 使用方法 引入依赖 点击查看具体教程 基本使用步骤 在布局中使用其标签 <com.fac ...

  4. Useful command for Docker

    Copy file from Container to Host: docker cp <containerId>:/file/path/within/container /host/pa ...

  5. Programming In Scala笔记-第十一章、Scala中的类继承关系

    本章主要从整体层面了解Scala中的类层级关系. 一.Scala的类层级 在Java中Object类是所有类的最终父类,其他所有类都直接或间接的继承了Object类.在Scala中所有类的最终父类为A ...

  6. springMVC源码分析--HandlerMethod

    在之前的博客中我们已经接触过HandlerMethod,接下来我们简单介绍一下HandlerMethod,简单来说HandlerMethod包含的信息包括类.方法和参数的一个信息类,通过其两个构造函数 ...

  7. ubuntu蓝牙音响配对成功但在声音设置中无法设置 解决

    ubuntu蓝牙音响配对成功但在声音设置中无法设置 解决 首先,连接蓝牙 但是,在声音设置中如下: 都没有发现设备??? 打开终端输入: ~$ pactl load-module module-blu ...

  8. ROS(indigo)ROSPlan框架

    源码地址:https://github.com/KCL-Planning/ROSPlan/wiki ROSPlan框架 ROSPlan框架提供了用于在ROS的系统任务规划的通用方法.ROSPlan的两 ...

  9. 目标管理体系:OKR

    一.什么是OKR体系? OKR体系的全称是Objectives & Key Results,即目标与关键成果.所谓OKR,O = Objective 可以理解为企业目标,KR =Key Res ...

  10. springmvc注解形式的开发参数接收

    springmvc基于注解的开发 注解第一个例子 1. 创建web项目 springmvc-2 2. 在springmvc的配置文件中指定注解驱动,配置扫描器 <!-- sprimgmvc 注解 ...