ssm整合

Posted svipero

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ssm整合相关的知识,希望对你有一定的参考价值。

项目目录

技术图片

 

 

1.引入必要的依赖pom.xml

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.1.0.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <!--应用变量-->
            <version>${spring.version}</version>
        </dependency>
        <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-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</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-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--事务-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>

        <!--mybatis和spring的兼容包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>


        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

<!-- 并加入mybatis逆向插件,在build标签中-->
<plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generator.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>

2.mybatis逆向xml配置文件generator.xml

<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动包位置 -->
    <classPathEntry location="E:mysql-connector-java-5.1.6.jar" />
    <!--<classPathEntry location="C:UsersAdministrator.m2
epositorycomoracleojdbc611.2.0.4.0-atlassian-hostedojdbc6-11.2.0.4.0-atlassian-hosted.jar" />-->
    <context id="mysql" targetRuntime="MyBatis3">
        <!-- 生成的Java文件的编码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 格式化java代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <commentGenerator>
            <!--是否关闭注释-->
            <property name="suppressAllComments" value="false" />
            <!--是否关闭时间标识-->
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!-- 数据库链接URL、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/db_test?characterEncoding=UTF-8" userId="root" password="5445abcd">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="com.wolf.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成的映射文件包名和位置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成mapper接口的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.wolf.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
        <!-- 选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素
            选择的table会生成一下文件:
            1,SQL map文件
            2,生成一个主键类;
            3,除了BLOB和主键的其他字段的类;
            4,包含BLOB的类;
            5,一个用户生成动态查询的条件类(selectByExample, deleteByExample),可选;
            6,Mapper接口(可选)

            tableName(必要):要生成对象的表名;
            注意:大小写敏感问题。正常情况下,MBG会自动的去识别数据库标识符的大小写敏感度,在一般情况下,MBG会
                根据设置的schema,catalog或tablename去查询数据表,按照下面的流程:
                1,如果schema,catalog或tablename中有空格,那么设置的是什么格式,就精确的使用指定的大小写格式去查询;
                2,否则,如果数据库的标识符使用大写的,那么MBG自动把表名变成大写再查找;
                3,否则,如果数据库的标识符使用小写的,那么MBG自动把表名变成小写再查找;
                4,否则,使用指定的大小写格式查询;
            另外的,如果在创建表的时候,使用的""把数据库对象规定大小写,就算数据库标识符是使用的大写,在这种情况下也会使用给定的大小写来创建表名;
            这个时候,请设置delimitIdentifiers="true"即可保留大小写格式;

            可选:
            1,schema:数据库的schema;
            2,catalog:数据库的catalog;
            3,alias:为数据表设置的别名,如果设置了alias,那么生成的所有的SELECT SQL语句中,列名会变成:alias_actualColumnName
            4,domainObjectName:生成的domain类的名字,如果不设置,直接使用表名作为domain类的名字;可以设置为somepck.domainName,那么会自动把domainName类再放到somepck包里面;
            5,enableInsert(默认true):指定是否生成insert语句;
            6,enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get);
            7,enableSelectByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询语句;
            8,enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update);
            9,enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete);
            10,enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句;
            11,enableCountByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询总条数语句(用于分页的总条数查询);
            12,enableUpdateByExample(默认true):MyBatis3Simple为false,指定是否生成动态修改语句(只修改对象中不为空的属性);
            13,modelType:参考context元素的defaultModelType,相当于覆盖;
            14,delimitIdentifiers:参考tableName的解释,注意,默认的delimitIdentifiers是双引号,如果类似MYSQL这样的数据库,使用的是`(反引号,那么还需要设置context的beginningDelimiter和endingDelimiter属性)
            15,delimitAllColumns:设置是否所有生成的SQL中的列名都使用标识符引起来。默认为false,delimitIdentifiers参考context的属性

            注意,table里面很多参数都是对javaModelGenerator,context等元素的默认属性的一个复写;
         -->
        <table tableName="user" domainObjectName="User" />
    </context>
</generatorConfiguration>

3.db.properties

datasource.driver=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
datasource.password=root
datasource.username=root

4.log4j.properties

log4j.rootLogger=info, A1 , R
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m -(:%L)%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=D:log	estsocket_log.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n  

5.springmvc.properties

view.prefix=/
view.suffix=.jsp

6.编写配置类

6.1 SpringConfig

package com.wolf.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;

@Configuration
//spring托管类所在的包路径
@ComponentScan({"com.wolf.service"})
//spring相关参数所在的资源文件(数据库信息文件)
@PropertySource("classpath:db.properties")
//代理mapper接口
@MapperScan("com.wolf.mapper")
public class SpringConfig{
    //数据源参数
    @Value("${datasource.driver}")
    private String driverClass;
    @Value("${datasource.url}")
    private String url;
    @Value("${datasource.username}")
    private String username;
    @Value("${datasource.password}")
    private String password;
    /**
     * spring注入数据源
     * @return
     */
    @Bean
    public DruidDataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    //sessionFactory
    @Bean("sessionFactory")
    public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource)throws Exception{
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //设置,mapper.xml映射路径(默认是和mapper接口在同一路径)
        GenericApplicationContext context = new GenericApplicationContext();
        Resource[] resources = context.getResources("classpath:mapper/*.xml");
        sessionFactory.setMapperLocations(resources);
        return sessionFactory;
    }
}

6.2SpringMMCConfig

package com.wolf.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@EnableWebMvc
@Configuration
@ComponentScan("com.wolf.controller")
@PropertySource("classpath:springmvc.properties")
public class SpringMVCConfig implements WebMvcConfigurer {
    @Value("${view.prefix}")
    private String prefix;
    @Value("${view.suffix}")
    private String suffix;
    @Bean
    public InternalResourceViewResolver getViewResolver(){
        return new InternalResourceViewResolver(prefix,suffix);
    }

    //配置静态资源可以被访问
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

6.3MyWebAppInitializer

package com.wolf.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * 配置容器初始化时需要加载的配置类
 */
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMVCConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

7.剩下的交给mybatis逆向生成

技术图片

 

以上是关于ssm整合的主要内容,如果未能解决你的问题,请参考以下文章

SSM框架整合

SSM 项目整合详细解读

SSM整合

520前,我放弃陪女朋友时间,被迫写代码:“SSM框架整合+excel文件上传到数据库+数据更新“

shiro整合SSM(spring_springmvc_mybatis)

ssm整合redis