• 今天我们来学习Spring整合Mybatis。

  开发环境:Ide:MyEclipse 2017 CI

      JDK:1.8

   首先我们简单的认识下这两个框架

 1、Mybatis

   MyBatis是一个支持普通SQL查询存储过程高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

  入门:1.所需Jar包 

  

 2、数据库搭建

  

  1. DROP TABLE IF EXISTS `smbms_user`;
  2. CREATE TABLE `smbms_user` (
  3. `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  4. `userCode` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户编码',
  5. `userName` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户名称',
  6. `userPassword` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户密码',
  7. `gender` int(10) DEFAULT NULL COMMENT '性别(1:女、 2:男)',
  8. `birthday` date DEFAULT NULL COMMENT '出生日期',
  9. `phone` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '手机',
  10. `address` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址',
  11. `userRole` bigint(20) DEFAULT NULL COMMENT '用户角色(取自角色表-角色id)',
  12. `createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
  13. `creationDate` datetime(0) DEFAULT NULL COMMENT '创建时间',
  14. `modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
  15. `modifyDate` datetime(0) DEFAULT NULL COMMENT '更新时间',
  16. PRIMARY KEY (`id`) USING BTREE
  17. ) ENGINE = InnoDB AUTO_INCREMENT = 35 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
  18.  
  19. -- ----------------------------
  20. -- Records of smbms_user
  21. -- ----------------------------
  22. INSERT INTO `smbms_user` VALUES (1, 'admin', '系统管理员', '', 1, '1983-10-10', '', '北京市海淀区成府路207号', 1, 1, '2013-03-21 16:52:07', NULL, NULL);
  23. INSERT INTO `smbms_user` VALUES (2, 'liming', '李明', '', 2, '1983-12-10', '', '北京市东城区前门东大街9号', 2, 2, '2014-12-31 19:52:09', NULL, NULL);
  24. INSERT INTO `smbms_user` VALUES (5, 'hanlubiao', '韩路彪', '', 2, '1984-06-05', '', '北京市朝阳区北辰中心12号', 2, 3, '2014-12-31 19:52:09', NULL, NULL);
  25. INSERT INTO `smbms_user` VALUES (6, 'zhanghua', '张华', '', 2, '1983-06-15', '', '北京市海淀区学院路61号', 3, NULL, '2013-02-11 10:51:17', NULL, NULL);
  26. INSERT INTO `smbms_user` VALUES (7, 'wangyang', '王洋', '', 2, '1982-12-31', '', '北京市海淀区西二旗辉煌国际16层', 3, NULL, '2014-06-11 19:09:07', NULL, NULL);
  27. INSERT INTO `smbms_user` VALUES (8, 'zhaoyan', '赵燕', '', 2, '1986-03-07', '', '北京市海淀区回龙观小区10号楼', 3, NULL, '2016-04-21 13:54:07', NULL, NULL);
  28. INSERT INTO `smbms_user` VALUES (10, 'sunlei', '孙磊', '', 3, '1981-01-04', '', '北京市朝阳区管庄新月小区12楼', 3, NULL, '2015-05-06 10:52:07', NULL, NULL);
  29. INSERT INTO `smbms_user` VALUES (11, 'sunxing', '孙兴', '', 3, '1978-03-12', '', '北京市朝阳区建国门南大街10号', 3, NULL, '2016-11-09 16:51:17', NULL, NULL);
  30. INSERT INTO `smbms_user` VALUES (12, 'zhangchen', '张晨', '', 3, '1986-03-28', '', '朝阳区管庄路口北柏林爱乐三期13号楼', 3, NULL, '2016-08-09 05:52:37', 1, '2016-04-14 14:15:36');
  31. INSERT INTO `smbms_user` VALUES (13, 'dengchao', '系邓超', '', 1, '1981-11-04', '', '北京市海淀区北航家属院10号楼', 3, NULL, '2016-07-11 08:02:47', NULL, NULL);
  32. INSERT INTO `smbms_user` VALUES (14, 'yangguo', '系杨过', '', 1, '1980-01-01', '', '北京市朝阳区北苑家园茉莉园20号楼', 3, NULL, '2015-02-01 03:52:07', NULL, NULL);
  33. INSERT INTO `smbms_user` VALUES (15, 'zhaomin', '系赵敏', '', 1, '1987-12-04', '', '北京市昌平区天通苑3区12号楼', 2, NULL, '2015-09-12 12:02:12', NULL, NULL);

 3、导入Log4j配置

  1. log4j.rootLogger=debug, stdout,logfile
  2.  
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  4. log4j.appender.stdout.Target=System.err
  5. log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
  6.  
  7. log4j.appender.logfile=org.apache.log4j.FileAppender
  8. log4j.appender.logfile.File=jbit.log
  9. log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
  10. log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss}%l %F %p %m%n

  4、导入Jdbc配置

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.uri=jdbc\:mysql\://localhost\:3306/smbms?useUnicode\=true&characterEncoding\=utf8
  3. jdbc.name=root
  4. jdbc.pwd=1234

  项目目录:

  Mybatis是一个开源的持久化框架,用于优化项目中的Dao的Impl,替代Dao的为Mapper的接口,具体实现一样,只是名字不一,便于区分

  我们在对应的Mapper中写入具体需要执行的操作,并且建立对应相同名字的Xml文件

  

  

  类:UserMapper.java

    

  1. package com.mapper;
  2.  
  3. import java.util.List;
  4.  
  5. import com.entuty.User;
  6.  
  7. public interface UserMapper {
  8. /*
  9. * 查询所有的用户
  10. */
  11. List<User> Cxall();
  12. }

  UserMapper.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper SYSTEM "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3.  
  4. <mapper namespace="com.mapper.UserMapper">
  5. <select id="Cxall" resultType="User">
  6. select * from smbms_user
  7. </select>
  8. </mapper>

  注意上述4行 需要引入Mapper命名空间,如果在整合Spring时使用的是Mapper 代理的方式需要注意 Id必须和UserMapper中的方法名保持一致。

  创建SqlMapperConfig.xml(Mybatis核心配置文件)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration SYSTEM "http://mybatis.org/dtd/mybatis-3-config.dtd" >
  3. <configuration>
  4. <properties resource="Jdbc.properties"></properties>
  5. <typeAliases> 给当前包中的所有类取别名,别名为类名
  6. <package name="com.entuty" />
  7. </typeAliases>    
  8. <environments default="development">                                配置数据源
  9. <environment id="development">
  10. <transactionManager type="JDBC"></transactionManager>
  11. <dataSource type="POOLED">
  12. <property name="driver" value="${jdbc.driver}" />
  13. <property name="url" value="${jdbc.uri}" />
  14. <property name="username" value="${jdbc.name}" />
  15. <property name="password" value="${jdbc.pwd}" />
  16. </dataSource>
  17. </environment>
  18. </environments>
  19. <mappers>                                      配置映射的Mapper
  20. <mapper resource="com/mapper/UserMapper.xml"/>
  21. </mappers>
  22. </configuration>

  Mybatis环境搭建完毕。

  2、Spring

  导入Spring Jar包 其中的核心包是

  创建业务层和业务层的实现类

  创建Spring核心配置文件 applicationContext.xml

  在Spring发布的时候并未想到和Mybatis整合,而后也没为了mybatis发布版本,所以是由Mybtais 提供的整合。

  1、优化数据源 将数据源转交给Spring容器管理,那么Mybatis配置中的原有配置数据源以及 对应实现类的Mapper.xml都交于Spring容器

  

  1. 1 <?xml version="1.0" encoding="UTF-8"?>
  2. 2 <!DOCTYPE configuration SYSTEM "http://mybatis.org/dtd/mybatis-3-config.dtd" >
  3. 3 <configuration>
  4. 5 <typeAliases> 给当前包中的所有类取别名,别名为类名
  5. 6 <package name="com.entuty" />
  6. 7 </typeAliases>    
  7. 8 </configuration>

  2.applicationContext.xml

  将jdbc配置也使用Spring获取  同时使用Dbcp数据源创建JDBc链接<?xml version="1.0" encoding="UTF-8"?>

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  3. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  5. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
  6. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
  7. <!-- DBCP/C3p0 -->
  8.  
  9. <context:property-placeholder location="jdbc.properties" />
  10. <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
  11. <property name="driverClassName" value="${jdbc.driver}"></property>
  12. <property name="url" value="${jdbc.uri}"></property>
  13. <property name="username" value="${jdbc.name}"></property>
  14. <property name="password" value="${jdbc.pwd}"></property>
  15. </bean>
  16.  
  17.    在Mybatis中 用户执行一个操作的顺序是 首先获取Sqlsessionfactoey
        然后由Selsessionfactory创建 Sqlsession
        之后确认是Mapper代理还是 原生的Steamnemet
        在Spring中配置SqlsessionFactoryBean
  18.  
  19. <!-- 会话工厂通过Spring获取 -->
  20. <!-- 配置org.mybatis.spring.SqlSessionFactoryBean 将会话工厂交给Spring -->
  21. <bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
  22. <!-- 指定Mybatis核心配置文件位置 -->
  23. <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
  24. <!-- 指定数据源 -->
  25. <property name="dataSource" ref="dataSource"></property>
  26. <!-- 加载映射文件 -->
  27. <property name="mapperLocations">
  28. <list>
  29. <value>com/mapper/*.xml</value>
  30. </list>
  31. </property>
  32. </bean>
  33.  
  34. </beans>

  Userserviceimpl.Java

  

  1. package com.service.impl;
  2.  
  3. import java.util.List;
  4.  
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.mybatis.spring.SqlSessionTemplate;
  8. import org.mybatis.spring.support.SqlSessionDaoSupport;
  9.  
  10. import com.entuty.User;
  11. import com.mapper.UserMapper;
  12. import com.service.Userservice;
  13.  
  14. public class Userserviceimpl implements Userservice {
  15.  
  16. private UserMapper userMapper;
  17.  
  18. public void setUserMapper(UserMapper userMapper) {
  19. this.userMapper = userMapper;
  20. }
  21.  
  22. @Override
  23. public List<User> Cxall() {
  24. return userMapper.Cxall();
  25. }
  26.  
  27. }

  对 private UserMapper userMapper; 进行注入

  同时使Spring容器来扫描对应的Mapper

  

  1.   
  2. <bean id="map" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  3. <property name="basePackage" value="com.mapper"></property>
  4. </bean>
  5.  
  6. <!-- 配置工厂 -->
  7. <bean id="sqlFactory" class="com.service.impl.Userserviceimpl">
  8. <property name="userMapper" ref="userMapper" />
  9. </bean>

   测试:

    

  1. package com.Test;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.List;
  6.  
  7. import org.apache.ibatis.io.Resources;
  8. import org.apache.ibatis.session.SqlSession;
  9. import org.apache.ibatis.session.SqlSessionFactory;
  10. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  11. import org.mybatis.spring.SqlSessionFactoryBean;
  12. import org.springframework.context.ApplicationContext;
  13. import org.springframework.context.support.ClassPathXmlApplicationContext;
  14.  
  15. import com.entuty.User;
  16. import com.mapper.UserMapper;
  17. import com.service.Userservice;
  18. import com.service.impl.Userserviceimpl;
  19.  
  20. public class Test {
  21. public static void main(String[] args) {
  22. ApplicationContext ap=new ClassPathXmlApplicationContext("applicationContext.xml");
  23. Userservice us=(Userservice) ap.getBean("sqlFactory");
  24. List<User> arr=us.Cxall();
  25. for (User user : arr) {
  26. System.out.println(user.getUsername());
  27. }
  28. }
  29. }

  结果:

  

  1. DEBUG - Fetching JDBC Connection from DataSource
  2. DEBUG - JDBC Connection [, URL=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring
  3. DEBUG - ==> Preparing: select * from smbms_user
  4. DEBUG - ==> Parameters:
  5. DEBUG - <== Total:
  6. DEBUG - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@757277dc]
  7. DEBUG - Returning JDBC Connection to DataSource
  8. 系统管理员
  9. 李明
  10. 韩路彪
  11. 张华
  12. 王洋
  13. 赵燕
  14. 孙磊
  15. 孙兴
  16. 张晨
  17. 系邓超
  18. 系杨过
  19. 系赵敏
  20. admin
  21. 张三
  22. 张三
  23. 张三啊
  24. 张三啊
  25. 张三啊
  26. 张三啊
  27. 张三啊
  28. 张三啊
  29. 张三啊

  感谢大家,如有问题,敬请大牛指正!

  

Spring整合Mybatis案例,献给初学的朋友的更多相关文章

  1. Spring整合MyBatis案例练习笔记

    需求: 用户登录 技术需求: Servlet+Spring+Mybatis+MVC+jsp+css+html+jquery 数据库设计: 用户表 Sql语句设计: select * from t_us ...

  2. spring基础:什么是框架,框架优势,spring优势,耦合内聚,什么是Ioc,IOC配置,set注入,第三方资源配置,综合案例spring整合mybatis实现

    知识点梳理 课堂讲义 1)Spring简介 1.1)什么是框架 源自于建筑学,隶属土木工程,后发展到软件工程领域 软件工程中框架的特点: 经过验证 具有一定功能 半成品 1.2)框架的优势 提高开发效 ...

  3. Spring整合MyBatis小结

    MyBatis在Spring中的配置 我们在Spring中写项目需要运用到数据库时,现在一般用的是MyBatis的框架来帮助我们书写代码,但是学习了SSM就要知道M指的就是MyBatis,在此,在Sp ...

  4. SpringBoot整合Mybatis案例

    SpringBoot整合Mybatis案例 2019/7/15以实习生身份入职公司前端做Angular ,但是感觉前途迷茫,于是乎学习一下Java的框架——SpringBooot. 参照大神博客:ht ...

  5. Spring学习总结(六)——Spring整合MyBatis完整示例

    为了梳理前面学习的内容<Spring整合MyBatis(Maven+MySQL)一>与<Spring整合MyBatis(Maven+MySQL)二>,做一个完整的示例完成一个简 ...

  6. Spring学习总结(五)——Spring整合MyBatis(Maven+MySQL)二

    接着上一篇博客<Spring整合MyBatis(Maven+MySQL)一>继续. Spring的开放性和扩张性在J2EE应用领域得到了充分的证明,与其他优秀框架无缝的集成是Spring最 ...

  7. 分析下为什么spring 整合mybatis后为啥用不上session缓存

    因为一直用spring整合了mybatis,所以很少用到mybatis的session缓存. 习惯是本地缓存自己用map写或者引入第三方的本地缓存框架ehcache,Guava 所以提出来纠结下 实验 ...

  8. 2017年2月16日 分析下为什么spring 整合mybatis后为啥用不上session缓存

    因为一直用spring整合了mybatis,所以很少用到mybatis的session缓存. 习惯是本地缓存自己用map写或者引入第三方的本地缓存框架ehcache,Guava 所以提出来纠结下 实验 ...

  9. spring整合mybatis错误:class path resource [config/spring/springmvc.xml] cannot be opened because it does not exist

    spring 整合Mybatis 运行环境:jdk1.7.0_17+tomcat 7 + spring:3.2.0 +mybatis:3.2.7+ eclipse 错误:class path reso ...

随机推荐

  1. 深入理解Spring系列之七:web应用自动装配Spring配置

    转载 https://mp.weixin.qq.com/s/Lf4akWFmcyn9ZVGUYNi0Lw 在<深入理解Spring系列之一:开篇>的示例代码中使用如下方式去加载Spring ...

  2. select count(*) from user注入

    先来看一条sql语句: mysql; +------+----------+----------+------------+ | id | username | password | flag | + ...

  3. linux编程之main()函数启动过程【转】

    转自:http://blog.csdn.net/gary_ygl/article/details/8506007 1 最简单的程序  1)编辑helloworld程序,$vim helloworld. ...

  4. 判断Selenium加载完成

    How do you make Selenium 2.0 wait for the page to load? You can also check pageloaded using followin ...

  5. 关于ORA-04091异常的出现原因,以及解决方案

    问题分析 在Oracle中执行DML语句的时候是需要显示进行提交操作的.当我们进行插入的时候,会触发触发器执行对触发器作用表和扩展表的种种操作,但是这个时 候触发器和插入语句是在同一个事务管理中的,因 ...

  6. python安装模块的时候报错error: command 'gcc' failed with exit status 1

    [情况] 在写Python代码的时候,需要用到psutil模块,需要安装. 但是在安装时,报错:error: command 'gcc' failed with exit status 1 [解决步骤 ...

  7. python3.6升级及setuptools、pip安装

    升级python3.6 1.打开官网www.python.org,找到最新3.6.3版本,复制下载链接 2.创建/app目录,wget下载到该目录下,编译安装 mkdir /app cd /app w ...

  8. C++中求类的大小

    今天刷题时看到一题,是求类的大小的,其中涉及了内存的一些知识,记录一下. 正确答案是12和9 首先是内存对齐原则,可以参考这篇博文:http://www.cppblog.com/snailcong/a ...

  9. bug优先级定义

    优先级定义如下: <版本前期阶段>(功能刚提测): [P0—紧急]:完全不能满足产品要求,基本功能明显未实现或完全不可用,阻塞测试流程与进度(核心功能流程) 1.功能未实现 .功能缺失 2 ...

  10. 【Java】if判断boolean类型

    public class Test { public static void main(String[] args) { boolean i=false; boolean j=true; if(i=j ...