mybatis详解-(23)spring整合

Spring是一个开放源代码的设计层面框架,他解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用。Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。
本篇还是以示例的形式介绍一下spring是如何整合mybatis。

1.使用maven构建web项目

mybatis详解-(23)spring整合_第1张图片

pom.xml文件配置

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>org.mybatisgroupId>
  <artifactId>mybatis-study-02artifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>jarpackaging>

  <name>mybatis-study-02name>
  <url>http://maven.apache.orgurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <spring4.version>4.2.4.RELEASEspring4.version>
  properties>

  <dependencies>
    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.2.1version>
    dependency>

    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-ehcacheartifactId>
      <version>1.0.0version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>1.2.0version>
    dependency>

    
    <dependency>
        <groupId>net.sf.ehcachegroupId>
        <artifactId>ehcache-coreartifactId>
        <version>2.6.10version>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-beansartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-coreartifactId>
        <version>4.2.4.RELEASEversion>
        
        <exclusions>
            <exclusion>
                <groupId>commons-logginggroupId>
                <artifactId>commons-loggingartifactId>
            exclusion>
        exclusions>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-expressionartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-apiartifactId>
        <version>1.7.12version>
    dependency>
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-log4j12artifactId>
        <version>1.7.6version>
    dependency>
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.17version>
    dependency>
    <dependency>
        <groupId>commons-logginggroupId>
        <artifactId>commons-loggingartifactId>
        <version>1.2version>
    dependency>

    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.35version>
    dependency>

    
    <dependency>
        <groupId>c3p0groupId>
        <artifactId>c3p0artifactId>
        <version>0.9.1.1version>
    dependency>

    
    <dependency>    
        <groupId>javax.servletgroupId>    
        <artifactId>servlet-apiartifactId>    
        <version>2.5version>    
    dependency>
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>jstlartifactId>
        <version>1.2version>
    dependency>

    

    
    
  dependencies>
project>

2.mybatis主配置文件

mybatis-config.xml
使用了spring之后,mybatis主配置文件配置较少了。具体存放位置看上图的整个工程架构。



<configuration>

    

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>

    

configuration>

3.mybatis映射配置文件

按照业务区分开。具体存放位置看上图的整个工程架构。
这里只展示一个文件的简单配置:




<mapper namespace="org.mybatis.dao.SysuserMapper">

    
    <select id="getEmployeeById" resultType="org.mybatis.bean.Employee">
        select * from mybatis_employee where id = #{id}
    select>

    
    
    
    <select id="getEmployeeByIdAndLastName" resultType="org.mybatis.bean.Employee">
        select * from mybatis_employee where id = #{id} and last_name = #{lastName}
    select>


    <select id="getEmployeeByEmployeeField" resultType="org.mybatis.bean.Employee">
        select * from mybatis_employee where id = #{id} and last_name = #{lastName}
    select>


    <select id="getEmployeeByMap" resultType="org.mybatis.bean.Employee">
        select * from mybatis_employee where id = #{id} and last_name = #{lastName}
    select>

    
    <insert id="addEmployee" parameterType="org.mybatis.bean.Employee" useGeneratedKeys="true" keyProperty="id">
        insert into mybatis_employee 
        (last_name,email,gender) 
        values 
        (#{lastName},#{email},#{gender});
    insert>

    
    <insert id="addEmployeeo">
        
        <selectKey keyProperty="id" order="BEFORE" resultType="Integer">
            select employees_seq from dual;
        selectKey>

        insert into mybatis_employee 
        (id,last_name,email,gender) 
        values 
        (#{id},#{lastName},#{email},#{gender});
    insert>

    
    <update id="updateEmployee">
        update mybatis_employee
        set
        last_name = #{lastName},
        email = #{email},
        gender = #{gender}
        where 
        id = #{id}
    update>

    
    <delete id="deleteEmployee">
        delete from mybatis_employee where id = #{id}
    delete>

mapper>

4.spring配置文件

applicationContext.xml


<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:tx="http://www.springframework.org/schema/tx"
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
        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-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    
    <context:component-scan base-package="org.mybatis">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    

    
    <context:property-placeholder location="classpath:db.properties"/>

    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${mysql.url}">property>
        <property name="driverClass" value="${mysql.driver}">property>
        <property name="user" value="${mysql.username}">property>
        <property name="password" value="${mysql.password}">property>
    bean>

    
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>

    
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>

    
     <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource">property>
        
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
        
        <property name="mapperLocations" value="classpath:mapper/*/*.xml">property>
     bean>

    
    <mybatis-spring:scan base-package="org.mybatis.dao"/>
    
beans>

5.spring-mvc配置文件

spring-mvc.xml
视图解析器没什么好解释的,按照固定格式配置就行了。
包扫描,因为spring-mvc只负责v层的页面控制,所以只扫描所有的controller就足够了。


<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:mvc="http://www.springframework.org/schema/mvc"
    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-4.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

    

    
    <context:component-scan base-package="org.mybatis.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/">property>
        <property name="suffix" value=".jsp">property>
    bean>

    <mvc:annotation-driven>mvc:annotation-driven>

    <mvc:default-servlet-handler/>

beans>

6.配置web.xml

引入spring和spring-mvc的配置文件,编码过滤


<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <display-name>Archetype Created Web Applicationdisplay-name>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>


     <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

web-app>

7.创建页面

这里使用欢迎页index.jsp,跳转页面WEB-INF/pages/loginsuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主页title>
head>
<body>
    <h1>Index Pageh1>

    
    <a href="sysuser/login">welcomea>
    <br><br>

body>
html>
<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>logintitle>
head>
<body>
login success
body>
html>

8.创建controller层

package org.mybatis.controller;

import org.mybatis.service.SysuserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/sysuser")
public class SysUserController {

    @Autowired
    private SysuserService sysuserService;

    @RequestMapping(value="/login",method=RequestMethod.GET)
    private String sysuserlogin(){
        Integer userId = 2;
        String loginStatus = sysuserService.login(userId);
        System.out.println(loginStatus);
        return "loginsuccess";
    }
}

9.创建service层

package org.mybatis.service;

public interface SysuserService {

    public String login(Integer userId);
}
package org.mybatis.service;

import org.mybatis.bean.Employee;
import org.mybatis.dao.SysuserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("sysuserService")
public class SysuserServiceImpl implements SysuserService{

    @Autowired
    private SysuserMapper sysuserMapper;

    public String login(Integer userId) {
        Employee emp = sysuserMapper.getEmployeeById(userId);
        System.out.println(emp);
        return "loginsuccess";
    }

}

10.创建mapper接口

package org.mybatis.dao;

import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.mybatis.bean.Employee;
import org.springframework.stereotype.Repository;

@Repository("sysuserMapper")
public interface SysuserMapper {

    public Employee getEmployeeById(int id);

}

11.测试

这里写图片描述

跳转结果

这里写图片描述

打印结果

DEBUG - DispatcherServlet with name ‘springmvc’ processing GET request for [/mybatis-study-02/sysuser/login]
DEBUG - Looking up handler method for path /sysuser/login
DEBUG - Returning handler method [private java.lang.String org.mybatis.controller.SysUserController.sysuserlogin()]
DEBUG - Returning cached instance of singleton bean ‘sysUserController’
DEBUG - Last-Modified value for [/mybatis-study-02/sysuser/login] is: -1
DEBUG - Creating a new SqlSession
DEBUG - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6edbe1dd] was not registered for synchronization because synchronization is not active
DEBUG - Fetching JDBC Connection from DataSource
DEBUG - trace com.mchange.v2.resourcepool.BasicResourcePool@74e22cc5 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@7f446405)
DEBUG - JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@66803b47] will not be managed by Spring
DEBUG - ooo Using Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@66803b47]
DEBUG - ==> Preparing: select * from mybatis_employee where id = ?
DEBUG - ==> Parameters: 2(Integer)
DEBUG - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6edbe1dd]
DEBUG - Returning JDBC Connection to DataSource
DEBUG - trace com.mchange.v2.resourcepool.BasicResourcePool@74e22cc5 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@7f446405)
Employee [id=2, lastName=lisi, [email protected], gender=1]
loginsuccess
DEBUG - Invoking afterPropertiesSet() on bean with name ‘loginsuccess’
DEBUG - Rendering view [org.springframework.web.servlet.view.JstlView: name ‘loginsuccess’; URL [/WEB-INF/pages/loginsuccess.jsp]] in DispatcherServlet with name ‘springmvc’
DEBUG - Forwarding to resource [/WEB-INF/pages/loginsuccess.jsp] in InternalResourceView ‘loginsuccess’
DEBUG - Successfully completed request
DEBUG - Returning cached instance of singleton bean ‘sqlSessionFactoryBean’

本文是在前面系列文章的基础之上实现的,如果对mybatis的一些基本使用不会的,建议先参考前面的mybatis详解-(1)到mybatis详解-(22)系列文章。实现都是手把手搭建和测试的。

到此mybatis的使用就介绍完了。

后续还会写一些什么内容呢?敬请期待….

你可能感兴趣的:(mybatis)