spring与mybatis(oracle)整合
今天闲着无聊把项目拆解开,抽出了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)整合的更多相关文章
- SSM框架整合(Spring+SpringMVC+MyBatis+Oracle)
1.开发环境搭建以及创建Maven Web项目 参看之前的博文[确保maven web项目不报错]:http://www.cnblogs.com/cainiaomahua/p/6306476.html ...
- (4)Maven快速入门_4在Spring+SpringMVC+MyBatis+Oracle+Maven框架整合运行在Tomcat8中
利用Maven 创建Spring+SpringMVC+MyBatis+Oracle 项目 分了三个项目 Dao (jar) Service (jar) Controller (web) ...
- 关于Spring和mybatis的整合
Spring同Mybatis的整合 1.引入相应的jar包.(Mybatis的jar包,Spring的jar包,mybatis-spring-1.1.1.jar). 2.编写相应的包(三层的包).搭建 ...
- 如约而至,Java 10 正式发布! Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十四)Redis缓存正确的使用姿势 努力的孩子运气不会太差,跌宕的人生定当更加精彩 优先队列详解(转载)
如约而至,Java 10 正式发布! 3 月 20 日,Oracle 宣布 Java 10 正式发布. 官方已提供下载:http://www.oracle.com/technetwork/java ...
- 基于maven进行spring 和mybatis的整合(Myeclpise)
学习日记:基于maven进行spring和mybatis的整合,进行分页查询 什么是maven:maven是一个项目管理工具,使用maven可以自动管理java项目的整个生命周期,包括编译.构建.测试 ...
- Spring+SpringMVC+MyBatis+easyUI整合基础篇(六)maven整合SSM
写在前面的话 承接前文<Spring+SpringMVC+MyBatis+easyUI整合基础篇(五)讲一下maven>,本篇所讲述的是如何使用maven与原ssm项目整合,使得一个普 ...
- Spring+SpringMVC+MyBatis+easyUI整合基础篇(八)mysql中文查询bug修复
写在前面的话 在测试搜索时出现的问题,mysql通过中文查询条件搜索不出数据,但是英文和数字可以搜索到记录,中文无返回记录.本文就是写一下发现问题的过程及解决方法.此bug在第一个项目中点这里还存在, ...
- Spring+SpringMVC+MyBatis+easyUI整合基础篇(十一)SVN服务器进阶
日常啰嗦 上一篇文章<Spring+SpringMVC+MyBatis+easyUI整合基础篇(十)SVN搭建>简单的讲了一下SVN服务器的搭建,并没有详细的介绍配置文件及一些复杂的功能, ...
- Spring+SpringMVC+MyBatis+easyUI整合基础篇(十二)阶段总结
不知不觉,已经到了基础篇的收尾阶段了,看着前面的十几篇文章,真的有点不敢相信,自己竟然真的坚持了下来,虽然过程中也有过懒散和焦虑,不过结果还是自己所希望的,克服了很多的问题,将自己的作品展现出来,也发 ...
随机推荐
- all unicode
Unicode Chart Range Decimal Name 0x0000-0x007F 0-127 Basic Latin 0x0080-0x00FF 128-255 Latin-1 Suppl ...
- ACM Bee
In Africa there is a very special species of bee. Every year, the female bees of such species give b ...
- 作业03-面向对象入门.md
1. 本周学习总结 初学面向对象,会学习到很多碎片化的概念与知识.尝试学会使用思维导图将这些碎片化的概念.知识点组织起来.请使用工具画出本周学习到的知识点及知识点之间的联系.步骤如下: 1.1 写出你 ...
- java.lang.ClassNotFoundException:org.springframework.web.context.ContextLoaderListener问题解决
今天搭建SSH项目的时候出现了如下错误: 严重: Error configuring application listener of class org.springframework.web.con ...
- android Spinner控件详解
Spinner提供了从一个数据集合中快速选择一项值的办法.默认情况下Spinner显示的是当前选择的值,点击Spinner会弹出一个包含所有可选值的dropdown菜单,从该菜单中可以为Spinner ...
- chromium出现输入密码解锁登录密钥环
chromium出现输入密码解锁登录密钥环 在ubuntu 16.04上安装了Chromium出现对话框,如下所示: 因为密码框截图困难,这个是网上图片. 点取消就可以使用,但是每次都这样很烦,百度后 ...
- 基于Nginx服务器和iOS9的HTTPS安全通信
简介 在网络通信中,使用抓包软件可以对网络请求进行分析,并进行重放攻击,重放攻击的解决方案一般是使用一个变化的参数,例如RSA加密的时间戳,但考虑到网络传输时延,时间戳需要有一定的误差容限,这样仍然不 ...
- Unsupported major.minor version 52.0
今天运行项目,切换一下eclipse,运行程序突然发现普通的类main()方法无法运行,报错详细信息如下: Exception in thread "main" java.lang ...
- [error]configure: error: You need a C++ compiler for C++ support.
安装pcre包的时候提示缺少c++编译器 解决办法 使用yum安装 yum -y install gcc-c++ 本文出自 "orangleliu笔记本"博客,转载请务必保留此出处 ...
- Java进阶(四十六)简述ArrayList、Vector与LinkedList的异同点
简述ArrayList.Vector与LinkedList的异同点 Collection类的继承图如下: 从图中可以看出,LinkedList与ArrayList.ArrayDeque这三者都 ...