Spring/Spring MVC/MyBatis整合详解

本文引用自:《Java EE企业级应用开发教程》

由于Spring MVC只是Spring框架中的一个模块,所以Spring MVC与Spring之间不存在整合的问题,只需要引入相应Jar包就可以直接使用。因此,Spring/Spring MVC/MyBatis的整合,只涉及Spring与MyBatis的整合,以及Spring MVC与MyBatis的整合。

首先,定义三大框架的版本:

  • Spring 5.2.3( 注意:Spring框架的所有Jar包版本必须保持一致,否则会发生不可预料的错误!
  • Spring MVC 5.2.3
  • MyBatis 3.5.2

其它附件的版本:

  • log4j 1.2.17
  • mysql 5.1.49
  • mybatis-spring 1.3.1

这些Jar包的引入地址,可以参考:https://mvnrepository.com/

一、准备所需要的Jar包

1.1 Spring核心包

commons-logging-1.2.jar        Spring需要用它记录日志(第三方包)
    spring-beans-5.2.3.RELEASE.jar    SpringIoC(依赖注入)的基础实现
    spring-context-5.2.3.RELEASE.jar    Spring提供在基础IoC功能上的扩展服务,如邮件服务、任务调度、JNDI定位、EJB集成、远程访问、缓存以及各种视图层框架的封装等
    spring-core-5.2.3.RELEASE.jar        Spring核心包
    spring-expression-5.2.3.RELEASE.jar    Spring表达式语言
    spring-aop-5.2.3.RELEASE.jar        Spring的面向切面编程,提供AOP(面向切面编程)实现

1.2 Spring的JDBC相关包

spring-jdbc-5.2.3.RELEASE.jar        JDBC驱动包
    spring-tx-5.2.3.RELEASE.jar        事务管理
    commons-dbcp2-2.1.1.jar        数据源所需
    commons-pool2-2.4.2.jar        数据源所需

1.3 Spring的aspectj相关包(可选 ,本节用不到)

aopalliance-1.0.jar        AspectJ包(三个)
    aspectjrt-1.9.5.jar
    aspectjweaver-1.8.7.jar

1.4 Spring MVC相关包

spring-webmvc-5.2.3.RELEASE.jar
    spring-web-5.2.3.RELEASE.jar

1.5 MyBatis相关包

mybatis-3.5.2.jar
    ant-1.10.3.jar
    ant-launcher-1.10.3.jar
    asm-7.0.jar
    cglib-3.2.10.jar
    commons-logging-1.2.jar
    javassist-3.24.1-GA.jar
    log4j-1.2.17.jar
    log4j-api-2.11.2.jar
    log4j-core-2.11.2.jar
    ognl-3.2.10.jar
    slf4j-api-1.7.26.jar
    slf4j-log4j12-1.7.26.jar

1.6 其它包

mysql-connector-java-5.1.49-bin.jar    MySQL数据库驱动
mybatis-spring-1.3.1.jar        Spring与MyBatic整合包

1.7 pom.xml文件参考

Spring/Spring MVC/MyBatis整合详解
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation
="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>ssmgroupId>
<artifactId>ssmartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>warpackaging>
<name>ssmname>
<description />
<properties>
<webVersion>4.0webVersion>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>8.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.glassfish.webgroupId>
<artifactId>javax.servlet.jsp.jstlartifactId>
<version>1.2.4version>
dependency>
    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>log4j<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>log4j<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>1.2.17<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.springframework<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>spring-context<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>5.2.3.RELEASE<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.springframework<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>spring-aop<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>5.2.17.RELEASE<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.aspectj<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>aspectjrt<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>1.8.7<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.aspectj<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>aspectjweaver<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>1.8.7<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>aopalliance<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>aopalliance<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>1.0<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.springframework<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>spring-web<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>5.2.17.RELEASE<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.springframework<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>spring-webmvc<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>5.2.17.RELEASE<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.springframework<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>spring-jdbc<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>5.2.3.RELEASE<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.mybatis<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>mybatis<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>3.5.2<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.projectlombok<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>lombok<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>1.18.20<span><span>version</span><span>&gt;</span>
        <span>&lt;</span><span>scope</span><span>&gt;</span>provided<span><span>scope</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>junit<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>junit<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>4.13<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.apache.commons<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>commons-dbcp2<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>2.9.0<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.apache.commons<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>commons-pool2<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>2.11.1<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>mysql<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>mysql-connector-java<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>5.1.49<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>com.fasterxml.jackson.core<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>jackson-databind<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>2.12.5<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>com.fasterxml.jackson.core<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>jackson-core<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>2.12.5<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>com.fasterxml.jackson.core<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>jackson-annotations<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>2.12.5<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>commons-fileupload<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>commons-fileupload<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>1.3.3<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>commons-io<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>commons-io<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>2.6<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>org.mybatis<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>mybatis-spring<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>1.3.3<span><span>version</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>

    <span>&lt;</span><span>dependency</span><span>&gt;</span>
        <span>&lt;</span><span>groupId</span><span>&gt;</span>oraclejdbc<span><span>groupId</span><span>&gt;</span>
        <span>&lt;</span><span>artifactId</span><span>&gt;</span>oraclejdbc<span><span>artifactId</span><span>&gt;</span>
        <span>&lt;</span><span>version</span><span>&gt;</span>4.0<span><span>version</span><span>&gt;</span>
        <span>&lt;</span><span>scope</span><span>&gt;</span>system<span><span>scope</span><span>&gt;</span>
        <span>&lt;</span><span>systemPath</span><span>&gt;</span>${project.basedir}/lib/ojdbc6.jar<span><span>systemPath</span><span>&gt;</span>
    <span><span>dependency</span><span>&gt;</span>
<span><span>dependencies</span><span>&gt;</span>
<span>&lt;</span><span>build</span><span>&gt;</span>
    <span>&lt;</span><span>plugins</span><span>&gt;</span>
        <span>&lt;</span><span>plugin</span><span>&gt;</span>
            <span>&lt;</span><span>artifactId</span><span>&gt;</span>maven-compiler-plugin<span><span>artifactId</span><span>&gt;</span>
            <span>&lt;</span><span>version</span><span>&gt;</span>2.3.2<span><span>version</span><span>&gt;</span>
            <span>&lt;</span><span>configuration</span><span>&gt;</span>
                <span>&lt;</span><span>source</span><span>&gt;</span>1.8<span><span>source</span><span>&gt;</span>
                <span>&lt;</span><span>target</span><span>&gt;</span>1.8<span><span>target</span><span>&gt;</span>
            <span><span>configuration</span><span>&gt;</span>
        <span><span>plugin</span><span>&gt;</span>
        <span>&lt;</span><span>plugin</span><span>&gt;</span>
            <span>&lt;</span><span>artifactId</span><span>&gt;</span>maven-war-plugin<span><span>artifactId</span><span>&gt;</span>
            <span>&lt;</span><span>version</span><span>&gt;</span>3.2.3<span><span>version</span><span>&gt;</span>
            <span>&lt;</span><span>configuration</span><span>&gt;</span>
                <span>&lt;</span><span>failOnMissingWebXml</span><span>&gt;</span>false<span><span>failOnMissingWebXml</span><span>&gt;</span>
            <span><span>configuration</span><span>&gt;</span>
        <span><span>plugin</span><span>&gt;</span>
    <span><span>plugins</span><span>&gt;</span>
    <span>&lt;</span><span>resources</span><span>&gt;</span>
        <span>&lt;</span><span>resource</span><span>&gt;</span>
            <span>&lt;</span><span>directory</span><span>&gt;</span>lib<span><span>directory</span><span>&gt;</span>
            <span>&lt;</span><span>targetPath</span><span>&gt;</span>/WEB-INF/lib/<span><span>targetPath</span><span>&gt;</span>
            <span>&lt;</span><span>includes</span><span>&gt;</span>
                <span>&lt;</span><span>include</span><span>&gt;</span>**/*.jar<span><span>include</span><span>&gt;</span>
            <span><span>includes</span><span>&gt;</span>
        <span><span>resource</span><span>&gt;</span>
    <span><span>resources</span><span>&gt;</span>
<span><span>build</span><span>&gt;</span>

project>

View Code

注意:本配置文件额外引用lombok、junit、jackson、fileupload、oraclejdbc(本地引用)等相关包;不需要的,请自行删除。

二、创建配置文件

2.1 创建db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xuejia?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=admin
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

2.2 创建log4j.properties

Global logging configuration
log4j.rootLogger=ERROR, stdout
MyBatis logging configuration...

log4j.logger.com.itheima=DEBUG
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

2.3 创建applicationContext.xml

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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

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

    <bean id="dataSource"
        class="org.apache.commons.dbcp2.BasicDataSource">

        <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="${jdbc.maxTotal}" />

        <property name="maxIdle" value="${jdbc.maxIdle}" />

        <property name="initialSize" value="${jdbc.initialSize}" />
    bean>

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

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

    <bean id="sqlSessionFactory"
        class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />

        <property name="configLocation"
            value="classpath:mybatis-config.xml" />
    bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.dao" />
    bean>

    <context:component-scan
        base-package="com.itheima.service" />
beans>

该文件中,首先根据db.properties的信息配置数据源;然后配置事务管理器并开启事务注解;接下来配置整合MyBatis框架的MyBatis工厂信息,最后定义mapper扫描器来扫描DAO层以及扫描Service层的配置。

2.4 创建mybatis-config.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="com.itheima.po" />
    typeAliases>
configuration>

由于在Spring中已经配置数据源信息以及mapper接口文件扫描器,所以在MyBatis的配置文件中只需要根据POJO类路径进行别名配置即可。

2.5 创建springmvc-config.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:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:component-scan base-package="com.itheima.controller" />

    <mvc:annotation-driven />

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

该文件中,主要配置用于扫描@Controller注解的包扫描器、注解驱动器以及视图解析器。

2.6 创建web.xml

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://xmlns.jcp.org/xml/ns/javaee"
      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
      id="WebApp_ID" version="3.1">

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

    <filter>
        <filter-name>encodingfilter-name>
        <filter-class>
             org.springframework.web.filter.CharacterEncodingFilter
        filter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingfilter-name>
        <url-pattern>*.actionurl-pattern>
    filter-mapping>

    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>
             org.springframework.web.servlet.DispatcherServlet
        servlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc-config.xmlparam-value>
        init-param>

        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>

        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

该文件中,配置Spring的文件监听器、编码过滤器以及Spring MVC的前端控制器等信息。

三、创建各种程序

3.1 创建PO类

package com.itheima.po;
/**
 * 客户持久化类
 */
public class Customer {
    private Integer id;       // 主键id
    private String username; // 客户名称
    private String jobs;      // 职业
    private String phone;     // 电话
    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;
    }
    public String getJobs() {
        return jobs;
    }
    public void setJobs(String jobs) {
        this.jobs = jobs;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
}

此实体类对应的数据库SQL语句为:

CREATE TABLE t_customer (
  ID int(11) NOT NULL AUTO_INCREMENT,
  USERNAME varchar(45) NOT NULL,
  JOBS varchar(45) DEFAULT NULL,
  PHONE varchar(45) DEFAULT NULL,
  PRIMARY KEY (ID)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

3.2 创建Dao类,及其对应的映射文件(同一个package)

CustomerDao.java

package com.itheima.dao;
import com.itheima.po.Customer;
/**
 * Customer接口文件
 */
public interface CustomerDao {
    /**
     * 根据id查询客户信息
     */
    public Customer findCustomerById(Integer id);
}

CustomerDao.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="com.itheima.dao.CustomerDao">

    <select id="findCustomerById" parameterType="Integer"
                                       resultType="Customer">
        select * from t_customer where id = #{id}
    select>
mapper>

说明:配置文件applicationContext.xml,已经配置mapper扫描器扫描com.itheima.dao包下的所有接口及映射文件,所以此处完成DAO层接口及映射文件开发后,工作即告一段落。

3.3 创建service接口类,及其实现类

CustomerService.java

package com.itheima.service;
import com.itheima.po.Customer;
public interface CustomerService {
    public Customer findCustomerById(Integer id);
}

CustomerServiceImpl.java

package com.itheima.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.dao.CustomerDao;
import com.itheima.po.Customer;
import com.itheima.service.CustomerService;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
    //注解注入CustomerDao
    @Autowired
    private CustomerDao customerDao;
    //查询客户
    public Customer findCustomerById(Integer id) {
        return this.customerDao.findCustomerById(id);
    }
}

该文件中,使用@Service注解来标识业务层的实现类,使用@Transactional注解来标识类中所有方法都纳入Spring的事务管理,并使用@Autowired注解将CustomerDao对象注入到本类中,然后在本类的查询方法中调用CustomerDao对象的查询客户方法。

注:@Transactional注解主要针对数据的增加、修改、删除,此处仅为说明使用。

3.4 创建控制器类

package com.itheima.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.itheima.po.Customer;
import com.itheima.service.CustomerService;
@Controller
public class CustomerController {
    @Autowired
    private CustomerService customerService;
    /**
     * 根据id查询客户详情
     */
    @RequestMapping("/findCustomerById")
    public String findCustomerById(Integer id,Model model) {
        Customer customer = customerService.findCustomerById(id);
        model.addAttribute("customer", customer);
        //返回客户信息展示页面
        return "customer";
    }
}

该文件中,使用@Controller注解来标识控制器类,然后通过@Autowired注解将CustomerService接口对象注入到本类中,最后编写一个根据id查询客户的方法findCustomerById,并将结果返回到视图名为customer的JSP页面中。

3.5 创建JSP页面customer.jsp,位于:WEB-INF\jsp

@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>客户信息title>
head>
<body>
    <table border=1>
        <tr>
            <td>编号td>
            <td>名称td>
            <td>职业td>
            <td>电话td>
        tr>
        <tr>
            <td>${customer.id}td>
            <td>${customer.username}td>
            <td>${customer.jobs}td>
            <td>${customer.phone}td>
        tr>
    table>
body>
html>

四、测试,打开页面:http://localhost:8080/ssm/findCustomerById?id=1

Spring/Spring MVC/MyBatis整合详解

结果如上图所示。

Original: https://www.cnblogs.com/nayitian/p/15379765.html
Author: 那些年的事儿
Title: Spring/Spring MVC/MyBatis整合详解

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/540839/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Mysql安装后打开MySQL Command Line Client闪退的解决方法

    问题原因:安装时mysql command line Client中的my.ini目录地址是MySQL软件的地址!实际上,我们安装MySQL时,一般是MySQL软件地址和MySQL…

    Java 2023年6月5日
    079
  • 新的开始

    新的开始 很久之前就动过写博客的想法,因为我个人认为每天写博客是一个很好的习惯,写博客的过程就是把你今天所学到的知识进行系统性的总结,不仅可以加强你今天所学的知识的印象,后面复习的…

    Java 2023年6月15日
    092
  • SpringBootWeb开发-登录和拦截器实现

    引言:实现拦截器功能,这里是通过session的方式,在登录请求发起的时候,通过往请求里添加session,request.getSession().setAttribute(&#…

    Java 2023年6月9日
    070
  • ElasticSearch(三)SpringBoot 整合ES

    ElasticSearch(三)SpringBoot 整合ES 使用Java API 这种方式,官方已经明确表示在ES 7.0 版本中弃用 TransportClient 客户端,…

    Java 2023年6月5日
    0121
  • JavaBean内省与BeanInfo

    Java的BeanInfo在工作中并不怎么用到,我也是在学习spring源码的时候,发现SpringBoot启动时候会设置一个属叫”spring.beaninfo.ig…

    Java 2023年6月8日
    087
  • Java编程题(1):n个数里出现次数大于等于n/2的数

    题目描述:输入n个整数,输出出现次数大于等于数组长度一半的数。 输入描述:每个测试输入包含 n个空格分割的n个整数,n不超过100,其中有一个整数出现次数大于等于n/2。 输出描述…

    Java 2023年6月6日
    0116
  • Kafka

    1. Kafka简介 1.1 消息队列 1.1.1 消息队列简介 消息Message:通讯设备之间传递的数据 队列Queue:一种特殊的线性表(数据元素首尾相连),特殊之处在于只允…

    Java 2023年6月8日
    0112
  • java日常开发必备:list的四种遍历

    在平时的开发过程中使用List的场景很多,你知道List的遍历有多少种方式?今天一起来梳理下List的几种遍历方式。这里以java.util.ArrayList为例来演示。 这里有…

    Java 2023年6月9日
    0102
  • MySQL 数据库性能优化之索引优化

    Original: https://www.cnblogs.com/wxweven/archive/2012/04/18/2454984.htmlAuthor: wxwevenTi…

    Java 2023年6月9日
    0150
  • lambda表达式常用01

    1、 优化线程代码 以前我们使用线程可能是这么使用的: 使用lambda: 再次进行优化写法: 2.Arrays.sort 排序优化 在代码中,我们会使用Arrays.sort对数…

    Java 2023年6月9日
    096
  • 【系列文章】Maven 源码解析:依赖调解是如何实现的?

    系列文章目录(请务必按照顺序阅读): 给自己的公众号打个广告 欢迎大家关注我的公众号:xiaoxi666,一起来玩一起学! Original: https://www.cnblog…

    Java 2023年6月16日
    079
  • Java设计模式——观察者模式的灵活应用

    灵感来源于一个猪队友给我的题目 看到这个,我抓住的关键字是: 任何子任务失败,要通知所有子任务执行取消逻辑。 这不就是消息广播吗?观察者模式! 干活 首先是收听者 package …

    Java 2023年5月29日
    076
  • Spring Boot【快速入门】

    转自: https://www.cnblogs.com/wmyskxz/p/9010832.html Spring Boot 概述 Build Anything with Spri…

    Java 2023年5月30日
    071
  • 自定义注解获取当前登录用户

    在做项目的时候,我们经常会用到当前登录的用户,获取这个用户相关的信息,总是用User user = session.getAttribute(“user”)…

    Java 2023年6月16日
    0178
  • Spring 集成 Swagger

    Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务 Swagger 的目标是对 REST API 定义一个标准且和语言无关的…

    Java 2023年5月30日
    091
  • Mybatis系列全解(五):全网最全!详解Mybatis的Mapper映射文件

    Mybatis系列全解(五):全网最全!详解Mybatis的Mapper映射文件 Mybatis系列全解(五):全网最全!详解Mybatis的Mapper映射文件 – …

    Java 2023年6月7日
    0105
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球