spring與mybatis oracle 整合
阿新 • • 發佈:2019-01-10
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
今天閒著無聊把專案拆解開,抽出了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 mapperPUBLIC "-//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")@Servicepublic 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 * */@Servicepublic 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