SSM整合

SSM整合

1.引入环境所需maven依赖



<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.drcgroupId>
  <artifactId>personal_blogartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>personal_blog Maven Webappname>
  
  <url>http://www.example.comurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
  properties>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.46version>
    dependency>
    <dependency>
      <groupId>com.mchangegroupId>
      <artifactId>c3p0artifactId>
      <version>0.9.5.2version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.1version>
    dependency>
    
    <dependency>
      <groupId>org.mybatis.generatorgroupId>
      <artifactId>mybatis-generator-coreartifactId>
      <version>1.3.5version>
    dependency>

    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>5.1.5.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>5.1.5.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>5.1.5.RELEASEversion>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>5.1.5.RELEASEversion>
    dependency>

    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.2version>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>5.1.5.RELEASEversion>
    dependency>
  dependencies>

  <build>
    <finalName>personal_blogfinalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-pluginartifactId>
          <version>3.1.0version>
        plugin>
        
        <plugin>
          <artifactId>maven-resources-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-compiler-pluginartifactId>
          <version>3.8.0version>
        plugin>
        <plugin>
          <artifactId>maven-surefire-pluginartifactId>
          <version>2.22.1version>
        plugin>
        <plugin>
          <artifactId>maven-war-pluginartifactId>
          <version>3.2.2version>
        plugin>
        <plugin>
          <artifactId>maven-install-pluginartifactId>
          <version>2.5.2version>
        plugin>
        <plugin>
          <artifactId>maven-deploy-pluginartifactId>
          <version>2.8.2version>
        plugin>
      plugins>
    pluginManagement>
  build>
project>

2.配置文件

配置文件主要有 日志配置文件spring-mybatis 配置文件springmvc配置文件数据库连接信息配置文件mybatis-generator配置文件web.xml

3.整合spring和mybatis

1) log4j .properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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)jdbc.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis
jdbc.username = root
jdbc.password = 123
# 可以继续配置其他属性

3)spring-mybatis.xml

这个配置文件主要完成spring和mybatis的整合,配置的内容有自动扫描、自动注入、配置数据库等。


<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
        http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:component-scan base-package="com.drc.blog.dao"/>
    
    <context:property-placeholder location="jdbc.properties"/>

    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        
        <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
    bean>
    
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.drc.blog.dao"/>
    bean>

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

4) 创建表

create table t_test {
	tid int primary key auto_increment,
	tname varchar(255)
}

5) mybatis 逆向工程

配置文件:mybatis-generator.xml



<generatorConfiguration>
    
    <context id="DB2Tables" targetRuntime="MyBatis3Simple">
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/personal_blog"
                        userId="root" password="123"/>
        
        <javaTypeResolver>
            <property name="forceBigDecimal" value="false"/>
        javaTypeResolver>
        
        <javaModelGenerator targetPackage="com.drc.blog.domain" targetProject=".\src\main\java">
            <property name="trimStrings" value="true"/>
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="mybatis.mapper" targetProject=".\src\main\resources">
            <property name="enableSubPackage" value="true"/>
        sqlMapGenerator>
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.drc.blog.dao" targetProject=".\src\main\java">
            <property name="enableSubPackage" value="true"/>
        javaClientGenerator>
        
        <table tableName="test" domainObjectName="Test">
            
            <property name="useActualColumnNames" value="false"/>
        table>
    context>
generatorConfiguration>

驱动类:MybatisGenerator.java

package com.drc.blog.mybatis;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MybatisGenerator {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("src\\main\\resources\\mybatis.generator\\mybatis-generator.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

以上是测试数据,接下来测试整合是否成功

6) 测试mybatis整合spring

package com.drc.blog.test;

import com.drc.blog.dao.TestMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;

/**
 * 测试mybatis整合spring
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-mybatis.xml")
public class MybatisSpringTest {
    /*
    没有在mapper接口上配置@Repositroy("testMapper")
    Autowired & Resource 都可以使用
     */
//    @Autowired
    @Resource(name="testMapper")
    private TestMapper testMapper;
    @Test
    public void test1() {
        List<com.drc.blog.domain.Test> tests = testMapper.selectAll();
        tests.forEach(test -> System.out.println(test.getTname()));
    }
}

测试过程出现的问题:

  1. NoSuchBeanException:no bean named ‘testMapper’ can be found 没有testMapper 这个bean

原因是在spring-mybatis.xml中没有配置MapperScannerConfigurer(整合包中的类),无法创建接口的代理对象。

  1. 由于由于粗心的原因,部分配置文件出现出现了一些小问题,还需要熟悉。

测试通过,需要注意的一点:在第一次注入testMapper时,并没有在Mapper上添加任何注解,完全由配置文件进行配置,Mapper接口的名称就是TestMapper。

而后,通过注解的方式将在TestMapper上添加 @Repository(“tmapper”);再次进行测试,发现NoSuchBeanException。然后在测试类中修改注入时的name为 “tmapper”,测试通过。

关闭spring的component-scan,仍然可以扫描。所以扫描mapper接口使用的是MapperScannerConfig

4.springMVC配置

1) spring-mvc.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"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <context:component-scan base-package="com.drc.blog.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>

2) web.xml



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring-*.xmlparam-value>
  context-param>
  
  <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>
  filter>
  
  <filter>
    <filter-name>hiddenfilter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  
  <filter-mapping>
    <filter-name>hiddenfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  
  <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>
web-app>

3) controller

package com.drc.blog.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}


总结

第一次整合ssm,整合的步骤一般都是先完成spring和一个框架的整合,然后再完成spring和另一个框架的整合。而springmvc是属于spring的一个web框架,所以不需要中间包进行整合,mybatis也提供了mybatis-spring支持整合。本次整合使用了spring-mybatis.xml(mapper接口的配置)和spring-mvc.xml(springMVC配置)分别管理dao层和controller层的bean,没有写到对service层以及事务的配置。准备的是创建一个spring-tx.xml 用于管理service层的bean以及事务控制,如果有不妥之处,还望指出!

你可能感兴趣的:(Java)