SSM整合

1. 依赖添加

  1. 数据库准备

    依然沿用mybatis数据库测试脚本!

    CREATE DATABASE `mybatis-example`;
    
    USE `mybatis-example`;
    
    CREATE TABLE `t_emp`(
      emp_id INT AUTO_INCREMENT,
      emp_name CHAR(100),
      emp_salary DOUBLE(10,5),
      PRIMARY KEY(emp_id)
    );
    
    INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("tom",200.33);
    INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("jerry",666.66);
    INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("andy",777.77);
    
  2. 准备项目

    part04-ssm-integration

    转成web项目

  3. 依赖导入

    pom.xml

    
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
      <modelVersion>4.0.0modelVersion>  
      <groupId>com.atguigugroupId>  
      <artifactId>part04-ssm-integrationartifactId>  
      <version>1.0-SNAPSHOTversion>  
      <packaging>warpackaging>
      <properties>
        <spring.version>6.0.6spring.version>
        <jakarta.annotation-api.version>2.1.1jakarta.annotation-api.version>
        <jakarta.jakartaee-web-api.version>9.1.0jakarta.jakartaee-web-api.version>
        <jackson-databind.version>2.15.0jackson-databind.version>
        <hibernate-validator.version>8.0.0.Finalhibernate-validator.version>
        <commons-fileupload.version>1.3.1commons-fileupload.version>
        <mybatis.version>3.5.11mybatis.version>
        <mysql.version>8.0.25mysql.version>
        <pagehelper.version>5.1.11pagehelper.version>
        <druid.version>1.2.8druid.version>
        <mybatis-spring.version>3.0.2mybatis-spring.version>
        <jakarta.servlet.jsp.jstl-api.version>3.0.0jakarta.servlet.jsp.jstl-api.version>
        <logback.version>1.2.3logback.version>
        <lombok.version>1.18.26lombok.version>
    
        <maven.compiler.source>17maven.compiler.source>
        <maven.compiler.target>17maven.compiler.target>  
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> 
      properties>
      
    
      <dependencies>
        
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-contextartifactId>
          <version>${spring.version}version>
        dependency>
    
        <dependency>
          <groupId>jakarta.annotationgroupId>
          <artifactId>jakarta.annotation-apiartifactId>
          <version>${jakarta.annotation-api.version}version>
        dependency>
    
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-aopartifactId>
          <version>${spring.version}version>
        dependency>
    
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-aspectsartifactId>
          <version>${spring.version}version>
        dependency>
    
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-txartifactId>
          <version>${spring.version}version>
        dependency>
    
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-jdbcartifactId>
          <version>${spring.version}version>
        dependency>
          
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webmvcartifactId>
          <version>${spring.version}version>
        dependency>
    
        <dependency>
          <groupId>jakarta.platformgroupId>
          <artifactId>jakarta.jakartaee-web-apiartifactId>
          <version>${jakarta.jakartaee-web-api.version}version>
          <scope>providedscope>
        dependency>
    
        
        <dependency>
          <groupId>jakarta.servlet.jsp.jstlgroupId>
          <artifactId>jakarta.servlet.jsp.jstl-apiartifactId>
          <version>${jakarta.servlet.jsp.jstl-api.version}version>
        dependency>
         
        <dependency>
          <groupId>commons-fileuploadgroupId>
          <artifactId>commons-fileuploadartifactId>
          <version>${commons-fileupload.version}version>
        dependency>
    
        <dependency>
          <groupId>com.fasterxml.jackson.coregroupId>
          <artifactId>jackson-databindartifactId>
          <version>${jackson-databind.version}version>
        dependency>
          
        <dependency>
          <groupId>org.hibernate.validatorgroupId>
          <artifactId>hibernate-validatorartifactId>
          <version>${hibernate-validator.version}version>
        dependency>
        
        <dependency>
          <groupId>org.hibernate.validatorgroupId>
          <artifactId>hibernate-validator-annotation-processorartifactId>
          <version>${hibernate-validator.version}version>
        dependency>
          
        
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatisartifactId>
          <version>${mybatis.version}version>
        dependency>
    
        
        <dependency>
          <groupId>mysqlgroupId>
          <artifactId>mysql-connector-javaartifactId>
          <version>${mysql.version}version>
        dependency>
    
        <dependency>
          <groupId>com.github.pagehelpergroupId>
          <artifactId>pagehelperartifactId>
          <version>${pagehelper.version}version>
        dependency>
    
        
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webartifactId>
          <version>${spring.version}version>
        dependency>
    
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatis-springartifactId>
          <version>${mybatis-spring.version}version>
        dependency>
    
        
        <dependency>
          <groupId>ch.qos.logbackgroupId>
          <artifactId>logback-classicartifactId>
          <version>${logback.version}version>
        dependency>
    
        <dependency>
          <groupId>org.projectlombokgroupId>
          <artifactId>lombokartifactId>
          <version>${lombok.version}version>
        dependency>
        
        <dependency>
          <groupId>com.alibabagroupId>
          <artifactId>druidartifactId>
          <version>${druid.version}version>
        dependency>
        
      dependencies>
    
    project>
    
  4. 实体类添加

    com.atguigu.pojo

    @Data
    public class Employee {
    
        private Integer empId;
        private String empName;
        private Double empSalary;
    }
    
  5. logback配置

    位置:resources/logback.xml

    
    <configuration debug="true">
        
        <appender name="STDOUT"
                  class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                
                
                <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%npattern>
                <charset>UTF-8charset>
            encoder>
        appender>
    
        
        
        <root level="DEBUG">
            
            <appender-ref ref="STDOUT" />
        root>
    
        
        <logger name="com.atguigu.mybatis" level="DEBUG" />
    
    configuration>
    

2. 控制层配置编写

主要配置controller,springmvc相关! 本次先不配置文件上传!

位置:resources/spring-mvc.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 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="com.atguigu.controller" />

    
    <mvc:annotation-driven />
     

    
    
    <mvc:default-servlet-handler/>

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

3. 业务层配置编写

主要配置service,注解aop和声明事务相关!

位置:resources/spring-service.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: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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

       
       <context:component-scan base-package="com.atguigu.service,com.atguigu.advice,com.atguigu.pointcut" />
    
       
       <aop:aspectj-autoproxy />
    
       
       <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
           <property name="dataSource" ref="dataSource" />
       bean>
    
       <tx:annotation-driven transaction-manager="transactionManager" /> 
beans>

4. 持久层配置编写

jdbc外部配置

位置:resources/jdbc.properties

jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql:///mybatis-example
jdbc.driver=com.mysql.cj.jdbc.Driver

持久层配置

位置:resources/spring-mapper.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:jdbc.properties"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
    bean>
    
beans>

配置mybatis方式1:保留mybaits全局配置

准备mybatis-config.xml文件:去掉数据库信息,去掉mapper包映射(xml中配置)


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        
        <setting name="logImpl" value="SLF4J"/>
        
        <setting name="autoMappingBehavior" value="FULL"/>
    settings>

    <typeAliases>
        
        <package name="com.atguigu.pojo"/>
    typeAliases>

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            
            <property name="helperDialect" value="mysql"/>
        plugin>
    plugins>
    
configuration>

修改spring-mapper.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:jdbc.properties"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
    bean>

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

    
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.atguigu.mapper"/>
    bean>
    
    
beans>

配置mybatis方式2:完全配置文件实现

修改spring-mapper.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:jdbc.properties"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
    bean>

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

        
        <property name="configuration">
            <bean class="org.apache.ibatis.session.Configuration">
                <property name="mapUnderscoreToCamelCase" value="true"/>
            bean>
        property>

        
        <property name="typeAliasesPackage" value="com.atguigu.pojo"/>

        
        <property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>

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

    bean>

    
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.atguigu.mapper"/>
    bean>
    
beans>
  1. 容器初始化配置web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">

  
  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring-service.xml,classpath:spring-mapper.xmlparam-value>
  context-param>

  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

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

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

web-app>

6. 整合测试

  1. 需求

    查询所有员工信息,返回对应json数据!

  2. controller

    @Slf4j
    @RestController
    @RequestMapping("/employee")
    public class EmployeeController {
    
        @Autowired
        private EmployeeService employeeService;
    
        @GetMapping("list")
        public List<Employee> retList(){
            List<Employee> employees = employeeService.findAll();
            log.info("员工数据:{}",employees);
            return employees;
        }
    }
    
  3. service

    @Service
        public class EmployeeServiceImpl implements EmployeeService {
    
            @Autowired
            private EmployeeMapper employeeMapper;
    
            /**
             * 查询所有员工信息
             */
            @Override
            public List<Employee> findAll() {
                List<Employee> employeeList =  employeeMapper.queryAll();
                return employeeList;
            }
        }
    
  4. mapper

    mapper接口 包:com.atguigu.mapper

    public interface EmployeeMapper {
    
         List<Employee> queryAll();
    }
    

    mapper XML 文件位置: resources/mappers

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.atguigu.mapper.EmployeeMapper">
    
        <select id="queryAll" resultType="employee">
            
            select emp_id empId,emp_name empName, emp_salary empSalary from t_emp
        select>
    
    mapper>
    

你可能感兴趣的:(SSM,SSM)