SpringMVC+Mybatis框架搭建

2021-03-03 12:23:29 浏览数 (1)

1. 准备环境


1. 所需jar包
  • 数据库驱动包
  • mybatis jars
  • mybatis和spring的整合包
  • log4j包
  • 数据库连接池包 dbcp
  • spring包
  • jstl
  • junit
  • aspectjweaver.jar
  • commons-pool2-2.4.2
2. 工程结构

2. dao层


1. sqlMapConfig.xml
  • mybatis本身的配置文件
代码语言:javascript复制
<?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>

    <!-- 全局settings配置,根据需要添加 -->
    
    <!-- 配置别名 -->
    <typeAliases>
        <!-- 批量扫描别名 -->
        <package name="com.swxc.ssm.po" />
    </typeAliases>

    <!-- 配置mapper
     由于使用spring和mybatis的整合包进行mapper扫描,所以这里不需要配置。
     必须遵循mapper.xml和mapper.java问价同名并在同一目录。
     -->

</configuration>
2. applicationContext-dao.xml
  • 配置:SqlSessionFactory、数据源、mapper扫描器
代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:context.="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 加载db.properties中的内容,db.properties的key命名要有一定的特殊规则。 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置数据源,dbcp -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.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="maxTotal" value="30" />
        <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>

    <!-- mapper扫描器 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描包路径,如果需要扫描多个,中间使用半角 -->
        <property name="basePackage" value="com.swxc.ssm.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

</beans>
3. 逆向工程(generatorSqlmapCustom)生成po类以及mapper(单标增删改查)
  • 将生成的文件拷贝到工程中。
4. 手动定义商品查询mapper
  • 针对综合查询mapper,一般情况会有关联查询,所以建议自定义mapper。
  • ItemsMapperCustom.xml
代码语言:javascript复制
<?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="com.swxc.ssm.mapper.ItemsMapperCustom">

    <!-- 定义商品查询的sql片段 -->
    <sql id="query_items_where">
        <!-- 使用动态sql,通过if判断,满足条件进行sql拼接
         商品的查询条件通过ItemsQueryVo包装对象中的itemsCustom属性传递。-->
        <if test="itemsCustom != null">
            <if test="ItemsCustom.name != none and itemsCustom.name != ''">
                name like '%${itemsCustom.name}%'
            </if>
        </if>
    </sql>
    <!-- 商品列表查询 -->
    <!-- 建议parameterType传入包装对象-->
    <select id="findItemsList" parameterType="com.swxc.ssm.po.ItemsQueryVo" resultType="com.swxc.ssm.po.ItemsCustom">
        select * from items
        <where>
            <include refid="query_items_where" />
        </where>
    </select>
</mapper>
  • ItemsmapperCustom.java
代码语言:javascript复制
package com.swxc.ssm.mapper;

import com.swxc.ssm.po.ItemsCustom;
import com.swxc.ssm.po.ItemsQueryVo;

import java.util.List;

/**
 * Description
 * Author shadowolf
 * Date 2017/7/26. 3:47
 * Version 1.0
 */
public interface ItemsMapperCustom {

    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;

}

3. service层


1. 定义service 接口
代码语言:javascript复制
package com.swxc.ssm.service;

import com.swxc.ssm.po.ItemsCustom;
import com.swxc.ssm.po.ItemsQueryVo;

import java.util.List;

/**
 * Description 商品管理service
 * Author shadowolf
 * Date 2017/7/26. 8:32
 * Version 1.0
 */
public interface ItemsService {

    // 商品查询列表
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;

}
代码语言:javascript复制
package com.swxc.ssm.service.impl;

import com.swxc.ssm.mapper.ItemsMapperCustom;
import com.swxc.ssm.po.ItemsCustom;
import com.swxc.ssm.po.ItemsQueryVo;
import com.swxc.ssm.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Description 商品管理
 * Author shadowolf
 * Date 2017/7/26. 9:22
 * Version 1.0
 */
public class ItemsServiceImpl implements ItemsService {

    @Autowired
    private ItemsMapperCustom itemsMapperCustom;

    @Override
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
        // 通过ItemsMapperCustom查询数据库
        return itemsMapperCustom.findItemsList(itemsQueryVo);
    }
}
2. 在spring容器中配置service
  • 创建applicationContext-service.xml,文件中配置service。
代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:context.="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util.xsd">
    <!-- 商品管理的service -->
    <bean id="itemsService" class="com.swxc.ssm.service.impl.ItemsServiceImpl" />
</beans>
3. 事务控制(applicationContext-transaction.xml)
  • 在applicationContext-transaction.xml中,使用spring声明式事务控制方法。
代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:context.="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 事务管理器
     对mybatis操作数据库的事务控制,spring使用jdbc的事务控制
     -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源
         dataSource在application-dao.xml中配置
         -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" 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 -->
    <aop:config>
        <!-- pointcut:切点,com.swxc.ssm.service.impl下的所有类的下的所有方法,不限制传入参数 -->
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.swxc.ssm.service.impl.*.*(..))" />
    </aop:config>

</beans>

4. springmvc


1. 配置springmvc.xml
  • 创建springmvc文件,配置处理器映射器、适配器、视图解析器。
代码语言:javascript复制
<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       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.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 可以扫描controller、service、......
     这里让扫描controller,指定controller的包
     -->
    <context:component-scan base-package="com.swxc.ssm.controller" />

    <!-- 使用mvc:annotation-driven可以代替注解映射器和注解适配器的配置
     mvc:annotation-driven默认加载很多的参数绑定方法,比如json转换解析器就默认加载了,
     如果使用mvc:annotation-driven,不用配置RequestMappingHandlerMapping和RequestMappingHandlerAdapter
     实际开发使用mvc:annotation-driven
     -->
    <mvc:annotation-driven />

    <!-- 视图解析器
     解析jsp视图,默认使用jstl标签,classpath下必须有jstl包
     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置jsp路径的前缀和后缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>
2. 配置前端控制器(web.xml)
代码语言:javascript复制
<!-- 前端控制器 -->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等)
     如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-servlet.xml(springmvc-servlet.xml)
     -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!--
    第一种:*.action    访问以.action结尾由DispatcherServlet进行解析。
    第二种:/            所有访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析
                           使用此种方法,可以实现RESTful风格。
    第三种:/*           这样配置不对。使用这种配置,最终要转发到一个jsp页面时,仍然会由DispatcherServlet解析jsp页面,
                           不能根据jsp页面找到handler,会报错。
    -->
    <url-pattern>*.action</url-pattern>
</servlet-mapping>
3. 编写Controller(就是Handler)
代码语言:javascript复制
package com.swxc.ssm.controller;

import com.swxc.ssm.po.ItemsCustom;
import com.swxc.ssm.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * Description 商品的Controller
 * Author shadowolf
 * Date 2017/7/26. 11:20
 * Version 1.0
 */
@Controller
public class ItemsController {

    @Autowired
    private ItemsService itemsService;

    // 商品的查询
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception {
        List<ItemsCustom> itemsList = itemsService.findItemsList(null);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemsList", itemsList);
        modelAndView.setViewName("items/itemsList");
        return modelAndView;
    }

}
5. 编写jsp页面
  • WEB-INF/jsp/itemsList.jsp
代码语言:javascript复制
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<!doctype  html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>查询商品列表</title>
</head>
<body>
    <form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
        查询条件:
        <table width="100%" border="1">
            <tr>
                <td><input type="submit" value="查询" /></td>
            </tr>
        </table>
        商品列表:
        <table width="100%" border="1">
            <tr>
                <td>商品名称</td>
                <td>商品价值</td>
                <td>生产日期</td>
                <td>商品描述</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${itemsList }" var="item">
                <tr>
                    <td>${item.name }</td>
                    <td>${item.price }</td>
                    <td><fmt:formatDate value="${item.createTime }" pattern="yyyy-MM-dd HH:mm:ss" /> </td>
                    <td>${item.detail }</td>
                    <td>
                        <a href="${pageContext.request.contextPath}/item/editItem.action?id=${item.id}">修改</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </form>
</body>
</html>

5. 加载spring容器


  • 将mapper、service、controller加载到spring容器中。(以下文件)
    • mapper使用了扫描器
    • service使用了声明式的配置方式
    • controller使用了组件扫描
  • 建议使用通配符来加载上边的配置文件
  • 方法:
    • 在web.xml中,添加spring容器的监听器,加载spring容器。
代码语言:javascript复制
<!-- 加载spring容器 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

0 人点赞