随笔 - 72  文章 - 28  trackbacks - 0
<2014年1月>
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

常用链接

留言簿(4)

随笔分类(66)

随笔档案(72)

文章档案(19)

收藏夹

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 

Ibatis+spring整合集成开发

 

前面的文档学习了ibatis的开发,这节学习ibatisspring的整合集成开发。

1.需要的开发包包括ibatis开发包和spring常用包

 

 

2.创建POJO实体类,Area.javaDefine_industry.java

package com.ibatis.sample.config;

import java.io.Serializable;

public class Area implements Serializable{

    private int area_id;

    private String province;

    private String area;

    private String code;

    private String regdate;

    public int getArea_id() {

       return area_id;

    }

    public void setArea_id(int areaId) {

       area_id = areaId;

    }

    public String getProvince() {

       return province;

    }

    public void setProvince(String province) {

       this.province = province;

    }

    public String getArea() {

       return area;

    }

    public void setArea(String area) {

       this.area = area;

    }

    public String getCode() {

       return code;

    }

    public void setCode(String code) {

       this.code = code;

    }

    public String getRegdate() {

       return regdate;

    }

    public void setRegdate(String regdate) {

       this.regdate = regdate;

    }

}

 

package com.ibatis.sample.config;

import java.io.Serializable;

public class Define_industry implements Serializable{

    private int industry_id;

    private String title;

    public Define_industry(){};

    public Define_industry(String title){

     this.title = title;

     }

    public Define_industry(int industry_id,String title){

       this.industry_id=industry_id;

       this.title=title;

    }

    public int getIndustry_id() {

       return industry_id;

    }

    public void setIndustry_id(int industryId) {

       industry_id = industryId;

    }

    public String getTitle() {

       return title;

    }

    public void setTitle(String title) {

       this.title = title;

    }

}

 

3.创建Ibatis映射文件Area.xmlIndustry.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMap   PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" 

"http://www.ibatis.com/dtd/sql-map-2.dtd">

<sqlMap namespace="Area">

    <typeAlias alias="area" type="com.ibatis.sample.config.Area"/>

    <select id="getArea" parameterClass="int" resultClass="area">

       <![CDATA[

       select province,area,code,to_char(regdate,'yyyy-mm-dd') as regdate from DEFINE_AREA where area_id=#id#

       ]]>

    </select>

    <select id="getArealist" resultClass="area">

       <![CDATA[

       select * from DEFINE_AREA

       ]]>

    </select>

    <select id="getArealist1" parameterClass="String" resultClass="area">

       <![CDATA[

       select area_id, province,area,code from DEFINE_AREA where area like '%'||#are#||'%'

       ]]>

    </select>

   

    <resultMap id="get_area_result" class="area">

       <result property="area_id" column="area_id" jdbcType="NUMBER" javaType="int"/>

       <result property="area" column="area" jdbcType="VARCHAR" javaType="String"/>

    </resultMap>

   

    <select id="getArealist2" parameterClass="area" resultMap="get_area_result">    

       select area_id, province,area,code from DEFINE_AREA

       <dynamic prepend="where">

         <isNotEmpty prepend="and" property="area">

             area like '%'||#area#||'%'

         </isNotEmpty> 

        </dynamic>        

    </select>

 

</sqlMap>

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMap   PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" 

"http://www.ibatis.com/dtd/sql-map-2.dtd">

<sqlMap namespace="Industry">

    <typeAlias alias="industry" type="com.ibatis.sample.config.Define_industry"/>

    <typeAlias alias="userinfo" type="com.ibatis.sample.config.UserInfo"/>

   

    <select id="get_industryid" resultClass="int">

       <![CDATA[

       select seq_define_industry.nextval from dual

       ]]>

    </select>

   

    <insert id="insertIndustry" parameterClass="industry">

       <!-- <insert> 元素的子元素 < selectKey> 来支持主键自动生成,并把值写入相应的keyproperty对应的字段中-->

       <selectKey resultClass="java.lang.Integer" keyProperty="industry_id" >

                select seq_define_industry.nextval from dual        

       </selectKey>

       insert into DEFINE_INDUSTRY(industry_id,title) values(#industry_id#,#title#)

    </insert>

   

    <update id="updateIndustry" parameterClass="industry">

       update DEFINE_INDUSTRY set title=#title# where industry_id=#industry_id#

    </update>

   

    <delete id="delIndustry" parameterClass="int">

       delete from DEFINE_INDUSTRY where industry_id=#industry_id#

    </delete>

   

    <parameterMap id="login_pro" class="map">

        <parameter property="id" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/> 

        <parameter property="pwd" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN"/> 

        <parameter property="CompanyID" jdbcType="INTEGER" javaType="java.lang.Integer" mode="OUT"/> 

        <parameter property="companyname" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="groupID" jdbcType="INTEGER" javaType="java.lang.Integer" mode="OUT"/> 

        <parameter property="group_desc" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="selectLevel" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="updateLevel" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="addLelvel" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="delelteLevel" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="Account_id" jdbcType="INTEGER" javaType="java.lang.Integer" mode="OUT"/>

        <parameter property="Grade" jdbcType="INTEGER" javaType="java.lang.Integer" mode="OUT"/>

        <parameter property="account" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="Name" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="Mobile" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT"/>

        <parameter property="Result" jdbcType="INTEGER" javaType="java.lang.Integer" mode="OUT"/>

    </parameterMap>

   

    <procedure id="login_user" parameterMap="login_pro">   

       <![CDATA[{ call procedure_ecsystem_login(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }]]>

    </procedure>

   

</sqlMap>

 

4.Ibatis整合spring以后,ibatis中的数据库连接配置不再存在,而是到spring的配置文件中进行配置。Ibatis的配置文件SqlMapConfig.xml如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMapConfig         

    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"         

    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

      

<sqlMapConfig>

 

    <settings   

        cacheModelsEnabled="true"  

        enhancementEnabled="true" 

        lazyLoadingEnabled="true"   

        errorTracingEnabled="true"   

        maxRequests="32"   

        maxSessions="10"   

        maxTransactions="5"   

        useStatementNamespaces="false"   

      />   

       <sqlMap resource="com/ibatis/sample/config/Area.xml"/> 

<sqlMap resource="com/ibatis/sample/config/Industry.xml"/>

</sqlMapConfig>

 

4.Spring 的配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:p="http://www.springframework.org/schema/p"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

 

    <!-- 通用属性文件定义 -->

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

       <property name="locations">

           <list>

              <value>classpath:com/ibatis/sample/config/db.properties</value>

           </list>

       </property>

    </bean>

   

    <!--数据源配置-->

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 

        <property name="driverClassName" value="${driver}" /> 

        <property name="url" value="${url}" /> 

        <property name="username" value="${user}" /> 

        <property name="password" value="${password}" /> 

        <!-- 同一时间可以从池分配的最多连接数量 设置为0时表示无限制--> 

       <property name="maxActive" value="200" />

       <!-- 超时等待时间以毫秒为单位 --> 

       <property name="maxWait" value="500" />

       <!-- 池里不会被释放的最多空闲连接数量 设置为0时表示无限制--> 

       <property name="maxIdle" value="30" />

       <!-- 设置自动回收超时连接 -->

       <property name="removeAbandoned" value="true" />

       <!-- 自动回收超时时间(以秒数为单位) --> 

       <property name="removeAbandonedTimeout" value="60" />

       <property name="testOnBorrow" value="true"/>

       <property name="validationQuery" value="select 1 from dual"/>

    </bean> 

   

    <!-- Spring提供的iBatisSqlMap配置-->

    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">

     <property name="configLocation">

         <value>classpath:com/ibatis/sample/config/SqlMapConfig.xml</value>

     </property>

     <property name="dataSource" ref="dataSource" />

    </bean>

   

    <!-- 使用SqlMapClientDaoSupport提供的SqlMapClientTemplate对象来操纵数据库,

    继承SqlMapClientDaoSupport,要求我们注入SqlMapClient对象 ,sqlMapClientdatasource获取数据库连接-->

    <bean id="testDao" class="com.logic.TestDaoImpl">

       <property name="sqlMapClient" ref="sqlMapClient"></property>

    </bean> 

   

</beans>

 

5.DAO接口和实现类TestDao.javaTestDaoImpl.java

package com.logic;

 

import java.util.ArrayList;

import java.util.List;

 

import com.ibatis.sample.config.Area;

import com.ibatis.sample.config.Define_industry;

public interface TestDao {

 

    public Area getarea_byid(int id);

   

    public List getArealist1(String name);

   

    public void updateIndustry(Define_industry industry);

   

    public void insertIndustry(Define_industry industry);

}

 

package com.logic;

 

import java.util.ArrayList;

import java.util.List;

 

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

 

import com.ibatis.sample.config.Area;

import com.ibatis.sample.config.Define_industry;

 

public class TestDaoImpl extends SqlMapClientDaoSupport implements TestDao {

 

    public Area getarea_byid(int id){

        return (Area)getSqlMapClientTemplate().queryForObject("getArea",id);

    }

   

    public List getArealist1(String name){

       return getSqlMapClientTemplate().queryForList("getArealist1",name);

    }

   

    public void updateIndustry(Define_industry industry){

       getSqlMapClientTemplate().update("updateIndustry", industry);

    }

   

    public void insertIndustry(Define_industry industry){

       getSqlMapClientTemplate().insert("insertIndustry", industry);

    }

}

 

 

6.测试类

package com.logic;

 

import java.util.List;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.ibatis.sample.config.Area;

import com.ibatis.sample.config.Define_industry;

 

public class Test {

    public static void main(String[] args) {

       // TODO Auto-generated method stub

       ApplicationContext context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");

       TestDao testimpl=(TestDao)context.getBean("testDao");

       Area area=testimpl.getarea_byid(5);

       System.out.println(area.getArea());

       System.out.println(area.getProvince());

       System.out.println(area.getRegdate());

      

       List list1=testimpl.getArealist1("");

       for (int i = 0; i < list1.size(); i++) {

           Area area1=(Area)list1.get(i);

           System.out.println(area1.getArea_id()+"--"+area1.getArea());

       }

    }

 

}

 

7、以下加入页面操作和事务处理

修改spring的配置文件,加入事务代理和springcontroller

 

<?xml version="1.0" encoding="UTF-8"?>

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:p="http://www.springframework.org/schema/p"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

 

    <!-- 通用属性文件定义 -->

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

       <property name="locations">

           <list>

              <value>classpath:com/ibatis/sample/config/db.properties</value>

           </list>

       </property>

    </bean>

   

    <!--数据源配置-->

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 

        <property name="driverClassName" value="${driver}" /> 

        <property name="url" value="${url}" /> 

        <property name="username" value="${user}" /> 

        <property name="password" value="${password}" /> 

       

        <!-- 同一时间可以从池分配的最多连接数量 设置为0时表示无限制--> 

       <property name="maxActive" value="200" />

       <!-- 超时等待时间以毫秒为单位 --> 

       <property name="maxWait" value="500" />

       <!-- 池里不会被释放的最多空闲连接数量 设置为0时表示无限制--> 

       <property name="maxIdle" value="30" />

       <!-- 设置自动回收超时连接 -->

       <property name="removeAbandoned" value="true" />

       <!-- 自动回收超时时间(以秒数为单位) --> 

       <property name="removeAbandonedTimeout" value="60" />

       <property name="testOnBorrow" value="true"/>

       <property name="validationQuery" value="select 1 from dual"/>

    </bean> 

   

    <!-- 事务管理器 -->

    <bean id="transactionManager" 

    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 

        <property name="dataSource" ref="dataSource"></property> 

    </bean>

    <!--?事务代理拦截器的配置?--> 

    <bean id="txProxyTemplate" abstract="true" 

        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> 

        <property name="transactionManager"> 

            <ref bean="transactionManager" /> 

        </property> 

        <property name="transactionAttributes"> 

            <props> 

                <prop key="insert*">PROPAGATION_REQUIRED</prop> 

                <prop key="save*">PROPAGATION_REQUIRED</prop> 

                <prop key="update*">PROPAGATION_REQUIRED</prop> 

                <prop key="delete*">PROPAGATION_REQUIRED</prop> 

                <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> 

            </props> 

        </property> 

    </bean> 

 

     

    <!-- Spring提供的iBatisSqlMap配置-->

    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">

     <property name="configLocation">

         <value>classpath:com/ibatis/sample/config/SqlMapConfig.xml</value>

     </property>

     <property name="dataSource" ref="dataSource" />

    </bean>

 

    <!-- 定义页面请求映射 -->

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

    <property name="mappings">

           <props>             

              <!-- 测试模块开始 -->

              <prop key="/test.do">TestController</prop>

              </props>

       </property>

    </bean>   

   

    <!-- 配置实体实现类 -->

    <bean id="TestController" class="com.controller.TestController">

       <property name="testlogic" ref="testlogicProxy"/>      

    </bean>

   

   

    <!-- 使用SqlMapClientDaoSupport提供的SqlMapClientTemplate对象来操纵数据库,

    继承SqlMapClientDaoSupport,要求我们注入SqlMapClient对象 ,sqlMapClientdatasource获取数据库连接-->

    <bean id="testDao" class="com.logic.TestDaoImpl">

       <property name="sqlMapClient" ref="sqlMapClient"></property>

    </bean> 

    <bean id="testlogic" class="com.logic.TestlogicImpl">

       <property name="testDao" ref="testDao"/>     

    </bean>

    <bean id="testlogicProxy" parent="txProxyTemplate"> 

       <property name="target" ref="testlogic"></property> 

    </bean> 

</beans>

 

修改web.xml,使自动加载spring的配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"

    xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 

  <servlet>

       <servlet-name>testSystemSpring</servlet-name>

       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

       <init-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>/WEB-INF/applicationContext.xml</param-value>

       </init-param>

       <load-on-startup>1</load-on-startup>

    </servlet>

 

 <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

 </welcome-file-list>

</web-app>

 

TestController.java

package com.controller;

 

import java.util.ArrayList;

import java.util.List;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.Controller;

 

import com.ibatis.sample.config.Area;

import com.ibatis.sample.config.Define_industry;

import com.logic.Testlogic;

 

public class TestController implements Controller{

 

    private Testlogic testlogic;

    public Testlogic getTestlogic() {

       return testlogic;

    }

    public void setTestlogic(Testlogic testlogic) {

       this.testlogic = testlogic;

    }

    /* (non-Javadoc)

     * @see org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

     */

    public ModelAndView handleRequest(HttpServletRequest arg0,

           HttpServletResponse arg1) throws Exception {

       // TODO Auto-generated method stub

       Area area=testlogic.getarea_byid(7);

       System.out.println(area.getArea());

       System.out.println(area.getProvince());

       System.out.println(area.getRegdate());

      

       List list1=testlogic.getArealist1("");

       for (int i = 0; i < list1.size(); i++) {

           Area area1=(Area)list1.get(i);

           System.out.println(area1.getArea_id()+"--"+area1.getArea());

       }

   

       Define_industry industry=new Define_industry(10,"其它1");

       testlogic.updateIndustry(industry);

      

       List industrylist = new ArrayList();

       industrylist.add(new Define_industry("test_1"));

       industrylist.add(new Define_industry("test_2"));

       industrylist.add(new Define_industry("test_3"));

       industrylist.add(new Define_industry("test_4"));

       testlogic.insertIndustry(industrylist);

      

       return null;

    }

 

}

 

Testlogic.javaTestlogicImpl.java

package com.logic;

 

import java.util.List;

 

import com.ibatis.sample.config.Area;

import com.ibatis.sample.config.Define_industry;

public interface Testlogic {

 

    public Area getarea_byid(int id);

   

    public List getArealist1(String name);

   

    public void updateIndustry(Define_industry industry);

   

    public void insertArea(List vlist);

}

 

package com.logic;

 

import java.util.List;

 

import com.ibatis.sample.config.Area;

import com.ibatis.sample.config.Define_industry;

 

public class TestlogicImpl implements Testlogic {

 

    private TestDao testDao;

 

    public TestDao getTestDao() {

       return testDao;

    }

 

    public void setTestDao(TestDao testDao) {

       this.testDao = testDao;

    }

   

    public Area getarea_byid(int id){

       return testDao.getarea_byid(id);

    }

   

    public List getArealist1(String name){

       return testDao.getArealist1(name);

    }

   

    public void updateIndustry(Define_industry industry){

       testDao.updateIndustry(industry);

    }

   

    public void insertIndustry(List vlist){

       for(int i=0 ; i<vlist.size() ;i++){

          if(i>2){

           System.out.println("列表太长,中断事务");

           throw new RuntimeException("中断事务异常,当列表长度大于3的时候故意抛出,看看事务是否回滚");

          }

          Define_industry industry = (Define_industry)vlist.get(i);

          testDao.insertIndustry(industry);

        }

 

    }

}

 

启动tomcat,访问http://ip:port/test/test.do,访问项目

 

posted on 2014-01-09 11:38 kelly 阅读(285) 评论(0)  编辑  收藏 所属分类: java 框架

只有注册用户登录后才能发表评论。


网站导航: