思路

  1. 数据库连接池交给 Spring 管理
  2. SqlSessionFactory 交给 Spring 管理
  3. 从 Spring 容器中直接获得 mapper 的代理对象

步骤

  1. 创建工程
  2. 导入 jar
  3. 创建 config 文件夹,放置配置文件
    • 配置文件:

      • jdbc.properties : 数据库配置
        jdbc.driverClass=com.mysql.cj.jdbc.Driver
        jdbc.url=jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC
        jdbc.username=root
        jdbc.password=root
      • log4j.properties :日志打印
      • mybatis_config.xml:myBatis 配置,只需要配置二级缓存就可以了,其他都交给 Spring 处理。
        <?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>    <!-- 开启二级缓存 -->   
        <settings>       
        <setting name="cacheEnabled" value="true" />   
        </settings>
        </configuration>
      • applicationContext.xml: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:aop="http://www.springframework.org/schema/aop"   
        xmlns:tx="http://www.springframework.org/schema/tx"   
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="                          
        http://www.springframework.org/schema/beans                           
        http://www.springframework.org/schema/beans/spring-beans.xsd                           
        http://www.springframework.org/schema/context                           
        http://www.springframework.org/schema/context/spring-context.xsd                           
        http://www.springframework.org/schema/aop                           
        http://www.springframework.org/schema/aop/spring-aop.xsd                           
        http://www.springframework.org/schema/tx                           
        http://www.springframework.org/schema/tx/spring-tx.xsd">   
        <!-- 加载配置文件 -->   
        <context:property-placeholder location="classpath:config/jdbc.properties" />   
        <!-- 数据库连接池 -->   
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">       
        <property name="driverClassName"
        value="${jdbc.driverClass}" />       
        <property name="url" value="${jdbc.url}" />       
        <property name="username" value="${jdbc.username}" />       
        <property name="password" value="${jdbc.password}" />       
        <property name="maxActive" value="10" />       
        <property name="maxIdle" value="5" />   
        </bean>   
        <!-- 配置 sqlSessionFactory -->   
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">       
        <!-- 配置 mybatis 核心配置文件 -->       
        <property name="configLocation" value="classpath:config/mybatis_config.xml" />       
        <!-- 配置数据源 -->       
        <property name="dataSource" ref="dataSource" />       
        </bean>   
        </beans>
  4. DAO 开发
    1. 创建 POJO User.java

      public class User {   
      private Integer id;   
      private String username;   
      private Date birthday;   
      private String address;   
      private boolean sex;   
      public boolean isSex() {       
      return sex;   
      }   
      public void setSex(boolean sex) {      
      this.sex = sex;   
      }   
      public Integer getId() {       
      return id;   
      }   
      public void setId(Integer id) {      
      this.id = id;  
      }   
      public String getUsername() {       
      return username;  
      }   
      public void setUsername(String username) {      
      this.username = username;   
      }   
      public Date getBirthday() {     
      return birthday;  
      }   
      public void setBirthday(Date birthday) {     
      this.birthday = birthday;   
      }   
      public String getAddress() {    
      return address;   
      }   
      public void setAddress(String address) {      
      this.address = address;  
      }   
      @Override   
      public String toString() {       
      return "User{" +                "id=" + id +                ", username='" + username + '\'' +                ", birthday=" + birthday +                ", address='" + address + '\'' +                ", sex=" + sex +                '}';   
      }
      }
    2. 在 applicatonContext.xml 中配置别名扫描

    3. 实现 UserMapper 接口

      public interface UserMapper {   
      User quertUserById(int id);    List<User> queryUserByUserName(String username);    void saveUser(User user);
      }
    4. 实现 UserMapper.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="cc.lijingbo.ssm.mapper.UserMapper">   
      <select id="quertUserById" parameterType="int" resultType="user">       
      select * from user where id = #{id}   
      </select>   
      <select id="queryUserByUserName" resultType="user" parameterType="String">       
      select * from user where username like '%${value}%'   
      </select>   
      <insert id="saveUser" parameterType="user">       
      <selectKey keyProperty="id" keyColumn="id" order="AFTER"   resultType="int">           
      select last_insert_id()       
      </selectKey>       
      insert into user (username,sex,address) values (#{username},#{sex},#{address})   
      </insert>
      </mapper>
    5. 在 applicationContext.xml 中配置 mapper 扫描

    6. 测试

      public class UserMapperTest {   
      ApplicationContext applicationContext;   
      @Before   
      public void setUp() throws Exception {       
      applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
      }   
      @Test   
      public void quertUserById() {       
      UserMapper userMapper =
      applicationContext.getBean(UserMapper.class);       
      User user = userMapper.quertUserById(3);       
      System.out.println(user);   
      }   
      @Test   
      public void queryUserByUserName() {       
      UserMapper userMapper = applicationContext.getBean(UserMapper.class);       
      List<User> users = userMapper.queryUserByUserName("张");       
      for (User u : users) {          
      System.out.println(u);      
      }   
      }   
      @Test   
      public void saveUser() {       
      UserMapper userMapper = applicationContext.getBean(UserMapper.class);       
      User user = new User();       
      user.setUsername("刘备");      
      user.setAddress("深圳XXX");      
      user.setSex(false);      
      userMapper.saveUser(user); 
      }
      }

源码 github 地址

Spring 整合 myBatis的更多相关文章

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

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

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

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

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

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

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

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

  5. 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 ...

  6. spring 整合Mybatis 《报错集合,总结更新》

    错误:java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldExcepti ...

  7. spring整合mybatis(hibernate)配置

    一.Spring整合配置Mybatis spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位.一般需要具备如下几个基本配置. 1. ...

  8. spring 整合 mybatis 中数据源的几种配置方式

    因为spring 整合mybatis的过程中, 有好几种整合方式,尤其是数据源那块,经常看到不一样的配置方式,总感觉有点乱,所以今天有空总结下. 一.采用org.mybatis.spring.mapp ...

  9. Mybatis学习(六)————— Spring整合mybatis

    一.Spring整合mybatis思路 非常简单,这里先回顾一下mybatis最基础的根基, mybatis,有两个配置文件 全局配置文件SqlMapConfig.xml(配置数据源,全局变量,加载映 ...

  10. Spring整合MyBatis 你get了吗?

    Spring整合MyBatis 1.整体架构dao,entity,service,servlet,xml 2..引入依赖 <dependencies> <dependency> ...

随机推荐

  1. 关于python模块总结

    名词解释 模块(module):在python中,一个.py文件就是一个模块 包(package):为了避免模块名冲突,Python又引入了按目录来组织模块的方法.当目录下存在__init__.py, ...

  2. C++学习(1)—— 初识C++

    1. 变量 作用:给一段指定的内存空间起名,方便操作这段内存空间 语法:数据类型 变量名称=变量初始值​ #include<iostream> using namespace std; i ...

  3. java处理异常的机制关键字为throw和throws

    在异常处理的过程中,throws和throw的区别是? throws:是在方法上对一个方法进行声明,而不进行处理,而是向上传,谁调用谁处理. throw:是在具体的抛出一个异常类型. throws的栗 ...

  4. ARTS-week7

    Algorithm 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. Two Sum 编写一个 SQL 查询,满足条件:无论 ...

  5. danci3

    permit 英 [pə'mɪt] 美 [pɚ'mɪt] vi. 许可:允许 vt. 许可:允许 n. 许可证,执照 encapsulate 英 [ɪn'kæpsjʊleɪt; en-] 美 [ɪn' ...

  6. SSM框架--Spring+SpringMVC+Mybatis (IDEA)搭建

    使用idea创建一个maven项目( 这里演示 的是 web项目) 点击 Finish 然后开始配置 pom.xml文件(添加各种依赖jar包) 先去找 spring 所需的 jar包 jar包中心仓 ...

  7. intellij idea 搜索快捷键

    Ctrl+N按名字搜索类 1 相当于eclipse的ctrl+shift+R,输入类名可以定位到这个类文件 2 就像idea在其它的搜索部分的表现一样,搜索类名也能对你所要搜索的内容多个部分进行匹配 ...

  8. Optimal Marks SPOJ - OPTM(最小割)

    传送门 论文<最小割模型在信息学竞赛中的应用>原题 二进制不同位上互不影响,那么就按位跑网络流 每一位上,确定的点值为1的与S连一条容量为INF的有向边.为0的与T连一条容量为INF的有向 ...

  9. Redis-基础介绍

    Redis 基础介绍 一.Redis介绍 二.Redis和Memecache的不同 三.Redis的最佳应用场景: 四.Redis支持的键值类型 五.安装Redis 六.Redis启动方式 七.Red ...

  10. 函数(定义、参数、return、变量、作用域、预解析)

    一.函数定义 1.方式一       function 函数名(参数){  函数体  }——————函数声明的方法 function fn(a){ console.log(a); }: 2.方式二  ...