Spring + mybatis整合方案总结 结合实例应用
Spring + mybatis整合实例应用
项目结构图 (Spring3.0.2 +mybatis3.0.4)
方案一: 通过配置文件整合Spring和mybatis
应用数据库

--
--数据库 tb_user
-- drop table if exists tb_user; create table tb_user(
id int primary key auto_increment comment '主键',
username varchar(40) not null unique comment '用户名',
password varchar(40) not null comment '密码',
email varchar(40) comment '邮件',
age int comment '年龄',
sex char(2) not null comment '性别'
);

对应的实体类

package com.icreate.entity;
/**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 上午11:15:50
*
* @function: TODO
*
*/
public class User { private int id;
private String username;
private String password;
private String sex;
private String email;
private int age; //getter() and setter ()
}

数据Dao接口

package com.icreate.dao; import java.util.List; import com.icreate.entity.User; /**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 上午11:36:34
*
* @function: TODO
*
*/
public interface UserDao { public int insert(User user); public int update(User user); public int delete(String userName); public List<User> selectAll(); public int countAll(); public User findByUserName(String userName); }

在config目录下进行Mapper文件配置

<?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="com.icreate.dao.UserDao">
<select id="countAll" resultType="int"> <!-- 查询表中记录总数 -->
select count(*) c from tb_user;
</select> <select id="selectAll" resultType="com.icreate.entity.User"> <!-- 查询表中的所有用户 -->
select * from tb_user order by username asc
</select> <insert id="insert" parameterType="com.icreate.entity.User"> <!-- 向数据库中插入用户 -->
insert into tb_user(username,password,email,sex,age) values(#{username},#{password},#{email},#{sex},#{age})
</insert> <update id="update" parameterType="com.icreate.entity.User"> <!-- 更新库中的用户 -->
update tb_user set username=#{username},password=#{password},email=#{email},sex=#{sex},age=#{age} where username=#{username}
</update> <delete id="delete" parameterType="String"> <!-- 删除用户 -->
delete from tb_user where username=#{username}
</delete> <select id="findByUserName" parameterType="String" resultType="com.icreate.entity.User"> <!-- 根据用户名查找用户 -->
select * from tb_user where username=#{username}
</select>
</mapper>

Mybatis应用配置文件MyBatis-Configuration.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>
<mappers>
<mapper resource="com/icreate/dao/UserDao.xml"/>
</mappers>
</configuration>

Spring配置文件,本例中我们放在/WebRoot/WEB-INF/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-3.0.xsd"> <!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/db_mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean> <bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:MyBatis-Configuration.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean> <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.icreate.dao.UserDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean> <bean id="userService" class="com.icreate.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean> </beans>

同目录下的web.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"> <context-param>
<param-name>contextConfigLocation</param-name>
<!-- applicationContext.xml文件在/WEB-INF/目錄下時可以這樣配置,-->
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param> <!-- 配置上下文监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

配置说明:
<context-param/> 节点配置contextConfigLocation属性是为了让ContextLoaderListener找到Spring上下文的位置并加载它,如果不指定contextConfigLocation,ContextLoaderListener会到/WEB-INF/目录下找applicationContext.xml来加载。
<listener/> 节点上配了ContextLoaderListener。它实现了ServletContextListener接口,所以web server启动时ContextLoaderListener能读取到ServletContext,也就能通过<context-param/>指定的Spring上下文的路径来找到上下文并加载它。
当然,如果你不需要Spring来管理你的Bean,可以去掉上面两个节点。
定义service接口

package com.icreate.service; import java.util.List; import com.icreate.entity.User; /**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 下午03:52:07
*
* @function: TODO
*
*/
public interface UserService { public int insert(User user); public int update(User user); public int delete(String userName); public List<User> selectAll(); public int countAll(); public User findByUserName(String userName);
}

实现service接口,执行dao操作

package com.icreate.service.impl; import java.util.List; import com.icreate.dao.UserDao;
import com.icreate.entity.User;
import com.icreate.service.UserService; /**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 下午03:53:26
*
* @function: TODO
*
*/
public class UserServiceImpl implements UserService{ private UserDao userDao; public UserDao getUserDao() {
return userDao;
} public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} public int countAll() {
return this.userDao.countAll();
} public int delete(String userName) {
return this.userDao.delete(userName);
} public User findByUserName(String userName) {
return this.userDao.findByUserName(userName);
} public int insert(User user) {
return this.userDao.insert(user);
} public List<User> selectAll() {
return this.userDao.selectAll();
} public int update(User user) {
return this.userDao.update(user);
} }

接下来写我们的测试用例

package com.icreate.service; import java.util.List; import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext; import com.icreate.entity.User; /**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 下午05:16:28
*
* @function: TODO
*
*/
public class SpringBatis { ApplicationContext context = null;
UserService userService = null; @Before
public void initContext(){
this.context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
this.userService = (UserService) context.getBean("userService");
} @Test
public void countAll(){
System.out.println("数据库中的记录条数:" + userService.countAll());
} @Test
public void insert(){
User user = new User();
user.setUsername("苏若年");
user.setPassword("passtest");
user.setEmail("dennisit@163.com");
user.setSex("男");
user.setAge(23);
userService.insert(user);
} @Test
public void selectAll(){
List<User> list = userService.selectAll();
for(int i=0; i<list.size(); i++){
User user = list.get(i);
System.out.println("用户名:" + user.getUsername() + "\t密码:" + user.getPassword() + "\t邮箱:" + user.getEmail());
}
} @Test
public void update(){
User user = new User();
user.setUsername("苏若年");
user.setPassword("xxxxxxxx");
user.setEmail("xxxxxx@163xxx");
user.setSex("男");
user.setAge(23);
userService.update(user);
} @Test
public void delete(){
userService.delete("苏若年");
} @Test
public void findByName(){
User user = userService.findByUserName("苏若年");
System.out.println("用户名:" + user.getUsername() + "\t密码:" + user.getPassword() + "\t邮箱:" + user.getEmail()); }
}

方案二:使用注解整合
这次将配置文件放置在config目录下.
数据库表与实体类同上
数据dao接口定义

package com.icreate.dao; import java.util.List; import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import com.icreate.entity.User; /**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 上午11:36:34
*
* @function: TODO
*
*/
public interface UserDao { @Insert("insert into tb_user(username,password,email,sex,age) values(#{username},#{password},#{email},#{sex},#{age})")
public int insert(User user); @Update("update tb_user set username=#{username},password=#{password},email=#{email},sex=#{sex},age=#{age} where username=#{username}")
public int update(User user); @Delete("delete from tb_user where username=#{username}")
public int delete(String userName); @Select("select * from tb_user ")
public List<User> selectAll(); @Select("select count(*) from tb_user")
public int countAll(); @Select("select * from tb_user where username=#{username}")
public User findByUserName(String userName); }

Service接口与实现不变.
Spring配置文件内容如下

<?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-3.0.xsd"> <!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/db_mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean> <bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean> <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.icreate.dao.UserDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean> <bean id="userService" class="com.icreate.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean> </beans>

Web.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"> <context-param>
<param-name>contextConfigLocation</param-name>
<!-- applicationContext.xml文件在/WEB-INF/目錄下時可以這樣配置,-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <!-- 配置上下文监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> </web-app>

测试类大致上没有变化,只是ApplicationContext初始化的方法改变成了下面方式

ApplicationContext context = null;
UserService userService = null; @Before
public void initContext(){
this.context = new ClassPathXmlApplicationContext("applicationContext.xml");
//this.context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
this.userService = (UserService) context.getBean("userService");
}

至此我们Spring与mybatis整合实例应用演示完毕
转载:[http://www.cnblogs.com/dennisit/archive/2013/04/10/3012972.html]
Spring + mybatis整合方案总结 结合实例应用的更多相关文章
- SpringMVC+Spring+MyBatis整合完整版Web实例(附数据)
最近段时间正在学习Spring MVC和MyBatis的一些知识.自己也在网络上面找了一些例子来练习.但是都不是很完整.所以,今天,自己也抽空写了个完成的关于Spring MVC + Spring + ...
- 3.springMVC+spring+Mybatis整合Demo(单表的增删该查,这里主要是贴代码,不多解释了)
前面给大家讲了整合的思路和整合的过程,在这里就不在提了,直接把springMVC+spring+Mybatis整合的实例代码(单表的增删改查)贴给大家: 首先是目录结构: 仔细看看这个目录结构:我不详 ...
- Spring+Mybatis+SpringMVC+Maven+MySql搭建实例
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要讲了如何使用Maven来搭建Spring+Mybatis+SpringMVC+M ...
- SpringMVC+Spring+Mybatis整合
SpringMVC+Spring+Mybatis整合 导包 配置jdbc.properties.log4j.properties jdbc.driver=com.mysql.jdbc.Driver j ...
- SSM 即所谓的 Spring MVC + Spring + MyBatis 整合开发。
SSM 即所谓的 Spring MVC + Spring + MyBatis 整合开发.是目前企业开发比较流行的架构.代替了之前的SSH(Struts + Spring + Hibernate) 计划 ...
- Spring+Mybatis整合时 Failed to read candidate component class,Caused by:IllegalArgumentException
Spring+Mybatis整合时Caused by: java.lang.IllegalArgumentException错误 org.springframework.beans.factory.B ...
- 【转】Spring+Mybatis+SpringMVC+Maven+MySql搭建实例
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要讲了如何使用Maven来搭建Spring+Mybatis+SpringMVC+M ...
- Springmvc+Spring+Mybatis整合开发(架构搭建)
Springmvc+Spring+Mybatis整合开发(架构搭建) 0.项目结构 Springmvc:web层 Spring:对象的容器 Mybatis:数据库持久化操作 1.导入所有需要的jar包 ...
- SpringMVC + Spring + MyBatis 整合 + Spring shrio + easyUI + 权限管理框架,带shrio session和shrio cache集群实现方案
工作之余先来写了一个不算规范的简单架子 基于spring mvc + spring + mybatis + Spring shrio 基于redis的集群方案 系统权限部分,分成多个机构,其中每个机构 ...
随机推荐
- JS判断图片是否加载完成三种方式
1.img的complete属性 轮询不断监测img的complete属性,如果为true则表明图片已经加载完毕,停止轮询.该属性所有浏览器都支持. <p id="p1"&g ...
- RTSP协议资料
维基百科: RTSP:http://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol RTP:http://en.wikipedia.org/wik ...
- C# 导出word文档及批量导出word文档(3)
在初始化WordHelper时,要获取模板的相对路径.获取文档的相对路径多个地方要用到,比如批量导出时要先保存文件到指定路径下,再压缩打包下载,所以专门写了个关于获取文档的相对路径的类. #regio ...
- PHP 初学者的学习线路和建议【1】
先来看下PHP初学者的学习线路: (1) 熟悉HTML/CSS/JS等网页基本元素,完成阶段可自行制作简单的网页,对元素属性相对熟悉. (2) 理解动态语言的概念和运做机制,熟悉基本的PHP语法. ( ...
- linux上ln命令详细说明
ln是linux中又一个非常重要命令,它的功能是为某一个文件在另外一个位置建立一个同不的链接,这个命令最常用的参数是-s,具体用法是:ln –s 源文件 目标文件. 当我们需要在不同的目录,用到相同的 ...
- DEDE提高生成HTmL的速度
1.找到include/inc/inc_fun_SpGetArcList.php打开之. 2.查找以下代码: for($i=0;$i<$ridnum;$i++){ if($tps ...
- git生成密钥
安装 Git-1.9.4-preview20140611 1 通过 ssh-keygen 但生成的位置却是C:\Users\Admin\AppData\Local\VirtualStore\Progr ...
- python os.walk()遍历
os.walk()遍历 import os p='/bin' #设定一个路径 for i in os.walk(p): #返回一个元组 print (i) # i[0]是路径 i[1]是文件夹 i[2 ...
- [转] c#多线程(UI线程,控件显示更新) Invoke和BeginInvoke 区别
如果只是直接使用子线程访问UI控件,直接看内容三,如果想深入了解从内容一看起. 一.Control.Invoke和BeginInvoke方法的区别 先上总结: Control.Invoke 方法 (D ...
- asp.net core VS goang web[修正篇]
先前写过一篇文章:http://www.cnblogs.com/gengzhe/p/5557789.html,也是asp.net core和golang web的对比,热心的园友提出了几点问题,如下: ...