需要的jar包:

新建lib文件夹放入jar包,Build Path-->Add To Build Path之后:

原始Dao开发示例:

src下:新建核心配置文件sqlMapConfig.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>
<!-- 设置别名 -->
<typeAliases>
<package name="org.dreamtech.mybatis.pojo" />
</typeAliases>
<!-- 设置扫描包 -->
<mappers>
<package name="org.dreamtech.mybatis.mapper"/>
</mappers> </configuration>

新建Spring核心配置文件:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <context:property-placeholder location="classpath:db.properties" /> <!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<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> <!-- Mybatis的工厂 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 核心配置文件的位置 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml" />
</bean> <!-- Dao原始Dao -->
<bean id="userDao" class="org.dreamtech.mybatis.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean" />
</bean> </beans>

新建数据库配置文件:db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=12345

log4j配置文件(非必须):

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

接口:

package org.dreamtech.mybatis.dao;

public interface UserDao {

    public void insertUser();

}

实现类:

package org.dreamtech.mybatis.dao;

import org.mybatis.spring.support.SqlSessionDaoSupport;

/**
* 原始Dao开发
*
* @author YiQing
*
*/
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { //添加用户(代码省略)
public void insertUser() {
//this.getSqlSession().insert();
} }

Mapper动态代理开发:

新建包,类,映射文件:

applicationContext.xml配置如下:

    <!-- Mapper动态代理开发 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean" />
<property name="mapperInterface" value="org.dreamtech.mybatis.mapper.UserMapper" />
</bean>

UserMapper:

package org.dreamtech.mybatis.mapper;

import org.dreamtech.mybatis.pojo.User;

public interface UserMapper {

    // 通过ID查询一个用户
public User findUserById(Integer id); }

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="org.dreamtech.mybatis.mapper.UserMapper">
<!-- 通过ID查询一个用户 -->
<select id="findUserById" parameterType="Integer" resultType="User">
select * from user where id = #{v}
</select>
</mapper>

测试类:

package org.dreamtech.mybatis.junit;

import org.dreamtech.mybatis.mapper.UserMapper;
import org.dreamtech.mybatis.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class JunitTest { @Test
public void testMapper() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper mapper = (UserMapper) ac.getBean("userMapper");
User user = mapper.findUserById(10);
System.out.println(user.getUsername());
}
}

POJO:User类

package org.dreamtech.mybatis.pojo;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 1L;
private Integer id;
private String username; 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;
} }

Mapper动态代理扫描开发:

这种方式是Mapper动态代理开发的增强版:

Mapper动态代理开发存在弊端:Mapper过多时,配置文件繁琐

于是,想到,能否自动扫描一个包?

applicationContext.xml配置如下:

    <!-- Mapper动态代理开发 扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 基本包 -->
<property name="basePackage" value="org.dreamtech.mybatis.mapper" />
</bean>

注意:不需要再次注入工厂

测试类稍作改动即可:

由于没有ID,直接换成UserMapper类

package org.dreamtech.mybatis.junit;

import org.dreamtech.mybatis.mapper.UserMapper;
import org.dreamtech.mybatis.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class JunitTest { @Test
public void testMapper() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper mapper = ac.getBean(UserMapper.class);
User user = mapper.findUserById(10);
System.out.println(user.getUsername());
}
}

总结:通常我们选用第三种,不过也不能不会前两种

Mybatis框架七:三种方式整合Spring的更多相关文章

  1. 开发工具:Mybatis.Plus.插件三种方式的逆向工程

    本文源码:GitHub·点这里 || GitEE·点这里 一.逆向工程简介 在Java开发中,持久层最常用的框架就是mybatis,该框架需要编写sql语句,mybatis官方提供逆向工程,可以把数据 ...

  2. @Autowired注解和启动自动扫描的三种方式(spring bean配置自动扫描功能的三种方式)

    前言: @Autowired注解代码定义 @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, Elemen ...

  3. mybatis查询的三种方式

    查询最需要关注的问题:①resultType自动映射,②方法返回值:  interface EmpSelectMapper: package com.atguigu.mapper; import ja ...

  4. springboot与dubbo整合入门(三种方式)

    Springboot与Dubbo整合三种方式详解 整合环境: jdk:8.0 dubbo:2.6.2 springboot:2.1.5 项目结构: 1.搭建项目环境: (1)创建父项目与三个子项目,创 ...

  5. spring学习(03)之bean实例化的三种方式

    bean实体例化的三种方式 在spring中有三中实例化bean的方式: 一.使用构造器实例化:(通常使用的一个方法,重点) 二.使用静态工厂方法实例化: 三.使用实例化工厂方法实例化 第一种.使用构 ...

  6. Spring 循环依赖的三种方式(三级缓存解决Set循环依赖问题)

    本篇文章解决以下问题: [1] . Spring循环依赖指的是什么? [2] . Spring能解决哪种情况的循环依赖?不能解决哪种情况? [3] . Spring能解决的循环依赖原理(三级缓存) 一 ...

  7. java:struts框架2(方法的动态和静态调用,获取Servlet API三种方式(推荐IOC(控制反转)),拦截器,静态代理和动态代理(Spring AOP))

    1.方法的静态和动态调用: struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCT ...

  8. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件

    精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件 内容简介:本文介绍 Spring Boot 的配置文件和配置管理,以及介绍了三种读取配置文 ...

  9. Linux就这个范儿 第15章 七种武器 linux 同步IO: sync、fsync与fdatasync Linux中的内存大页面huge page/large page David Cutler Linux读写内存数据的三种方式

    Linux就这个范儿 第15章 七种武器  linux 同步IO: sync.fsync与fdatasync   Linux中的内存大页面huge page/large page  David Cut ...

随机推荐

  1. 转 Java操作PDF之iText详细入门

    转 Java操作PDF之iText详细入门 2016年08月08日 11:06:00 阅读数:19490 iText是著名的开放项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成 ...

  2. 为什么23种设计模式没有 MVC

    MVC的是为了把数据(Model)和视图(View)分离开来,然后用控制器(Controller)来粘合M和V之间的关系. MVC是观察者模式(Observer), 策略模式(Strategy)和组合 ...

  3. 【aardio】如何对listview中某一列,某一行的特定值进行修改?

    用表格创建数组来实现. import win.ui; /*DSG{{*/ var winform = ..win.form( bottom=399;parent=...;right=599;text= ...

  4. 软工作业1—java实现wc.exe

    github项目地址 https://github.com/liyizhu/wc.exe WC 项目要求 基本功能列表: wc.exe -c file.c     //返回文件 file.c 的字符数 ...

  5. [转]tomcat启动报错too low setting for -Xss

    tomcat启动报错too low setting for -Xss 网上给的答案都是调整Xss参数,其实不是正确的做法, -Xss:每个线程的Stack大小,“-Xss 15120” 这使得tomc ...

  6. JSP 页面中插入图片

    第一步 在 JSP 页面中插入图片 EL 表达式 ${pageContext.request.contextPath } 的值为当前的项目名称 <html> ... <body> ...

  7. Retrieving archetypes

    报错:Retrieving archetypes:' has encountered a problemAn internal error occurred during:"Retrievi ...

  8. MFC改变坐标系

    1.在MainFrm中的PreCreateWindow中设置默认窗口大小 BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !C ...

  9. peewee基本使用

    PEEWEE基本使用 Content Ⅰ  安装Ⅱ  链接数据库Ⅲ  建表 Ⅳ  增删改 Ⅴ  基础查询 Ⅵ  ForeignKey Ⅷ  事务 参考官方文档:http://docs.peewee-o ...

  10. python 初级重点

    关于python初学时遇到的重点: 1 python 2 和3 的区别 python2**不识别中文** -*- coding: utf-8 -*-(因为不能识别中文,所以代码有中文时需要在最前面加入 ...