Spring && SpringMVC && Mybatis

前言——SSM回顾

Spring

Mybatis

SpringMVC

1、导入ssm框架的基本依赖

<?xml version="1.0" encoding="UTF-8"?>

<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.0</modelVersion>

  <groupId>com.bjpowernode</groupId>
  <artifactId>mimissm</artifactId>
  <version>1.0</version>
  <packaging>war</packaging>

  <!-- 集中定义依赖版本号 -->
  <properties>
    <junit.version>4.12</junit.version>
    <spring.version>5.2.5.RELEASE</spring.version>

    <mybatis.version>3.5.1</mybatis.version>
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
    <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
    <mysql.version>8.0.22</mysql.version>
    <druid.version>1.1.12</druid.version>
    <pagehelper.version>5.1.2</pagehelper.version>

    <servlet-api.version>3.0.1</servlet-api.version>
    <jsp-api.version>2.0</jsp-api.version>

    <jstl.version>1.2</jstl.version>
    <slf4j.version>1.6.4</slf4j.version>
    <jackson.version>2.9.6</jackson.version>
  </properties>


  <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jms</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- Mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
    <dependency>
      <groupId>com.github.miemiedev</groupId>
      <artifactId>mybatis-paginator</artifactId>
      <version>${mybatis.paginator.version}</version>
    </dependency>
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>${pagehelper.version}</version>
    </dependency>
    <!-- MySql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- 连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>

    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>


    <!-- JSP相关 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <scope>provided</scope>
      <version>${jsp-api.version}</version>
    </dependency>
    <!-- Jackson Json处理工具包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20140107</version>
    </dependency>

    <!--    文件异步上传使用的依赖-->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
  </dependencies>

  <!-- 插件配置 -->
  <build>

    <!-- 构建过程中用到的插件 -->
    <plugins>
      <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.7</version>
        <!-- 插件的依赖 -->
        <dependencies>
          <!-- 逆向工程的核心依赖 -->
          <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
          </dependency>
          <!-- MySQL驱动 -->
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
          </dependency>
        </dependencies>
      </plugin>
      <plugin>
        <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
    </plugins>
    <!--识别所有的配置文件-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>


</project>

2、SSM工程整合流程

2.1、数据库配置文件db.properties

jdbc.url=jdbc:mysql://localhost:3306/xiaomissm?user=root&password=&useUnicode=true&characterEncoding=gbk&serverTimezone=Asia/Shanghai
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.user=xxxx
jdbc.passward=xxxxxx

2.2、mybatis配置文件mybatisConfig.xml

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--分页插件的配置,此处使用pagehelper插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper"></plugin>
    </plugins>
</configuration>

2.3、spring配置文件applicationContext.xml

  • 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:p="http://www.springframework.org/schema/p"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<import resource="classpath*:configrations/ApplicationContext_dao.xml"/>
<import resource="classpath*:configrations/ApplicationContext_service.xml"/>
<import resource="classpath*:configrations/ApplicationContext_trans.xml"/>

</beans>
2.3.1 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--引入数据库文件-->
    <context:property-placeholder location="classpath*:db.Properties"/>
    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="password" value="${jdbc.passward}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="driver" value="${jdbc.driverClass}"/>
        <property name="url" value="${jdbc.url}"/>
    </bean>
    <!--配置SqlSessionFactoryBean-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" xml:base="Mybatisconfig.xml">
        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--
        需要注意的是 SqlSessionFactoryBean 实现了 Spring 的 FactoryBean 接口。
        这意味着由 Spring 最终创建的 bean 并不是 SqlSessionFactoryBean 本身,
        而是工厂类(SqlSessionFactoryBean)的 getObject() 方法的返回结果。
        这种情况下,Spring 将会在应用启动时为你创建 SqlSessionFactory,
        并使用 sqlSessionFactory 这个名字存储起来。

        @Bean
        public SqlSessionFactory sqlSessionFactory() {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        return factoryBean.getObject();
        }
        -->
    
  
        <!--配置别名-->
        <property name="typeAliasesPackage" value="entity"></property>
    </bean>
    <!--配置MapperScanner-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
        <property name="basePackage" value="mapper"/>
    </bean>
</beans>
2.3.2 applicationContext_service.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--    设置业务逻辑层的包扫描器,目的是在指定的路径下,使用@Service注解的类,Spring负责创建对象,并添加依赖-->
    <context:component-scan base-package="service"/>

</beans>
2.3.3 applicationContext_trans.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<xsd:schema xmlns="http://www.springframework.org/schema/aop"
			xmlns:xsd="http://www.w3.org/2001/XMLSchema"
			xmlns:tool="http://www.springframework.org/schema/tool"
			targetNamespace="http://www.springframework.org/schema/aop"
			elementFormDefault="qualified"
			attributeFormDefault="unqualified">

	<xsd:import namespace="http://www.springframework.org/schema/beans" schemaLocation="https://www.springframework.org/schema/beans/spring-beans.xsd"/>
	<xsd:import namespace="http://www.springframework.org/schema/tool" schemaLocation="https://www.springframework.org/schema/tool/spring-tool.xsd"/>

	<xsd:annotation>
		<xsd:documentation><![CDATA[
	Defines the configuration elements for the Spring Framework's AOP support.
		]]></xsd:documentation>
	</xsd:annotation>

	<xsd:element name="config">
		<xsd:annotation>
			<xsd:documentation><![CDATA[
	A section (compartmentalization) of AOP-specific configuration (including
	aspects, pointcuts, etc).
			]]></xsd:documentation>
		</xsd:annotation>
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element name="pointcut" type="pointcutType" minOccurs="0" maxOccurs="unbounded">
					<xsd:annotation>
						<xsd:documentation><![CDATA[
	A named pointcut definition.
						]]></xsd:documentation>
					</xsd:annotation>
				</xsd:element>
				<xsd:element name="advisor" type="advisorType" minOccurs="0" maxOccurs="unbounded">
					<xsd:annotation>
						<xsd:documentation source="java:org.springframework.aop.Advisor"><![CDATA[
	A named advisor definition.
						]]></xsd:documentation>
					</xsd:annotation>
				</xsd:element>
				<xsd:element name="aspect" type="aspectType" minOccurs="0" maxOccurs="unbounded">
					<xsd:annotation>
						<xsd:documentation><![CDATA[
	A named aspect definition.
						]]></xsd:documentation>
					</xsd:annotation>
				</xsd:element>
			</xsd:sequence>
			<xsd:attribute name="proxy-target-class" type="xsd:boolean" default="false">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	Are class-based (CGLIB) proxies to be created? By default, standard
	Java interface-based proxies are created.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:attribute>
			<xsd:attribute name="expose-proxy" type="xsd:boolean" default="false">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	Indicate that the proxy should be exposed by the AOP framework as a
	ThreadLocal for retrieval via the AopContext class. Off by default,
	i.e. no guarantees that AopContext access will work.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:attribute>
		</xsd:complexType>
	</xsd:element>

	<xsd:element name="aspectj-autoproxy">
		<xsd:annotation>
			<xsd:documentation source="java:org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"><![CDATA[
	Enables the use of the @AspectJ style of Spring AOP.

	See org.springframework.context.annotation.EnableAspectJAutoProxy Javadoc
	for information on code-based alternatives to this XML element.
			]]></xsd:documentation>
		</xsd:annotation>
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element name="include" type="includeType" minOccurs="0" maxOccurs="unbounded">
					<xsd:annotation>
						<xsd:documentation><![CDATA[
	Indicates that only @AspectJ beans with names matched by the (regex)
	pattern will be considered as defining aspects to use for Spring autoproxying.
						]]></xsd:documentation>
					</xsd:annotation>
				</xsd:element>
			</xsd:sequence>
			<xsd:attribute name="proxy-target-class" type="xsd:boolean" default="false">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	Are class-based (CGLIB) proxies to be created? By default, standard
	Java interface-based proxies are created.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:attribute>
			<xsd:attribute name="expose-proxy" type="xsd:boolean" default="false">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	Indicate that the proxy should be exposed by the AOP framework as a
	ThreadLocal for retrieval via the AopContext class. Off by default,
	i.e. no guarantees that AopContext access will work.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:attribute>
		</xsd:complexType>
	</xsd:element>

	<xsd:element name="scoped-proxy">
		<xsd:complexType>
			<xsd:annotation>
				<xsd:documentation source="java:org.springframework.aop.scope.ScopedProxyFactoryBean"><![CDATA[
	Marks a bean definition as being a scoped proxy.

	A bean marked as such will be exposed via a proxy, with the 'real'
	bean instance being retrieved from some other source (such as a
	HttpSession) as and when required.
				]]></xsd:documentation>
			</xsd:annotation>
			<xsd:attribute name="proxy-target-class" type="xsd:boolean" default="true">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	Are class-based (CGLIB) proxies to be created? This is the default; in order to
	switch to standard Java interface-based proxies, turn this flag to "false".
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:attribute>
		</xsd:complexType>
	</xsd:element>

	<xsd:complexType name="aspectType">
		<xsd:choice minOccurs="0" maxOccurs="unbounded">
			<xsd:element name="pointcut" type="pointcutType">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	A named pointcut definition.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:element>
			<xsd:element name="declare-parents" type="declareParentsType">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	Allows this aspect to introduce additional interfaces that the advised
	object will transparently implement.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:element>
			<xsd:element name="before" type="basicAdviceType">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	A before advice definition.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:element>
			<xsd:element name="after" type="basicAdviceType">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	An after advice definition.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:element>
			<xsd:element name="after-returning" type="afterReturningAdviceType">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	An after-returning advice definition.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:element>
			<xsd:element name="after-throwing" type="afterThrowingAdviceType">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	An after-throwing advice definition.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:element>
			<xsd:element name="around" type="basicAdviceType">
				<xsd:annotation>
					<xsd:documentation><![CDATA[
	An around advice definition.
					]]></xsd:documentation>
				</xsd:annotation>
			</xsd:element>
		</xsd:choice>
		<xsd:attribute name="id" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	The unique identifier for an aspect.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="ref" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	The name of the (backing) bean that encapsulates the aspect.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="order" type="xsd:token">
			<xsd:annotation>
				<xsd:documentation source="java:org.springframework.core.Ordered"><![CDATA[
	Controls the ordering of the execution of this aspect when multiple
	advice executes at a specific joinpoint.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
	</xsd:complexType>

	<xsd:complexType name="includeType">
		<xsd:attribute name="name" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation source="java:java.util.regex.Pattern"><![CDATA[
	The regular expression defining which beans are to be included in the
	list of @AspectJ beans; beans with names matched by the pattern will
	be included.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
	</xsd:complexType>

	<xsd:complexType name="pointcutType">
		<xsd:annotation>
			<xsd:appinfo>
				<tool:annotation>
					<tool:exports type="org.springframework.aop.Pointcut"/>
				</tool:annotation>
			</xsd:appinfo>
		</xsd:annotation>
		<xsd:attribute name="id" type="xsd:string" use="required">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	The unique identifier for a pointcut.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="expression" use="required" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	The pointcut expression.

	For example : 'execution(* com.xyz.myapp.service.*.*(..))'
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
	</xsd:complexType>

	<xsd:complexType name="declareParentsType">
		<xsd:attribute name="types-matching" type="xsd:string" use="required">
			<xsd:annotation>
				<xsd:documentation source="java:org.springframework.aop.aspectj.TypePatternClassFilter"><![CDATA[
	The AspectJ type expression that defines what types (classes) the
	introduction is restricted to.

	An example would be 'org.springframework.beans.ITestBean+'.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="implement-interface" type="xsd:string" use="required">
			<xsd:annotation>
				<xsd:documentation source="java:java.lang.Class"><![CDATA[
	The fully qualified name of the interface that will be introduced.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="default-impl" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation source="java:java.lang.Class"><![CDATA[
	The fully qualified name of the class that will be instantiated to serve
	as the default implementation of the introduced interface.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="delegate-ref" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	A reference to the bean that will serve
	as the default implementation of the introduced interface.
				]]></xsd:documentation>
				<xsd:appinfo>
					<tool:annotation kind="ref"/>
				</xsd:appinfo>
			</xsd:annotation>
		</xsd:attribute>
	</xsd:complexType>

	<xsd:complexType name="basicAdviceType">
		<xsd:attribute name="pointcut" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	The associated pointcut expression.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="pointcut-ref" type="pointcutRefType">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	The name of an associated pointcut definition.
				]]></xsd:documentation>
				<xsd:appinfo>
					<tool:annotation kind="ref">
						<tool:expected-type type="org.springframework.aop.Pointcut"/>
					</tool:annotation>
				</xsd:appinfo>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="method" type="xsd:string" use="required">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	The name of the method that defines the logic of the advice.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="arg-names" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	The comma-delimited list of advice method argument (parameter) names
	that will be matched from pointcut parameters.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
	</xsd:complexType>

	<xsd:complexType name="afterReturningAdviceType">
		<xsd:complexContent>
			<xsd:extension base="basicAdviceType">
				<xsd:attribute name="returning" type="xsd:string">
					<xsd:annotation>
						<xsd:documentation><![CDATA[
	The name of the method parameter to which the return value must
	be passed.
						]]></xsd:documentation>
					</xsd:annotation>
				</xsd:attribute>
			</xsd:extension>
		</xsd:complexContent>
	</xsd:complexType>

	<xsd:complexType name="afterThrowingAdviceType">
		<xsd:complexContent>
			<xsd:extension base="basicAdviceType">
				<xsd:attribute name="throwing" type="xsd:string">
					<xsd:annotation>
						<xsd:documentation><![CDATA[
	The name of the method parameter to which the thrown exception must
	be passed.
						]]></xsd:documentation>
					</xsd:annotation>
				</xsd:attribute>
			</xsd:extension>
		</xsd:complexContent>
	</xsd:complexType>

	<xsd:complexType name="advisorType">
		<xsd:annotation>
			<xsd:appinfo>
				<tool:annotation>
					<tool:exports type="org.springframework.aop.Advisor"/>
				</tool:annotation>
			</xsd:appinfo>
		</xsd:annotation>
		<xsd:attribute name="id" type="xsd:string"/>
		<xsd:attribute name="advice-ref" type="xsd:string" use="required">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	A reference to an advice bean.
				]]></xsd:documentation>
				<xsd:appinfo>
					<tool:annotation kind="ref">
						<tool:expected-type type="org.aopalliance.aop.Advice"/>
					</tool:annotation>
				</xsd:appinfo>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="pointcut" type="xsd:string">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	A pointcut expression.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="pointcut-ref" type="pointcutRefType">
			<xsd:annotation>
				<xsd:documentation><![CDATA[
	A reference to a pointcut definition.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
		<xsd:attribute name="order" type="xsd:token">
			<xsd:annotation>
				<xsd:documentation source="java:org.springframework.core.Ordered"><![CDATA[
	Controls the ordering of the execution of this advice when multiple
	advice executes at a specific joinpoint.
				]]></xsd:documentation>
			</xsd:annotation>
		</xsd:attribute>
	</xsd:complexType>

	<xsd:simpleType name="pointcutRefType">
		<xsd:annotation>
			<xsd:appinfo>
				<tool:annotation kind="ref">
					<tool:expected-type type="org.springframework.aop.Pointcut"/>
				</tool:annotation>
			</xsd:appinfo>
		</xsd:annotation>
		<xsd:union memberTypes="xsd:string"/>
	</xsd:simpleType>

</xsd:schema>

2.4、springmvc配置文件springmvc.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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--设置包扫描器-->
    <context:component-scan base-package="controller"/>
    <!--设置视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--设置前后缀-->
        <property name="prefix" value=""/>
        <property name="suffix" value=""/>
    </bean>
    <!--设置文件上传核心组件-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
    <!--设置注解驱动-->
    <mvc:annotation-driven/>
</beans>

2.5、web.xml配置

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--spring-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.AbstractContextLoaderInitializer</listener-class>
  </listener>
  <!--配置springmvc-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!--指定加载文件,通过contextConfigLocation-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

在上文我们成功搭建了SSM的基本框架并成功的运行出来的helloworld程序;
当然,这样的程序是十分简单的,但他的配置却十分繁琐。

而使用Spring Boot 整合SSM则可以使得搭建过程更为简单

2.6、SSM工程整合流程小技巧

2.6.1、逆向工程generatorConfiguration

逆向生成dao/mapper/entity
generatorConfiguration
逆向工程插件

 <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.7</version>
        <!-- 插件的依赖 -->
        <dependencies>
          <!-- 逆向工程的核心依赖 -->
          <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
          </dependency>
          <!-- MySQL驱动 -->
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
          </dependency>
        </dependencies>
      </plugin>

逆向工程配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--导入属性配置文件-->
    <properties resource="db.Properties"/>
    <!--指定特定数据库的jdbc驱动包的位置-->
    <context id="default" targetRuntime="MyBatis3">
        <!--optional 旨在创建class时,对注释进行控制false:生成注释,true:不生成注释-->
        <commentGenerator>
            <property name="suppressData" value="false"/>
            <property name="suppressAllComments" value="false"/>
        </commentGenerator>
        <!--jdbc的连接-->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.user}"
                        password="${jdbc.passward}">
            <!--MySQL 不支持 schema 或者 catalog 所以需要添加这个-->
            <!--参考 : http://www.mybatis.org/generator/usage/mysql.html-->
            <property name="nullCatalogMeansCurrent" value="true"/>
            <!-- MySQL8默认启用 SSL ,不关闭会有警告-->
            <property name="useSSL" value="false"/>
 		</jdbcConnection>
        <!--非必需,类型处理器,在数据库和Java类型中进行转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成 DataObject 类存放位置 -->
        <javaModelGenerator targetPackage="entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件存放位置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成Dao持久层文件存放位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 生成对应表及其类名 -->
        <table tableName="tb_order" domainObjectName="tbOrder" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <!--            去除复杂操作语句-->
            <!--            enableCountByExample="false"-->
            <!--            enableUpdateByExample="false" -->
            <!--            enableDeleteByExample="false" -->
            <!--            enableSelectByExample="false"-->
            <!--            selectByExampleQueryId="false"-->
        </table>
 <table tableName="tb_order" domainObjectName="tbOrder" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>

    </context>
</generatorConfiguration>

3、 实际效果:
按照预期生成了dao\mapper\entity
在这里插入图片描述

3、Spring Boot 整合SSM

3.1、 准备工作

3.1.1、创建数据库
--- 创建数据库
CREATE DATABASE IF NOT EXISTS `demo` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

--- 创建数据库表
CREATE TABLE `t_user`
(
    `id`         BIGINT(20)   NOT NULL AUTO_INCREMENT COMMENT '编号',
    `login_name` VARCHAR(200) NULL DEFAULT NULL COMMENT '用户名称' COLLATE 'utf8_general_ci',
    `nick_name`  VARCHAR(200) NULL DEFAULT NULL COMMENT '用户昵称' COLLATE 'utf8_general_ci',
    `passwd`     VARCHAR(200) NULL DEFAULT NULL COMMENT '用户密码' COLLATE 'utf8_general_ci',
    PRIMARY KEY (`id`)
);

--- 插入测试数据
insert into t_user(login_name, nick_name, passwd) VALUES ('zhangsan', '张三', '123456');

3.1.2、引入Mybatis整合依赖
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.5</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>3.0.2</version>
    </dependency>
</dependencies>

3.1.3、创建配置文件

在项目的 /src/main/resources 目录下,创建 application.properties 配置文件,添加数据源和 MyBatis 的配置信息(如下)。

# 数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf8&autoReconnect=true&useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

# 指定映射文件的路径
mybatis.mapper-locations=classpath:/mapper/*.xml

# 开启驼峰命名映射
mybatis.configuration.map-underscore-to-camel-case=true

3.1.4、创建映射文件

在项目的 /src/main/resources/mapper 目录下,创建 UserMapper.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.clay.boot.mapper.UserMapper">

    <select id="getById" resultType="com.clay.boot.domain.User">
        select id, login_name, nick_name, passwd
        from `t_user`
    </select>

</mapper>

3.2、案例代码

3.2.1、创建实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

    /**
     * 编号
     */
    private Long id;

    /**
     * 用户名称
     */
    private String loginName;

    /**
     * 用户昵称
     */
    private String nickName;

    /**
     * 用户密码
     */
    private String passwd;

}

3.2.2、创建映射接口
@Mapper
public interface UserMapper {

}

3.2.3、 创建服务类
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User getById(Long id) {
        return userMapper.getById(id);
    }

}

3.2.4、 创建控制器类
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Long id) {
        return userService.getById(id);
    }

}

3.2.5、 创建主启动类

这里需要使用 @MapperScan 注解,指定 Mapper 接口的包扫描路径。值得一提的是,也可以创建独立的 MyBatis 配置类(如 MyBatisConfiguration),然后将 @MapperScan 注解标注在配置类上。

@SpringBootApplication
@MapperScan(basePackages = "com.clay.boot.mapper")
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

}

3.3、Spring Boot 整合SSM小结

SSM 整合流程总结

  • 导入 mybatis-spring-boot-starter
  • 配置数据源信息
  • 配置 MyBatis 的 Mapper 接口扫描与 XML 映射文件扫描
  • 编写 Bean、Mapper,创建 SQL 映射文件(XML),编写 SQL 语句执行 CRUD 操作,事务等操作依然和 Spring 中的用法一样
  • 实现的效果
    • 所有 SQL 都可以写在 XML 中
    • 所有 MyBatis 配置可以写在 application.properties 里面

第一行注释,编辑数据源
第二行注释,告诉Mybatis XML文件在哪里
第三行注释,告诉Mybatis mapper 接口文件在哪里(在主程序上添加@MapperScan(basePakage),或者在每一个Mapper接口文件上单独添加@Mapper注解)
第四行注释,将数据库中的user_name形式的命名转变为userName的驼峰命名

JDBC 场景的自动配置
在这里插入图片描述
MyBatisAutoConfiguration
在这里插入图片描述
如何分析哪个场景导入以后,开启了哪些自动配置类?

在 spring.boot.autoconfigure 包里面找 classpath:/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件中配置的所有值,就是要开启的自动配置类;但是每个类可能有条件注解,基于条件注解判断哪个自动配置类会生效。
快速定位生效的自动配置,方法如下:

# 是否开启调试模式,可以详细打印开启了哪些自动配置,Positive(生效的自动配置),Negative(不生效的自动配置)
debug=true

3.4、整合其他数据源

SpringBoot 默认使用 Hikari 作为数据源。

3.4.1、Druid 数据源

若希望 MyBatis 使用 Druid 数据源,可以参考以下配置内容。值得一提的是,截止目前为止 Druid 暂时不支持 SpringBoot 3。

3.4.1.1、引入 Druid 数据源
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>${druid-version}</version>
</dependency>

3.4.1.2、配置 Druid 数据源
# 数据源基本配置
spring.datasource.url=jdbc:mysql://192.168.200.100:3306/demo
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 配置StatFilter监控
spring.datasource.druid.filter.stat.enabled=true
spring.datasource.druid.filter.stat.db-type=mysql
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000

# 配置WallFilter防火墙
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=mysql
spring.datasource.druid.filter.wall.config.delete-allow=false
spring.datasource.druid.filter.wall.config.drop-table-allow=false

# 配置监控页,内置监控页面的首页是 /druid/index.html
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
spring.datasource.druid.stat-view-servlet.allow=*

# 其他 Filter 的配置这里不再演示,目前支持以下 Filter 的配置,详细说明请参考官方文档或者根据 IDE 提示(spring.datasource.druid.filter.*)进行配置
# StatFilter
# WallFilter
# ConfigFilter
# EncodingConvertFilter
# Slf4jLogFilter
# Log4jFilter
# Log4j2Filter
# CommonsLogFilter

3.5、编写Mapper接口的小技巧

此处可以安装MybatisX插件,
鼠标悬浮接口上右击生成对应的XML文件
鼠标悬浮方法上右击在对应的XML文件中生成SQL语句
在这里插入图片描述

  • 5
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringSpring MVC 和 Spring Boot 都是基于 Java 开发的框架,它们各自有着不同的优势。 Spring框架是一个企业级的开源框架,它提供了一个全面的编程和配置模型,可以帮助开发者快速构建各种类型的应用程序。Spring框架的优势包括: 1. 模块化设计:Spring框架是一个模块化的设计,可以根据需要选择不同的模块来构建应用程序。 2. 松耦合:Spring框架通过依赖注入和面向接口编程等方式,实现了组件之间的松耦合。 3. 事务管理:Spring框架提供了强大的事务管理功能,可以轻松处理数据库事务。 4. AOP支持:Spring框架支持面向切面编程,可以将横切关注点(如日志记录、安全性、事务管理等)从核心业务逻辑中分离出来。 5. 整合其他框架:Spring框架可以与其他框架(如Hibernate、MyBatis等)无缝整合,提供更强大的功能。 Spring MVC框架是Spring框架的一个模块,它是一个基于MVC架构的Web框架,具有以下优势: 1. 简单易用:Spring MVC框架提供了简单易用的API,可以快速构建Web应用程序。 2. 松耦合:Spring MVC框架通过依赖注入和面向接口编程等方式,实现了组件之间的松耦合。 3. 可扩展性:Spring MVC框架提供了灵活的配置选项和可扩展的API,可以满足不同应用程序的需求。 4. 整合其他框架:Spring MVC框架可以与其他框架(如Spring、Hibernate、MyBatis等)无缝整合,提供更强大的功能。 Spring Boot框架是Spring框架的一个扩展,它具有以下优势: 1. 快速开发Spring Boot框架提供了快速开发的功能,可以快速创建可独立运行的Spring应用程序。 2. 自动配置:Spring Boot框架提供了自动配置的功能,可以根据应用程序的需要自动配置Spring框架。 3. 简化配置:Spring Boot框架通过简化配置,减少了开发者的工作量。 4. 可嵌入性:Spring Boot框架可以将应用程序嵌入到Web容器中,或者作为独立的应用程序运行。 总之,SpringSpring MVC 和 Spring Boot 都是非常优秀的框架,可以帮助开发者快速构建各种类型的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值