Maven3 + Spring4 + SpringMVC4 + Mybatis3

Maven、Spring、SpringMVC、Mybatis 整合基本流程

完整源代码见Github:Maven-Spring-SpringMVC-Mybatis.

1 整合思路

1.1 Spring、SpringMVC、Mybatis 整合的系统架构:

Maven3 + Spring4 + SpringMVC4 + Mybatis3_第1张图片

1.2 整合基本流程

  整合采用自下而上的方式整合:

  • 第一步:整合 dao 层,mybatis和spring整合,通过spring管理mapper接口。使用 mapper的扫描器自动扫描mapper接口在spring中进行注册。
  • 第二步:整合 service 层,通过spring管理 service接口。使用配置方式将service接口配置在spring配置文件中。实现事务控制。
  • 第三步:整合 springmvc,由于 springmvc 是 spring 的模块,不需要整合,加入相应的 jar 包即可。

2 整合流程

2.1 pom.xml 中添加依赖

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        
        <spring.version>4.2.5.RELEASEspring.version>
        <mybatis.version>3.2.8mybatis.version>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjrtartifactId>
            <version>1.8.6version>
        dependency>

        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.8.6version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>4.2.5.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>

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

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

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>${mybatis.version}version>
        dependency>

        
        <dependency>
            <groupId>cglibgroupId>
            <artifactId>cglibartifactId>
            <version>3.1version>
        dependency>
        <dependency>
            <groupId>org.javassistgroupId>
            <artifactId>javassistartifactId>
            <version>3.17.1-GAversion>
        dependency>

        
        <dependency>
            <groupId>commons-logginggroupId>
            <artifactId>commons-loggingartifactId>
            <version>1.1.1version>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.5version>
        dependency>
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-coreartifactId>
            <version>2.0.2version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.5version>
        dependency>

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

        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.10version>
            <scope>testscope>
        dependency>
    dependencies>

2.2 整合 Mybatis 和 Spring:整合 dao 层

2.2.1 配置 db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc_mybatis?useUnicode=true&;characterEncoding=UTF-8
jdbc.username=username
jdbc.password=password
jdbc.initialPoolSize=5
jdbc.maxPoolSize=10

2.2.2 配置 Mybatis 的 SqlMapConfig.xml

  在 resources/config/mybatis 目录下创建 SqlMapConfig.xml :



<configuration>

    

    
    <typeAliases>
        
        <package name="com.markliu.ssm.po" />
    typeAliases>

    
    <mappers>
        
        <mapper resource="config/mybatis/mapper/ItemsCustomMapper.xml" />
        <mapper resource="config/mybatis/mapper/ItemsMapper.xml" />
        <mapper resource="config/mybatis/mapper/OrderDetailMapper.xml" />
        <mapper resource="config/mybatis/mapper/OrdersMapper.xml" />
        <mapper resource="config/mybatis/mapper/UserMapper.xml" />
    mappers>
configuration>

2.2.3 配置 Spring 的 applicationContext-dao.xml

  在 resources/config/spring 目录下创建 applicationContext-dao.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

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

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

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="configLocation" value="classpath:config/mybatis/SqlMapConfig.xml"/>
        
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="basePackage" value="com.markliu.ssm.mapper" />
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    bean>
beans>

2.2.4 逆向工程生成 po 类、 mapper.java 和 mapper.xml (单表的CRUD)

  Mybatis 逆向工程的基本流程参考 mybatis-generator.md

2.2.5 对于关联查询,需要手动创建 mapper.java 和 mapper.xml

  ItemsCustomMapper.xml:



<mapper namespace="com.markliu.ssm.mapper.ItemsCustomMapper">

    
    <sql id="ItemsCustom_Query_Where">
      
        <if test="itemsCustom!=null">
            <if test="itemsCustom.name!=null and itemsCustom.name!='">
                items.name like '%${itemsCustom.name}%'
            if>
        if>
    sql>
    
    
    <select id="getAllItemsLikeName"
            parameterType="com.markliu.ssm.po.ItemsCustomQueryVo"
            resultType="com.markliu.ssm.po.ItemsCustom">
        select * from items
        <where>
          <include refid="ItemsCustom_Query_Where" />
        where>
    select>
mapper>

  ItemsCustomMapper.java:

public interface ItemsCustomMapper {
    List getAllItemsLikeName(ItemsCustomQueryVo itemsCustomQueryVo) throws Exception;
}

2.3 整合 Mybatis 和 SpringMVC:整合 service 层

2.3.1 定义 service 接口

package com.markliu.ssm.service;

import com.markliu.ssm.po.ItemsCustom;
import com.markliu.ssm.po.ItemsCustomQueryVo;
import java.util.List;

public interface ItemsService {
    /**
     * 获取 Items 列表
     * @param itemsCustomQueryVo 封装针对 ItemsCustom 的复杂查询的 Vo 类
     * @return Items 列表
     * @throws Exception database exception
     */
    List getAllItemsLikeName(ItemsCustomQueryVo itemsCustomQueryVo) throws Exception;
}

2.3.2 定义 service 接口的实现类

package com.markliu.ssm.service.impl;

import com.markliu.ssm.mapper.ItemsCustomMapper;
import com.markliu.ssm.po.ItemsCustom;
import com.markliu.ssm.po.ItemsCustomQueryVo;
import com.markliu.ssm.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("itemsService")
public class ItemsServiceImpl implements ItemsService {

    // 注意 itemsCustomMapper 已通过包自动扫描的方式注入到 IoC 容器中,
    // 所以此处可以通过 Autowired 自动注入
    private ItemsCustomMapper itemsCustomMapper;

    @Autowired
    public void setItemsCustomMapper(ItemsCustomMapper itemsCustomMapper) {
        this.itemsCustomMapper = itemsCustomMapper;
    }

    public List getAllItemsLikeName(ItemsCustomQueryVo itemsCustomQueryVo)
            throws Exception {
        // 调用 dao 层的ItemsCustomMapper
        return itemsCustomMapper.getAllItemsLikeName(itemsCustomQueryVo);
    }
}

2.3.3 service 层定义事物管理 applicationContext-transaction.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    

    

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

    
    <tx:advice id="interceptorAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />

            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
        tx:attributes>
    tx:advice>

    
    <aop:config>
        <aop:advisor advice-ref="interceptorAdvice" pointcut="execution(* com.markliu.ssm.service.impl.*.*(..))"/>
    aop:config>

beans>

2.3 整合 Mybatis 和 SpringMVC:整合 controller 层

2.3.1 springmvc-dispatcherservlet.xml

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

    
    <context:component-scan base-package="com.markliu.ssm.controller" />
    <context:component-scan base-package="com.markliu.ssm.service" />
    <mvc:annotation-driven />

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

beans>

2.3.2 在 web.xml 中配置前端控制器

    <servlet>
        <servlet-name>springmvc-dispatcherservletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:config/spring/springmvc-dispatcherservlet.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>

    <servlet-mapping>
        <servlet-name>springmvc-dispatcherservletservlet-name>
        
        <url-pattern>/url-pattern>
    servlet-mapping>

2.3.3 编写控制器 Handler(Controller)

@Controller
@RequestMapping(value = "/items")
public class ItemsController {

    private ItemsService itemsService;

    @Autowired
    public void setItemsService(ItemsService itemsService) {
        this.itemsService = itemsService;
    }

    private ItemsMapper itemsMapper;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setItemsMapper(ItemsMapper itemsMapper) {
        this.itemsMapper = itemsMapper;
    }

    @RequestMapping(value = "/query_items", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView queryItems() throws Exception {

        Items items = itemsMapper.selectByPrimaryKey(1);
        System.out.println(items.toString());

        List itemsCustomList = itemsService.getAllItemsLikeName(null);

        for (ItemsCustom itemsCustom : itemsCustomList) {
            System.out.println(itemsCustom.toString());
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemsCustomList", itemsCustomList);
        modelAndView.setViewName("items/itemsList");
        return modelAndView;
    }
}

2.3.4 加载spring容器

  将mapper、service、controller加载到spring容器中。建议使用通配符加载 spring 容器的配置文件

  • applicationContext-dao.xml
  • applicationContext-transaction.xml
  • springmvc-dispatcherservlet.xml
      在web.xml中,添加spring容器监听器,加载spring容器。
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>/WEB-INF/classes/config/spring/applicationContext-*.xmlparam-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

Done.

你可能感兴趣的:(java学习总结之旅)