Struts2+Mybatis+Spring整合增删改查实例

在我的博客首页有s2sh整合的例子,现在要做的工作就是将此工程中hibernate换成mybatis,并且使用比较流行的annotation注解来实现。首先肯定是要将hibernate的jar包全部干掉,然后加上mybatis的jar包及其与spring整合所需jar包,下面只贴主要改动的类及其配置文件:

一.mybatis配置文件mybatis-config.xml

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

  1. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  2. <configuration>  
  3.     <typeAliases>  
  4.         <typeAlias alias="User" type="com.anxin.bean.User" />  
  5.         <typeAlias alias="Student" type="com.anxin.bean.Student" />  
  6.     </typeAliases>  
  7.     <mappers>  
  8.         <mapper resource="com/anxin/orm/mapping/User.xml" />  
  9.         <mapper resource="com/anxin/orm/mapping/Student.xml" />  
  10.     </mappers>  
  11. </configuration>  

二、bean的mapper文件

Student.xml

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="Student">  
  4.     <!--   
  5.         <resultMap type="Student" id="studentResultMap">  
  6.         <id property="id" column="id" />  
  7.         <result property="name" column="name" />  
  8.         <result property="age" column="age" />  
  9.         <result property="sex" column="sex" />  
  10.         <result property="address" column="address" />  
  11.         </resultMap>  
  12.     -->  
  13.     <insert id="save" parameterType="Student">  
  14.         insert into student(name,age,sex,address)  
  15.         values(#{name},#{age},#{sex},#{address})  
  16.     </insert>  
  17.     <update id="update" parameterType="Student">  
  18.         update student set  
  19.         name=#{name},age=#{age},sex=#{sex},address=#{address} where  
  20.         id=#{id}  
  21.     </update>  
  22.     <delete id="delete" parameterType="Student">  
  23.         delete from student where id=#{id}  
  24.     </delete>  
  25.     <delete id="deleteById" parameterType="int">  
  26.         delete from student where id=#{id}  
  27.     </delete>  
  28.     <select id="findById" parameterType="int" resultType="Student">  
  29.         select * from student where id=#{id}  
  30.     </select>  
  31.     <select id="findAll" resultType="Student">  
  32.         select * from student  
  33.     </select>  
  34.     <select id="queryPage" resultType="Student" parameterType="map">  
  35.         select * from student u  
  36.         <where>  
  37.             <if test="name!=null and name!='' ">  
  38.                 u.name like "%"#{name}"%"  
  39.             </if>  
  40.             <if test="sex!= null and sex!= '' ">and u.sex=#{sex}</if>  
  41.         </where>  
  42.         limit #{start},#{limit}  
  43.     </select>  
  44.     <select id="getTotalCounts" parameterType="map"  
  45.         resultType="Integer">  
  46.         select count(*)from student u  
  47.         <where>  
  48.             <if test="name!=null and name!='' ">  
  49.                 u.name like "%"#{name}"%"  
  50.             </if>  
  51.             <if test="sex!= null and sex!= '' ">and u.sex=#{sex}</if>  
  52.         </where>  
  53.     </select>  
  54. </mapper>  


User.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="User">  
  4. <!--    
  5.     <resultMap type="User" id="userResultMap">  
  6.         <id property="id" column="id" />  
  7.         <result property="username" column="username" />  
  8.         <result property="password" column="password" />  
  9.     </resultMap>  
  10. -->  
  11.     <insert id="save" parameterType="User">  
  12.         insert into users values(#{username},#{password})  
  13.     </insert>  
  14.     <update id="update" parameterType="User">  
  15.         update users set username=#{username},password=#{password} where  
  16.         id=#{id}  
  17.     </update>  
  18.     <delete id="delete" parameterType="User">  
  19.         delete from users where id=#{id}  
  20.     </delete>  
  21.     <delete id="deleteById" parameterType="int">  
  22.         delete from users where id=#{id}  
  23.     </delete>  
  24.     <select id="findById" parameterType="int"  
  25.         resultType="User">  
  26.         select * from Users where id=#{id}  
  27.     </select>  
  28.     <select id="findAll" resultType="User">select * from Users</select>  
  29.     <select id="queryPage" resultType="User"  
  30.         parameterType="map">  
  31.         select * from users u  
  32.     </select>  
  33.     <select id="getTotalCounts" parameterType="map" resultType="Integer">  
  34.         select count(*)from users  
  35.     </select>  
  36.     <select id="login" parameterType="User"  
  37.         resultType="User">  
  38.         select * from users where username=#{username} and  
  39.         password=#{password}  
  40.     </select>  
  41. </mapper>  


  1. <p></p><pre name="code" class="plain"><pre></pre>三、spring配置文件applicationContext.xml  
  2. <p></p>  
  3. <p><span style="font-family:Helvetica,Tahoma,Arial,sans-serif"><span style="font-size:14px; line-height:25px"></span></span></p>  
  4. <pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>  
  5. <beans xmlns="http://www.springframework.org/schema/beans"  
  6.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  7.     xmlns:context="http://www.springframework.org/schema/context"  
  8.     xmlns:tx="http://www.springframework.org/schema/tx"  
  9.     xsi:schemaLocation="  
  10.     http://www.springframework.org/schema/beans   
  11.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  12.     http://www.springframework.org/schema/context     
  13.     http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.     http://www.springframework.org/schema/tx   
  15.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
  16.   
  17.     <context:annotation-config></context:annotation-config>  
  18.     <context:component-scan base-package="com.anxin.struts.action" />  
  19.     <context:component-scan base-package="com.anxin.dao" />  
  20.     <context:component-scan base-package="com.anxin.service" />  
  21.     <bean id="propertyConfigurer"  
  22.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  23.         <property name="locations">  
  24.             <list>  
  25.                 <value>classpath:db.properties</value>  
  26.             </list>  
  27.         </property>  
  28.     </bean>  
  29.     <!-- 定义使用C3P0连接池的数据源 -->  
  30.     <bean id="dataSource"  
  31.         class="com.mchange.v2.c3p0.ComboPooledDataSource">  
  32.         <!-- 指定连接数据库的JDBC驱动 -->  
  33.         <property name="driverClass">  
  34.             <value>${driverClass}</value>  
  35.         </property>  
  36.         <!-- 连接数据库所用的URL -->  
  37.         <property name="jdbcUrl">  
  38.             <value>${jdbcUrl}</value>  
  39.         </property>  
  40.         <!-- 连接数据库的用户名 -->  
  41.         <property name="user">  
  42.             <value>${user}</value>  
  43.         </property>  
  44.         <!-- 连接数据库的密码 -->  
  45.         <property name="password">  
  46.             <value>${password}</value>  
  47.         </property>  
  48.         <!-- 设置数据库连接池的最大连接数 -->  
  49.         <property name="maxPoolSize">  
  50.             <value>20</value>  
  51.         </property>  
  52.         <!-- 设置数据库连接池的最小连接数 -->  
  53.         <property name="minPoolSize">  
  54.             <value>2</value>  
  55.         </property>  
  56.         <!-- 设置数据库连接池的初始化连接数 -->  
  57.         <property name="initialPoolSize">  
  58.             <value>2</value>  
  59.         </property>  
  60.         <!-- 设置数据库连接池的连接的最大空闲时间,单位为秒 -->  
  61.         <property name="maxIdleTime">  
  62.             <value>20</value>  
  63.         </property>  
  64.     </bean>  
  65.     <bean id="sqlSessionFactory"  
  66.         class="org.mybatis.spring.SqlSessionFactoryBean">  
  67.         <property name="configLocation"  
  68.             value="classpath:mybatis-config.xml" />  
  69.         <property name="dataSource" ref="dataSource" />  
  70.     </bean>  
  71.       
  72.   
  73.       
  74.     <!-- 数据库的事务管理器配置 -->  
  75.     <bean id="transactionManager"  
  76.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  77.         <property name="dataSource" ref="dataSource" />  
  78.     </bean>  
  79.     <!-- 使用annotation定义数据库事务,这样可以在类或方法中直接使用@Transactional注解来声明事务 -->  
  80.     <tx:annotation-driven transaction-manager="transactionManager" />  
  81. </beans></pre><br>  
  82. 四、泛型基类BaseDAOImpl.java<br>  
  83. <pre name="code" class="html"><pre name="code" class="html"><pre name="code" class="java">package com.anxin.dao.impl;  
  84.   
  85. import java.io.Serializable;  
  86. import java.util.List;  
  87. import java.util.Map;  
  88.   
  89. import javax.annotation.Resource;  
  90.   
  91. import org.apache.ibatis.session.SqlSessionFactory;  
  92. import org.mybatis.spring.support.SqlSessionDaoSupport;  
  93. import org.slf4j.Logger;  
  94. import org.slf4j.LoggerFactory;  
  95. import org.springframework.beans.factory.annotation.Autowired;  
  96.   
  97. import com.anxin.dao.BaseDAO;  
  98. import com.anxin.util.PageListData;  
  99.   
  100. public class BaseDAOImpl<T, PK extends Serializable> extends  
  101.         SqlSessionDaoSupport implements BaseDAO<T, PK> {  
  102.   
  103.     public static Logger logger = LoggerFactory.getLogger(BaseDAOImpl.class);  
  104.     @Autowired(required = true)  
  105.     @Resource(name = "sqlSessionFactory")  
  106.     public void setSuperSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {  
  107.         super.setSqlSessionFactory(sqlSessionFactory);  
  108.     }  
  109.     // 保存  
  110.     public T save(T entity) {  
  111.         try {  
  112.             getSqlSessionTemplate().insert(  
  113.                     entity.getClass().getSimpleName() + ".save", entity);  
  114.             return entity;  
  115.         } catch (RuntimeException re) {  
  116.             logger.error("save " + entity.getClass().getName() + " failed :{}",  
  117.                     re);  
  118.             throw re;  
  119.         }  
  120.     }  
  121.     // 更新  
  122.     public void update(T entity) {  
  123.         try {  
  124.             this.getSqlSessionTemplate().update(  
  125.                     entity.getClass().getSimpleName() + ".update", entity);  
  126.         } catch (RuntimeException re) {  
  127.             logger.error("update " + entity.getClass().getName()  
  128.                     + " failed :{}", re);  
  129.             throw re;  
  130.         }  
  131.     }  
  132.     // 删除  
  133.     public void delete(T entity) {  
  134.         try {  
  135.             this.getSqlSessionTemplate().delete(  
  136.                     entity.getClass().getSimpleName() + ".delete", entity);  
  137.         } catch (RuntimeException re) {  
  138.             logger.error("delete " + entity.getClass().getName()  
  139.                     + " failed :{}", re);  
  140.             throw re;  
  141.         }  
  142.     }  
  143.   
  144.     // 根据id删除某个对象  
  145.     public void delete(Class<T> entityClass, PK id) {  
  146.         try {  
  147.             this.getSqlSessionTemplate().delete(  
  148.                     entityClass.getSimpleName() + ".deleteById", id);  
  149.         } catch (RuntimeException re) {  
  150.             logger.error("delete " + entityClass.getName() + "failed :{}", re);  
  151.             throw re;  
  152.         }  
  153.     }  
  154.     // 根据id加载某个对象  
  155.     public T findById(Class<T> entityClass, PK id) {  
  156.         try {  
  157.             return (T) this.getSqlSessionTemplate().selectOne(  
  158.                     entityClass.getSimpleName() + ".findById", id);  
  159.         } catch (RuntimeException re) {  
  160.             logger.error("findById " + entityClass.getName() + "failed :{}",  
  161.                     re);  
  162.             throw re;  
  163.         }  
  164.     }  
  165.   
  166.     // 查找所有的对象  
  167.     public List<T> findAll(Class<T> entityClass) {  
  168.         try {  
  169.             return this.getSqlSessionTemplate().selectList(  
  170.                     entityClass.getSimpleName() + ".findAll");  
  171.         } catch (RuntimeException re) {  
  172.             logger  
  173.                     .error("findAll " + entityClass.getName() + "failed :{}",  
  174.                             re);  
  175.             throw re;  
  176.         }  
  177.     }  
  178.     // 根据查询参数,当前页数,每页显示的数目得到分页列表  
  179.     public PageListData queryPage(Class<T> entityClass, Map param,  
  180.             int currentPage, int pageSize) {  
  181.         try {  
  182.             return new PageListData((Integer)getSqlSessionTemplate()  
  183.                     .selectOne(entityClass.getSimpleName()+".getTotalCounts",param), pageSize, currentPage, this  
  184.                     .getSqlSessionTemplate().selectList(  
  185.                             entityClass.getSimpleName() + ".queryPage", param));  
  186.         } catch (RuntimeException re) {  
  187.             logger.error("findList " + entityClass.getName() + "failed :{}",  
  188.                     re);  
  189.             throw re;  
  190.         }  
  191.     }  
  192. }</pre><br>  
  193. <br>  
  194. <pre></pre>  
  195. <pre></pre>  
  196. <p></p>  
  197. <pre></pre>  
  198. <pre></pre>  
  199. StudentDAOImpl.java<br>  
  200. <p></p>  
  201. <p><span style="font-family:Helvetica,Tahoma,Arial,sans-serif"><span style="font-size:14px; line-height:25px"><br>  
  202. </span></span></p>  
  203. <p><span style="font-family:Helvetica,Tahoma,Arial,sans-serif"><span style="font-size:14px; line-height:25px"></span></span></p>  
  204. <pre name="code" class="java">package com.anxin.dao.impl;  
  205.   
  206. import org.springframework.stereotype.Repository;  
  207.   
  208. import com.anxin.bean.Student;  
  209. import com.anxin.dao.StudentDAO;  
  210.   
  211. @Repository  
  212. public class StudentDAOImpl extends BaseDAOImpl<Student, Integer> implements StudentDAO {  
  213. }  
  214. </pre>  
  215. <pre></pre>  
  216. <pre></pre>  
  217. <pre></pre>  
  218. <pre></pre>  
  219.   
  220. </pre></pre></pre>  
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值