zoukankan      html  css  js  c++  java
  • Unit08: Spring集成mybatis

        Unit08: Spring集成mybatis    

    1. Spring集成mybatis

    (1)方式一

    step1. 导包。
    spring-webmvc,mybatis,mybatis-spring, ojdbc,dbcp,spring-jdbc,junit。

    step2. 添加spring的配置文件。
    注:集成之后,不再需要mybatis的配置文件了,之前的配置信息 用一个bean(SqlSessionFactoryBean)来代替。

    step3.实体类。
    step4.映射文件。
    step5.Mapper映射器。
    step6.配置MapperScannerConfigurer。

    注:该bean负责调用SqlSession的getMapper方法,获得 符合Mapper映射器要求的对象。并且会将这些对象放到spring 容器里面(默认的id是首字母小写之后的接口名,比如Mapper 映射器名为EmpDAO,则默认的id是empDAO,也可以使用@Repository 来修改默认的id)。
    注:如果只扫描特定的映射器,可以做如下两步。
    step1.开发一个注解,比如@MyBatisRepository,并且,将 该注解添加到需要扫描的映射器上面。

    注入annotationClass属性值。

    代码:

    src/main/java

    annotations

    package annotations;
    
    public @interface MyBatisRepository {
    
    }
    MyBatisRepository.java

    dao

    package dao;
    
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.stereotype.Repository;
    
    import annotations.MyBatisRepository;
    import entity.Employee;
    import entity.Employee2;
    
    /**
     * Mapper映射器
     *
     */
    @Repository("empDAO")
    @MyBatisRepository
    public interface EmployeeDAO {
        public void save(Employee e);
        public List<Employee> findAll();
        public Employee findById(int id);
        public void modify(Employee e);
        public void delete(int id);
        public Map findById2(int id);
        public Employee2 findById3(int id);
    }
    EmployeeDAO.java

    entity

    package entity;
    
    public class Employee {
        private Integer id;
        private String name;
        private Integer age;
        
        @Override
        public String toString() {
            return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        
    }
    Employee.java
    package entity;
    
    public class Employee2 {
        private Integer empNo;
        private String ename;
        private Integer age;
        
        @Override
        public String toString() {
            return "Employee2 [empNo=" + empNo + ", ename=" + ename + ", age=" + age + "]";
        }
        
        public void setEmpNo(Integer empNo) {
            this.empNo = empNo;
        }
        public void setEname(String ename) {
            this.ename = ename;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        
    }
    Employee2.java
    <?xml version="1.0" encoding="UTF-8" ?>  
    <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
     "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
    
    <mapper namespace="dao.EmployeeDAO">
        <!-- 
            id:要求唯一
            parameterType:参数类型,要写类的完整的名称。
         -->
        <insert id="save" 
            parameterType="entity.Employee">
            INSERT INTO emp_czh 
            VALUES(emp_czh_seq.nextval,#{name},#{age})
        </insert>
        
        <!-- 
            resultType:返回类型,要写类的完整的名称。
         -->
        <select id="findAll" 
            resultType="entity.Employee">
            SELECT * FROM emp_czh
        </select>
        
        <select id="findById" 
            parameterType="int" 
            resultType="entity.Employee">
            SELECT * FROM emp_czh
            WHERE id = #{id1}
        </select>
        
        <update id="modify" 
            parameterType="entity.Employee">
            UPDATE emp_czh SET name = #{name},
            age = #{age} WHERE id = #{id}
        </update>
        
        <delete id="delete" parameterType="int">
            DELETE FROM emp_czh WHERE id = #{id1}
        </delete>
        
        <!-- 返回Map类型的结果 -->
        <!-- 
            map是java.util.Map的简写形式
         -->
        <select id="findById2" parameterType="int"
            resultType="map">
            SELECT * FROM emp_czh WHERE id = #{id1}
        </select>
        
        <!-- 
            resultMap告诉mybatis表的字段名
            与实体类的属性名的对应关系。
            (如果表的字段名与属性名相同,则不用写了)
         -->
        <resultMap type="entity.Employee2" 
            id="empResultMap">
            <result property="empNo" column="id"/>
            <result property="ename" column="name"/>
        </resultMap>
        
        <select id="findById3" parameterType="int"
            resultMap="empResultMap">
            SELECT * FROM emp_czh WHERE id = #{id1}
        </select>
    </mapper>
    EmpMapper.xml

    src/mian/resources

    # db connection parameters
    # key=value
    driver=oracle.jdbc.driver.OracleDriver
    url=jdbc:oracle:thin:@192.168.201.227:1521:orcl
    user=openlab
    pwd=open123
    # datasource parameters
    initSize=1
    maxSize=1
    db.properties
    <?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:context="http://www.springframework.org/schema/context" 
        xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
        xmlns:jee="http://www.springframework.org/schema/jee" 
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:util="http://www.springframework.org/schema/util"
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
        <!-- 读取db.properties文件 -->
        <util:properties id="db" 
        location="classpath:db.properties"/>
        <!-- 配置连接池 -->
        <bean id="ds" 
        class="org.apache.commons.dbcp.BasicDataSource"       
           destroy-method="close">       
          <property name="driverClassName" 
              value="#{db.driver}" />      
          <property name="url" 
              value="#{db.url}" />      
          <property name="username" 
              value="#{db.user}" />      
          <property name="password" 
              value="#{db.pwd}" />      
        </bean> 
        <!-- 配置SqlSessionFactoryBean -->
        <bean id="ssfb" 
            class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入连接池 -->
            <property name="dataSource" ref="ds"/>
            <!-- 注入映射文件的位置信息 -->
            <property name="mapperLocations"
            value="classpath:entity/*.xml"/>
        </bean>
        <!-- 配置MapperScannerConfigurer -->
        <bean 
        class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 注入要扫描的包名 -->
            <property name="basePackage"
            value="dao"/>
            <!-- 只扫描带有该注解的映射器 -->
            <property name="annotationClass"
            value="annotations.MyBatisRepository"/>
        </bean>
    </beans>
    spring-mybatis.xml

    src/test/java

    test

    package test;
    
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import dao.EmployeeDAO;
    import entity.Employee;
    
    public class TestCase {
        private EmployeeDAO dao;
        @Before
        public void init(){
            ApplicationContext ac = 
                new ClassPathXmlApplicationContext(
                    "spring-mybatis.xml");
            dao = ac.getBean("empDAO",
                    EmployeeDAO.class);
        }
        @Test
        public void test1(){
            List<Employee> emps = 
                    dao.findAll();
            System.out.println(emps);
        }
        @Test
        public void test2(){
            Employee e = new Employee();
            e.setName("Rod Johnson");
            e.setAge(40);
            dao.save(e);
        }
    }
    TestCase.java
      <dependencies>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-webmvc</artifactId>
              <version>3.2.8.RELEASE</version>
          </dependency>
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis</artifactId>
              <version>3.2.8</version>
          </dependency>
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis-spring</artifactId>
              <version>1.2.2</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-jdbc</artifactId>
              <version>3.2.8.RELEASE</version>
          </dependency>
          <dependency>
              <groupId>com.oracle</groupId>
              <artifactId>ojdbc14</artifactId>
              <version>10.2.0.4.0</version>
          </dependency>
          <dependency>
              <groupId>commons-dbcp</groupId>
              <artifactId>commons-dbcp</artifactId>
              <version>1.4</version>
          </dependency>
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.12</version>
          </dependency>
      </dependencies>
    pom.xml

    (2)方式二

    step1. 导包。
    spring-webmvc,mybatis,mybatis-spring, ojdbc,dbcp,spring-jdbc,junit。

    step2. 添加spring的配置文件。
    注:集成之后,不再需要mybatis的配置文件了,之前的配置信息 用一个bean(SqlSessionFactoryBean)来代替。

    step3.实体类。
    step4.映射文件。
    step5.Mapper映射器。
    step6.写映射器的实现类。

    SqlSessionTemplate注入到实现类中,然后调用 SqlSessionTemplate的方法即可。
    step7.配置SqlSessionTemplate。

    代码:

    src/main/java

    annotations

    package annotations;
    
    public @interface MyBatisRepository {
    
    }
    MyBatisRepository.java

    dao

    package dao;
    
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.stereotype.Repository;
    
    import annotations.MyBatisRepository;
    import entity.Employee;
    import entity.Employee2;
    
    /**
     * Mapper映射器
     *
     */
    public interface EmployeeDAO {
        public void save(Employee e);
        public List<Employee> findAll();
        public Employee findById(int id);
        public void modify(Employee e);
        public void delete(int id);
        public Map findById2(int id);
        public Employee2 findById3(int id);
    }
    EmployeeDAO.java
    package dao;
    
    import java.util.List;
    import java.util.Map;
    
    import javax.annotation.Resource;
    
    import org.mybatis.spring.SqlSessionTemplate;
    import org.springframework.stereotype.Repository;
    
    import entity.Employee;
    import entity.Employee2;
    
    @Repository("empDAO")
    public class EmployeeDAOMybatisImpl implements 
    EmployeeDAO{
        
        @Resource(name="sst")
        private SqlSessionTemplate sst;
        
        public void save(Employee e) {
            sst.insert("dao.EmployeeDAO.save",
                    e);
        }
    
        public List<Employee> findAll() {
            return sst.selectList(
                    "dao.EmployeeDAO.findAll");
        }
    
        public Employee findById(int id) {
            return sst.selectOne(
                    "dao.EmployeeDAO.findById", id);
        }
    
        public void modify(Employee e) {
            sst.update("dao.EmployeeDAO.modify",
                    e);
        }
    
        public void delete(int id) {
            sst.delete("dao.EmployeeDAO.delete", 
                    id);
        }
    
        public Map findById2(int id) {
            return sst.selectOne(
                    "dao.EmployeeDAO.findById2", id);
        }
    
        public Employee2 findById3(int id) {
            return sst.selectOne(
                    "dao.EmployeeDAO.findById3", id);
        }
    
    }
    EmployeeDAOMybatisImpl.java

    entity

    package entity;
    
    public class Employee {
        private Integer id;
        private String name;
        private Integer age;
        
        @Override
        public String toString() {
            return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        
    }
    Employee.java
    package entity;
    
    public class Employee2 {
        private Integer empNo;
        private String ename;
        private Integer age;
        
        @Override
        public String toString() {
            return "Employee2 [empNo=" + empNo + ", ename=" + ename + ", age=" + age + "]";
        }
        
        public void setEmpNo(Integer empNo) {
            this.empNo = empNo;
        }
        public void setEname(String ename) {
            this.ename = ename;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        
    }
    Employee2.java
    <?xml version="1.0" encoding="UTF-8" ?>  
    <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
     "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
    
    <mapper namespace="dao.EmployeeDAO">
        <!-- 
            id:要求唯一
            parameterType:参数类型,要写类的完整的名称。
         -->
        <insert id="save" 
            parameterType="entity.Employee">
            INSERT INTO emp_czh 
            VALUES(emp_czh_seq.nextval,#{name},#{age})
        </insert>
        
        <!-- 
            resultType:返回类型,要写类的完整的名称。
         -->
        <select id="findAll" 
            resultType="entity.Employee">
            SELECT * FROM emp_czh
        </select>
        
        <select id="findById" 
            parameterType="int" 
            resultType="entity.Employee">
            SELECT * FROM emp_czh
            WHERE id = #{id1}
        </select>
        
        <update id="modify" 
            parameterType="entity.Employee">
            UPDATE emp_czh SET name = #{name},
            age = #{age} WHERE id = #{id}
        </update>
        
        <delete id="delete" parameterType="int">
            DELETE FROM emp_czh WHERE id = #{id1}
        </delete>
        
        <!-- 返回Map类型的结果 -->
        <!-- 
            map是java.util.Map的简写形式
         -->
        <select id="findById2" parameterType="int"
            resultType="map">
            SELECT * FROM emp_czh WHERE id = #{id1}
        </select>
        
        <!-- 
            resultMap告诉mybatis表的字段名
            与实体类的属性名的对应关系。
            (如果表的字段名与属性名相同,则不用写了)
         -->
        <resultMap type="entity.Employee2" 
            id="empResultMap">
            <result property="empNo" column="id"/>
            <result property="ename" column="name"/>
        </resultMap>
        
        <select id="findById3" parameterType="int"
            resultMap="empResultMap">
            SELECT * FROM emp_czh WHERE id = #{id1}
        </select>
    </mapper>
    EmpMapper.xml

    src/main/resources

    # db connection parameters
    # key=value
    driver=oracle.jdbc.driver.OracleDriver
    url=jdbc:oracle:thin:@192.168.201.227:1521:orcl
    user=openlab
    pwd=open123
    # datasource parameters
    initSize=1
    maxSize=1
    db.properties
    <?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:context="http://www.springframework.org/schema/context" 
        xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
        xmlns:jee="http://www.springframework.org/schema/jee" 
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:util="http://www.springframework.org/schema/util"
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
        <!-- 读取db.properties文件 -->
        <util:properties id="db" 
        location="classpath:db.properties"/>
        <!-- 配置连接池 -->
        <bean id="ds" 
        class="org.apache.commons.dbcp.BasicDataSource"       
           destroy-method="close">       
          <property name="driverClassName" 
              value="#{db.driver}" />      
          <property name="url" 
              value="#{db.url}" />      
          <property name="username" 
              value="#{db.user}" />      
          <property name="password" 
              value="#{db.pwd}" />      
        </bean> 
        <!-- 配置SqlSessionFactoryBean -->
        <bean id="ssfb" 
            class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入连接池 -->
            <property name="dataSource" ref="ds"/>
            <!-- 注入映射文件的位置信息 -->
            <property name="mapperLocations"
            value="classpath:entity/*.xml"/>
        </bean>
        <!-- 配置SqlSessionTemplate -->
        <bean id="sst" 
        class="org.mybatis.spring.SqlSessionTemplate">
            <!-- 注入SqlSessionFactoryBean -->
            <constructor-arg index="0" 
            ref="ssfb"/>
        </bean>
        <!-- 配置组件扫描 -->
        <context:component-scan 
        base-package="dao"/>
    </beans>
    spring-mybatis.xml

    src/test/java

    test

    package test;
    
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import dao.EmployeeDAO;
    import entity.Employee;
    
    public class TestCase {
        private EmployeeDAO dao;
        @Before
        public void init(){
            ApplicationContext ac = 
                new ClassPathXmlApplicationContext(
                    "spring-mybatis.xml");
            dao = ac.getBean("empDAO",
                    EmployeeDAO.class);
        }
        @Test
        public void test1(){
            List<Employee> emps = 
                    dao.findAll();
            System.out.println(emps);
        }
        
        @Test
        public void test2(){
            Employee e = new Employee();
            e.setName("Hello Kitty");
            e.setAge(40);
            dao.save(e);
        }
    }
    TestCase.java
      <dependencies>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-webmvc</artifactId>
              <version>3.2.8.RELEASE</version>
          </dependency>
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis</artifactId>
              <version>3.2.8</version>
          </dependency>
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis-spring</artifactId>
              <version>1.2.2</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-jdbc</artifactId>
              <version>3.2.8.RELEASE</version>
          </dependency>
          <dependency>
              <groupId>com.oracle</groupId>
              <artifactId>ojdbc14</artifactId>
              <version>10.2.0.4.0</version>
          </dependency>
          <dependency>
              <groupId>commons-dbcp</groupId>
              <artifactId>commons-dbcp</artifactId>
              <version>1.4</version>
          </dependency>
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.12</version>
          </dependency>
          <dependency>
              <groupId>javax.annotation</groupId>
              <artifactId>javax.annotation-api</artifactId>
              <version>1.2</version>
          </dependency>
      </dependencies>
    pom.xml
  • 相关阅读:
    Sublime Text 3 绝对神器
    spring 笔记3: Spring 多环境配置文件切换
    elk-logstash: window下指定jdk目录
    通过slf4j/log4j的MDC/NDC 实现日志追踪
    spring 笔记2:Spring MVC : Did not find handler method for 问题的解决
    mysql一机多实例安装记录
    Java:通过反射复制父类字段到子类。
    mybatis研究:select性能对比
    spring " expected single matching bean but found 2" 问题一例。
    数组去重复
  • 原文地址:https://www.cnblogs.com/tangshengwei/p/6534349.html
Copyright © 2011-2022 走看看