设为首页 收藏本站
查看: 1205|回复: 0

[经验分享] Struts2+Mybatis+Spring整合增删改查实例

[复制链接]

尚未签到

发表于 2016-11-27 10:20:19 | 显示全部楼层 |阅读模式
  在我的博客首页有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 setname=#{name},age=#{age},sex=#{sex},address=#{address} whereid=#{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} whereid=#{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} andpassword=#{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 {
}
  剩下的代码基本跟以前的相同就不帖了
  源码可以去点击打开链接下载
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-306084-1-1.html 上篇帖子: mybatis 源码分析之 Mapper接口 下篇帖子: 避免mybatis generator生成Example类的配置方法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表