[置顶] Struts2+Mybatis+Spring整合增删改查实例

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

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

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

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<typeAliases>
		<typeAlias alias="User" type="com.anxin.bean.User" />
		<typeAlias alias="Student" type="com.anxin.bean.Student" />
	</typeAliases>
	<mappers>
		<mapper resource="com/anxin/orm/mapping/User.xml" />
		<mapper resource="com/anxin/orm/mapping/Student.xml" />
	</mappers>
</configuration>

二、bean的mapper文件

Student.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Student">
	<!-- 
		<resultMap type="Student" id="studentResultMap">
		<id property="id" column="id" />
		<result property="name" column="name" />
		<result property="age" column="age" />
		<result property="sex" column="sex" />
		<result property="address" column="address" />
		</resultMap>
	-->
	<insert id="save" parameterType="Student">
		insert into student(name,age,sex,address)
		values(#{name},#{age},#{sex},#{address})
	</insert>
	<update id="update" parameterType="Student">
		update student set
		name=#{name},age=#{age},sex=#{sex},address=#{address} where
		id=#{id}
	</update>
	<delete id="delete" parameterType="Student">
		delete from student where id=#{id}
	</delete>
	<delete id="deleteById" parameterType="int">
		delete from student where id=#{id}
	</delete>
	<select id="findById" parameterType="int" resultType="Student">
		select * from student where id=#{id}
	</select>
	<select id="findAll" resultType="Student">
		select * from student
	</select>
	<select id="queryPage" resultType="Student" parameterType="map">
		select * from student u
		<where>
			<if test="name!=null and name!='' ">
				u.name like "%"#{name}"%"
			</if>
			<if test="sex!= null and sex!= '' ">and u.sex=#{sex}</if>
		</where>
		limit #{start},#{limit}
	</select>
	<select id="getTotalCounts" parameterType="map"
		resultType="Integer">
		select count(*)from student u
		<where>
			<if test="name!=null and name!='' ">
				u.name like "%"#{name}"%"
			</if>
			<if test="sex!= null and sex!= '' ">and u.sex=#{sex}</if>
		</where>
	</select>
</mapper>


User.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="User">
<!--  
	<resultMap type="User" id="userResultMap">
		<id property="id" column="id" />
		<result property="username" column="username" />
		<result property="password" column="password" />
	</resultMap>
-->
	<insert id="save" parameterType="User">
		insert into users values(#{username},#{password})
	</insert>
	<update id="update" parameterType="User">
		update users set username=#{username},password=#{password} where
		id=#{id}
	</update>
	<delete id="delete" parameterType="User">
		delete from users where id=#{id}
	</delete>
	<delete id="deleteById" parameterType="int">
		delete from users where id=#{id}
	</delete>
	<select id="findById" parameterType="int"
		resultType="User">
		select * from Users where id=#{id}
	</select>
	<select id="findAll" resultType="User">select * from Users</select>
	<select id="queryPage" resultType="User"
		parameterType="map">
		select * from users u
	</select>
	<select id="getTotalCounts" parameterType="map" resultType="Integer">
		select count(*)from users
	</select>
	<select id="login" parameterType="User"
		resultType="User">
		select * from users where username=#{username} and
		password=#{password}
	</select>
</mapper>


三、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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<context:annotation-config></context:annotation-config>
	<context:component-scan base-package="com.anxin.struts.action" />
	<context:component-scan base-package="com.anxin.dao" />
	<context:component-scan base-package="com.anxin.service" />
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:db.properties</value>
			</list>
		</property>
	</bean>
	<!-- 定义使用C3P0连接池的数据源 -->
	<bean id="dataSource"
		class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<!-- 指定连接数据库的JDBC驱动 -->
		<property name="driverClass">
			<value>${driverClass}</value>
		</property>
		<!-- 连接数据库所用的URL -->
		<property name="jdbcUrl">
			<value>${jdbcUrl}</value>
		</property>
		<!-- 连接数据库的用户名 -->
		<property name="user">
			<value>${user}</value>
		</property>
		<!-- 连接数据库的密码 -->
		<property name="password">
			<value>${password}</value>
		</property>
		<!-- 设置数据库连接池的最大连接数 -->
		<property name="maxPoolSize">
			<value>20</value>
		</property>
		<!-- 设置数据库连接池的最小连接数 -->
		<property name="minPoolSize">
			<value>2</value>
		</property>
		<!-- 设置数据库连接池的初始化连接数 -->
		<property name="initialPoolSize">
			<value>2</value>
		</property>
		<!-- 设置数据库连接池的连接的最大空闲时间,单位为秒 -->
		<property name="maxIdleTime">
			<value>20</value>
		</property>
	</bean>
	<bean id="sqlSessionFactory"
		class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation"
			value="classpath:mybatis-config.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>
	

	
	<!-- 数据库的事务管理器配置 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 使用annotation定义数据库事务,这样可以在类或方法中直接使用@Transactional注解来声明事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

四、泛型基类BaseDAOImpl.java
package com.anxin.dao.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

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 com.anxin.dao.BaseDAO;
import com.anxin.util.PageListData;

public class BaseDAOImpl<T, PK extends Serializable> extends
		SqlSessionDaoSupport implements BaseDAO<T, PK> {

	public static Logger logger = LoggerFactory.getLogger(BaseDAOImpl.class);
	@Autowired(required = true)
	@Resource(name = "sqlSessionFactory")
	public void setSuperSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		super.setSqlSessionFactory(sqlSessionFactory);
	}
	// 保存
	public T save(T entity) {
		try {
			getSqlSessionTemplate().insert(
					entity.getClass().getSimpleName() + ".save", entity);
			return entity;
		} catch (RuntimeException re) {
			logger.error("save " + entity.getClass().getName() + " failed :{}",
					re);
			throw re;
		}
	}
	// 更新
	public void update(T entity) {
		try {
			this.getSqlSessionTemplate().update(
					entity.getClass().getSimpleName() + ".update", entity);
		} catch (RuntimeException re) {
			logger.error("update " + entity.getClass().getName()
					+ " failed :{}", re);
			throw re;
		}
	}
	// 删除
	public void delete(T entity) {
		try {
			this.getSqlSessionTemplate().delete(
					entity.getClass().getSimpleName() + ".delete", entity);
		} catch (RuntimeException re) {
			logger.error("delete " + entity.getClass().getName()
					+ " failed :{}", re);
			throw re;
		}
	}

	// 根据id删除某个对象
	public void delete(Class<T> entityClass, PK id) {
		try {
			this.getSqlSessionTemplate().delete(
					entityClass.getSimpleName() + ".deleteById", id);
		} catch (RuntimeException re) {
			logger.error("delete " + entityClass.getName() + "failed :{}", re);
			throw re;
		}
	}
	// 根据id加载某个对象
	public T findById(Class<T> entityClass, PK id) {
		try {
			return (T) this.getSqlSessionTemplate().selectOne(
					entityClass.getSimpleName() + ".findById", id);
		} catch (RuntimeException re) {
			logger.error("findById " + entityClass.getName() + "failed :{}",
					re);
			throw re;
		}
	}

	// 查找所有的对象
	public List<T> findAll(Class<T> entityClass) {
		try {
			return this.getSqlSessionTemplate().selectList(
					entityClass.getSimpleName() + ".findAll");
		} catch (RuntimeException re) {
			logger
					.error("findAll " + entityClass.getName() + "failed :{}",
							re);
			throw re;
		}
	}
	// 根据查询参数,当前页数,每页显示的数目得到分页列表
	public PageListData queryPage(Class<T> entityClass, Map param,
			int currentPage, int pageSize) {
		try {
			return new PageListData((Integer)getSqlSessionTemplate()
					.selectOne(entityClass.getSimpleName()+".getTotalCounts",param), pageSize, currentPage, this
					.getSqlSessionTemplate().selectList(
							entityClass.getSimpleName() + ".queryPage", param));
		} catch (RuntimeException re) {
			logger.error("findList " + entityClass.getName() + "failed :{}",
					re);
			throw re;
		}
	}
}






StudentDAOImpl.java


package com.anxin.dao.impl;

import org.springframework.stereotype.Repository;

import com.anxin.bean.Student;
import com.anxin.dao.StudentDAO;

@Repository
public class StudentDAOImpl extends BaseDAOImpl<Student, Integer> implements StudentDAO {
}




   

你可能感兴趣的:(spring,Hibernate,struts,数据库连接池,delete,encoding)