mybatis学习教程中级(十一)mybatis和spring框架整合(前奏篇)

1、引言

我们前面对mybatis的基础以及中级知识查询做了初步了解,比较它只是一个ORM框架。虽然独当一面,但是不能构造我们完整系统。接下来,我们讲讲他与Spring整合。以及顺带讲解一下Spring MVC。

2、Mybatis与Spring整合前奏

2.0 spring到底做了什么

。1、让spring管理我们的SqlsessionFactory

    2、让spring管理mapper对象

    3、让Spring管理数据源(从开始就在说)

  这样看来,以前我们需要手工做的事情,根本就让spring自动化处理完毕!!!

结构:

mybatis学习教程中级(十一)mybatis和spring框架整合(前奏篇)

2.1 整合jar包需要什么

新增jar:mybatis-spring、commons-dbcp、springwebmvc、spring-test、aspectjwaver、spring-jdbc

<span style="font-size:12px;"><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ycy.mybatis01</groupId>
  <artifactId>mybatis01</artifactId>
  <packaging>war</packaging>
  <version>1.0-mybatis01</version>
  <name>mybatis01 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <build>
    <finalName>mybatis01</finalName>
  </build>
  <!--junit测试-->
  <dependencies>
    <!--数据库驱动-->
    <dependency>
      <groupId>Mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!--数据库连接池-->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!--mybatis包-->
    <!--ehcache核心包-->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.6.11</version>
    </dependency>
    <!--ehcache-Mybatis包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
  <!--log4j官方推荐jar-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.3</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.3</version>
    </dependency>
    <!--log4j实现slf4j:因为Mybatis是用的slf4j-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>2.3</version>
    </dependency>
    <!--spring-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <!--spring-mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>
    <!--事务管理-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.0</version>
    </dependency>
    <!--junit测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
  </dependencies>
</project></span><strong style="font-size: 18px;">
</strong>
2.2 整合spring

我们先思考一下怎么整合:mapper查询sql----》需要sqlsession----》找sqlsessionFactory-----》找1configLcation(sqlconfig)、2datasource-----》1sqlconfig、2dbcp(jdbc等);我们需要这么的思维哦,不要每次都去copy,要知道逻辑层次,记住了。

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-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/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:/config/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>
	<!-- SqlsessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- mybatis配置文件 -->
		<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
	</bean>
	
	<!-- 配置dao -->
	<bean id="userDao" class="com.ycy.mybatis.dao.impl.UserMappermpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
	</bean>
	
	<!-- 配置mapper
	MapperFactoryBean:用于生成mapper代理对象
	 -->
	<!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper"/>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
	</bean> -->
	
</beans>
2.3 mapper

之前的mapper与一样设置的mapper.java

package com.ycy.mybatis.dao;

import com.ycy.mybatis.module.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * Created by Administrator on 2015/8/31 0031.
 */
public interface UserMapper {
    public User getUserById(int id) throws Exception;
}
实现类(注意注解service)

package com.ycy.mybatis.dao.impl;

import com.ycy.mybatis.dao.UserMapper;
import com.ycy.mybatis.module.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Service;

import java.sql.SQLFeatureNotSupportedException;
import java.util.List;

/**
 * Created by Administrator on 2015/8/31 0031.
 */
@Service
public class UserMappermpl extends SqlSessionDaoSupport implements UserMapper {

    @Override
    public User getUserById(int id) throws Exception {
        SqlSession sqlSession=this.getSqlSession();
        User user= sqlSession.selectOne("com.ycy.mybatis.dao.UserMapper.getUserById", id);
        return user;
    }
}
之前一样mapper一样设置mapper.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">
<!--命名空间:分类管理sql隔离,方便管理-->
<mapper namespace="com.ycy.mybatis.dao.UserMapper">
    <!--打开mapper二级缓存开关-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache">
        <property name="maxElementsInMemory" value="1000"/>
    </cache>
    <!--定义个ResultMap-->
    <!--如果ResultMap定义在一个mapper.xml里面,直接使用resultMap的id ,如果不在同一个mapper要在resultMap前面加namespace-->
    <resultMap id="userResultMap" type="User">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex" />
        <result column="address" property="address"/>
    </resultMap>
    <!--id标示一个sql语句,一个Statement,封装为一个MapperStatement-->
    <!--parameterType:传入参数类型;resultType:输出结果类型,指定映射的pojo-->
    <!--#{}标示一个占位符,-->
    <!--查询用户-->
    <!--oracle-->
    <!--   SELECT * FROM  USER  WHERE  username  LIKE  '%'||#{_parameter}||'%'-->
    <!-- mysql-->
    <select id="getUserById" parameterType="int" resultType="User" >
         SELECT  * FROM USER WHERE id=#{id}
        </select>
</mapper>
2.4 测试

我这里就不用ClassPathXmlApplicationContext;ApplicationContext;直接用spring.test,简单与方便。

package com.ycy.mybatis.springmybatisTest;

import com.ycy.mybatis.dao.UserMapper;
import com.ycy.mybatis.module.User;
import javafx.application.Application;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.applet.AppletContext;

/**
 * Created by Administrator on 2015/9/15 0015.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:spring/applicationContext.xml"})
public class Test11 {
    @Autowired
    private  UserMapper userMapper;
    @Test
    public  void  test111() throws Exception {
        User user=userMapper.getUserById(1);
        System.out.println( user.getUsername());
    }

}






上一篇:30多条mysql数据库优化方法,千万级数据库记录查询轻松解决


下一篇:《树莓派开发实战(第2版)》——1.13 关闭树莓派