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

Unit08: Spring集成mybatis的更多相关文章

  1. Spring集成MyBatis框架

    Java在写数据库查询时,我接触过四种方式: 1.纯Java代码,引用对应的数据库驱动包,自己写连接与释放逻辑(可以用连接池) 这种模式实际上性能是非常不错的,但是使用起来并不是非常方便:一是要手工为 ...

  2. SSM框架开发web项目系列(五) Spring集成MyBatis

    前言 在前面的MyBatis部分内容中,我们已经可以独立的基于MyBatis构建一个数据库访问层应用,但是在实际的项目开发中,我们的程序不会这么简单,层次也更加复杂,除了这里说到的持久层,还有业务逻辑 ...

  3. Spring集成MyBatis的使用-使用SqlSessionTemplate

    Spring集成MyBatis的使用 Spring集成MyBatis,早期是使用SqlSessionTemplate,当时并没有用Mapper映射器,既然是早期,当然跟使用Mapper映射器是存在一些 ...

  4. Spring集成MyBatis的使用-使用Mapper映射器

    Spring集成MyBatis使用 前面复习MyBatis时,发现在测试时,需要手动创建sqlSessionFactory,Spring将帮忙自动创建sqlSessionFactory,并且将自动扫描 ...

  5. Spring集成Mybatis,spring4.x整合Mybatis3.x

    Spring集成Mybatis,spring4.x整合Mybatis3.x ============================== 蕃薯耀 2018年3月14日 http://www.cnblo ...

  6. spring集成mybatis配置多个数据源,通过aop自动切换

    spring集成mybatis,配置多个数据源并自动切换. spring-mybatis.xml如下: <?xml version="1.0" encoding=" ...

  7. MyBatis从入门到精通(第9章):Spring集成MyBatis(下)

    MyBatis从入门到精通(第9章):Spring集成MyBatis(下) springmvc执行流程原理 mybatis-spring  可以帮助我们将MyBatis代码无缝整合到Spring中.使 ...

  8. MyBatis从入门到精通(第9章):Spring集成MyBatis(中)

    MyBatis从入门到精通(第9章):Spring集成MyBatis(中) 框架(Framework)是整个或部分系统的可重用设计,表现为一组抽象构件及构件实例间交互的方法.应该将应用自身的设计和具体 ...

  9. MyBatis从入门到精通(第9章):Spring集成MyBatis(上)

    MyBatis从入门到精通(第9章):Spring集成MyBatis(上) Spring是一个为了解决企业级Web应用开发过程中面临的复杂性,而被创建的一个非常流行的轻量级框架. mybatis-sp ...

随机推荐

  1. vue项目使用hbuilder打包后,真机测试白屏

    在命令行直接运行 npm run build后,生成的dist文件中,直接打开index.html文件 Tip: built files are meant to be served over an ...

  2. os模块、文件压缩 、匹配文件后缀名:fnmatch glob

    一.os模块 os模块:是python是系统交互的模块 import os # 0平台信息的一些操作 python是夸平台的,所以内部兼容了不同的平台 1. os.name # 操作系统 nt是win ...

  3. Vue.directive使用注意

    首先,Vue.directive要在实例初始化之前,不然会报错,还有,定义的指令不支持驼峰式写法,也会报下面同样的错,虽然在源码中没有找到在哪里统一处理大小写,但是在有关directive的方法中捕捉 ...

  4. C++高级编程2. 静态动态链接库

    C++高级编程2. 静态动态链接库20131018 1.动态链接库和静态链接库的区别: 静态链接库就是把lib文件中用到的函数代码直接连接进目标程序,程序运行的时候不在需要其他的库文件:动态链接库是把 ...

  5. bzoj3000

    题解: n!k进制的位数 首先考虑n!十进制的位数 =log10(n!) 然后用阶乘近似公式 继而换底 得到答案 代码: #include<bits/stdc++.h> using nam ...

  6. 多网卡下,vlc发送IGMP组播报告包

    这两天测试IGMP遇到一个问题,环境描述如下: 我的vlc客户端安装在windows下,该PC有两张网卡,本地连接1接公司网,本地链接2 接路由器.wireshark坚挺本地链接2,以测试路由的IGM ...

  7. 下拉列表框DropDownList绑定Dictionary泛型类

    DropDownList绑定Dictionary泛型类 定义一个Dictionary泛型类 /// <summary>    /// 产品类型    /// </summary> ...

  8. [置顶] JVM层对jar包字节码加密

    github https://github.com/sea-boat/ByteCodeEncrypt 需求 拿到的需求是要对某特定的jar包实现加密保护,jar包需要提供给外部使用,但核心逻辑部分需要 ...

  9. sql server不能删除数据库,显示错误:正在使用

    解决办法: use mastergoalter database database_name set single_user with rollback immediate --将数据库回滚到原始配置 ...

  10. [Math]Pi(1)

    数学知识忘地太快,在博客记录一下pi的生成. 100 Decimal places 3.14159265358979323846264338327950288419716939937510582097 ...