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

[经验分享] Spring + mybatis整合方案总结 结合实例应用

[复制链接]

尚未签到

发表于 2016-11-27 10:59:02 | 显示全部楼层 |阅读模式
Spring + mybatis整合实例应用
项目结构图 (Spring3.0.2 +mybatis3.0.4)
DSC0000.jpg

方案一: 通过配置文件整合Springmybatis 
应用数据库

--
--
数据库 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&amp;characterEncoding=UTF-8&amp;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上下文的位置并加载它,如果不指定contextConfigLocationContextLoaderListener会到/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目录下.
DSC0001.jpg
数据库表与实体类同上
数据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&amp;characterEncoding=UTF-8&amp;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");
}



至此我们Springmybatis整合实例应用演示完毕
转载请注明出处:[http://www.cnblogs.com/dennisit/archive/2013/04/10/3012972.html]

运维网声明 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-306122-1-1.html 上篇帖子: 解决MyBatis的Mapper XML错误,系统起不来,也不报错问题 下篇帖子: mybatis批量查询以及更新的写法及XML
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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