spring与mybatis(oracle)整合

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

先是完整的项目图

spring与mybatis(oracle)整合

首先是用户类 用户类中目前就只包含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);
	}

	}

}

测试结果

spring与mybatis(oracle)整合

DaoUtil已创建:1次;

success

上一篇:间隔DP基础 POJ2955——Brackets


下一篇:【MM系列】SAP里批量设置采购信息记录删除标记