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 { }

剩下的代码基本跟以前的相同就不帖了

源码可以去点击打开链接下载


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringCloud是一个基于Spring框架的开发工具集合,可以用于构建分布式系统的各个组件。Thymeleaf是一种用于构建Java应用程序的Java模板引擎,用于将数据渲染到HTML页面上。MyBatis-Plus是一个基于MyBatis框架的增强工具,提供了一些便捷的功能,如自动生成SQL语句、分页查询等。 在SpringCloud中,我们可以使用Thymeleaf来构建前端页面,通过MyBatis-Plus来操作数据库进行增删改查操作。 首先,我们需要在SpringCloud项目中引入Thymeleaf的依赖,并配置Thymeleaf的相关属性,如模板文件的存放位置、前缀后缀等。然后我们可以创建一个Controller类,使用@RequestMapping注解来处理请求,并返回视图模板。在视图模板中,我们可以使用Thymeleaf的语法来渲染数据,如插入变量、循环、条件判断等。 在MyBatis-Plus中,我们需要引入MyBatis-Plus的依赖,并配置MyBatis的相关属性,如数据库连接信息、Mapper接口扫描路径等。然后我们可以创建一个Mapper接口,使用@Mapper注解来标识该接口是一个Mapper,并编写相应的增删改查方法。MyBatis-Plus提供了一些注解,如@Select、@Insert、@Update、@Delete等,可以通过这些注解来实现对数据库的操作。 在Controller类中,我们可以通过@Autowired注解来注入Mapper接口,并调用相应的方法来实现对数据库增删改查操作。通过前端页面的请求,Controller类将数据传递给Thymeleaf视图模板进行渲染,最后将渲染后的页面返回给前端展示。 通过SpringCloud、Thymeleaf、MyBatis-Plus的结合使用,我们可以方便地实现对数据库增删改查操作,并将数据展示在前端页面上,实现一个完整的CRUD功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值