Spring + mybatis整合方案总结 结合实例应用
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测试数据">发送邮件</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测试数据">发送邮件</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://HdhCmsTestspringframework.org/schema/beans"
xmlns:xsi ="http://HdhCmsTestw3.org/2001/XMLSchema-instance"
xmlns:p ="http://HdhCmsTestspringframework.org/schema/p"
xsi:schemaLocation ="http://HdhCmsTestspringframework.org/schema/beans http://HdhCmsTestspringframework.org/schema/beans/spring-beans-3.0.xsd" >
<!-- 配置数据源 -->
< bean id ="dataSource" class ="org.apache测试数据mons.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测试数据/xml/ns/javaee"
xmlns:xsi ="http://HdhCmsTestw3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://java.sun测试数据/xml/ns/javaee
http://java.sun测试数据/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测试数据">发送邮件</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测试数据">发送邮件</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测试数据">发送邮件</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测试数据" );
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测试数据">发送邮件</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://HdhCmsTestspringframework.org/schema/beans"
xmlns:xsi ="http://HdhCmsTestw3.org/2001/XMLSchema-instance"
xmlns:p ="http://HdhCmsTestspringframework.org/schema/p"
xsi:schemaLocation ="http://HdhCmsTestspringframework.org/schema/beans http://HdhCmsTestspringframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 配置数据源 -->
<bean id="dataSource" class ="org.apache测试数据mons.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测试数据/xml/ns/javaee"
xmlns:xsi ="http://HdhCmsTestw3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://java.sun测试数据/xml/ns/javaee
http: // java.sun测试数据/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://HdhCmsTestcnblogs测试数据/dennisit/archive/2013/04/10/3012972.html ]
热爱生活,热爱Coding,敢于挑战,用于探索 ...
分类: JavaEE
标签: spring , mybatis
作者: Leo_wl
出处: http://HdhCmsTestcnblogs测试数据/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息查看更多关于Spring + mybatis整合方案总结 结合实例应用的详细内容...