Spring+SringMVC+Mybatis整合(idea版本,Maven管理項目)

前言:最近剛把SSM框架過了一遍,爲了防止忘記配置,特地記錄一下SSM整合的過程java

搭建環境以及版本介紹

本人採用的是idea2017,Maven3.6.1,Spring 5.1.6.RELEASE,Mybatis 3.5.0mysql

建立JavaWeb項目

建立後的目錄結構以下 git

SSM目錄結構

引入依賴

pom.xml文件以下,有點多,可是裏面的東西確實比較好用,推薦使用github

<?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>cn.kt</groupId>
    <artifactId>SSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <!--自動生成mapper.xml-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <!--框架版本信息-->
    <properties>
        <springVersion>5.1.6.RELEASE</springVersion>
        <mybatisVersion>3.5.0</mybatisVersion>
    </properties>

    <dependencies>
        <!--junit用於單元測試-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>
        <!--mysql數據庫驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <!--日誌log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!--緩存ehcache-->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.6.11</version>
        </dependency>

        <!--分頁插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.10</version>
        </dependency>

        <!--cglib用於動態代理-->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.12</version>
        </dependency>
        <!--mybatis-spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatisVersion}</version>
        </dependency>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.12</version>
        </dependency>
    </dependencies>

</project>
複製代碼

配置文件

這裏我使用mybatis-generator這個插件來生成*Mapper.xml文件,對於通常的CURD基本上是都包括了,強烈推薦web

generatorConfig.xml

<?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>
    <!--你的數據庫驅動位置-->
    <classPathEntry
            location="D:\Maven\localRepository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar"/>

    <context id="mysqlgenerator" targetRuntime="MyBatis3">
        <!--不生成註釋-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!-- 配置數據庫鏈接 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT"
                        userId="root"
                        password="你的密碼"/>

        <!-- 指定javaBean生成的位置 -->
        <javaModelGenerator targetPackage="cn.kt.domain" targetProject="src/main/java">
            <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
            <property name="enableSubPackages" value="true"/>
            <!-- 設置是否在getter方法中,對String類型字段調用trim()方法 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="cn.kt.mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 指定dao接口生成的位置,mapper接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="cn.kt.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- table表生成對應的DoaminObject -->
        <table tableName="student" domainObjectName="Student"/>
    </context>

</generatorConfiguration>

複製代碼

配置完成後 啓動插件:打開maven->Plugins->mybatis-generator,直接運行就能夠裏spring

applicationContext-mybatis.xml 直接將掃描mapper.xml的任務交給spring,便不在這裏配置 成功後生成四個文件

特別說明 StudentExample這個類是爲了實現QBC(query by criteria)查詢sql

db.properties 數據庫相關的屬性配置,記得在url後添加serverTimezone的設置

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&useSSL=false
name=root
password=你的密碼
maxActive=100
maxIdle=50
initialSize=20
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
複製代碼

applicationContext-mybatis.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>
    <settings>
        <!--這些都是可選項-->
        <!--啓用緩存,記得在Mapper.xml文件中啓用緩存-->
        <setting name="cacheEnabled" value="true"/>
        <!--啓用log4j-->
        <setting name="logImpl" value="LOG4J"/>
        <!--懶加載-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        <setting name="lazyLoadTriggerMethods" value="clone"/>
    </settings>
    <plugins>
        <!--分頁插件-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <property name="pageSizeZero" value="true"/>
        </plugin>
    </plugins>
</configuration>
複製代碼

applicationContext-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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <!--&lt;!&ndash;處理器映射器&ndash;&gt;
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    &lt;!&ndash;處理器適配器&ndash;&gt;
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>-->
    <!--等效於上面兩個-->
    <mvc:annotation-driven/>
    <!--視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前綴-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--後綴-->
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--須要掃描的包-->
    <context:component-scan base-package="cn.kt"/>

</beans>
複製代碼

applicationContext.xml spring主配置文件

<?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"
       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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--引入數據庫配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>

    <context:component-scan base-package="cn.kt"></context:component-scan>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${url}"/>
        <property name="username" value="${name}"/>
        <property name="password" value="${password}"/>
        <property name="driverClassName" value="${driver}"/>
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${initialSize}"/>
        <property name="minIdle" value="${maxIdle}"/>
        <property name="maxActive" value="${maxActive}"/>
        <!-- 配置獲取鏈接等待超時的時間 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/>
    </bean>
    <!--建立SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--鏈接池-->
        <property name="dataSource" ref="dataSource"/>
        <!--掃描Mapper.xml配置文件-->
        <property name="mapperLocations" value="classpath:cn/kt/mapper/*.xml"/>
        <!--mybatis相關配置-->
        <property name="configLocation" value="classpath:applicationContext-mybatis.xml"/>

    </bean>
    <bean id="session" factory-bean="sqlSessionFactory" factory-method="openSession" scope="prototype"/>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.kt.mapper"/>
    </bean>
    <!--spring管理事務-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
複製代碼

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>
    <!--解決post亂碼-->
    <filter>
        <filter-name>Encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--監聽器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <!--防止spring內存溢出監聽器-->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>
複製代碼

ehcacahe.xml 若是沒有在mybatis配置文件中啓用ehcache能夠不用配置

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <!-- 磁盤保存路徑 -->
    <diskStore path="F:/out/mybatis_cache"/>
    <defaultCache
            maxElementsInMemory="1"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>
複製代碼

log4j.properties,一樣若是沒有啓用也不用配置

### 設置###
log4j.rootLogger = ERROR ,stdout

log4j.logger.cn.kt.mapper=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

複製代碼

至此,SSM的配置文件就算寫完了
最後記得把maven引入的依賴倒入war包,否則運行起來會報ClassNotFound的bug數據庫

測試

編寫一個controller

@Controller
public class MyController {
    @Autowired
    private MyService myService;
    @RequestMapping("/test")
    public ModelAndView controller(){
        myService.service();
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("hello");
        return modelAndView;
    }
}
複製代碼

一個service

@Service
public class MyService {
    @Autowired
    StudentMapper studentMapper;

    public void service(){
        StudentExample studentExample=new StudentExample();
        StudentExample.Criteria criteria1 = studentExample.createCriteria();
        criteria1.andAgeBetween(1,10);
        List<Student> list=studentMapper.selectByExample(studentExample);
        System.out.println(list);
    }
}
複製代碼

在地址欄輸入相應的路徑, http://localhost:8080/項目名/test service層成功查詢到了數據,在控制檯輸出apache

瀏覽器也成功跳轉至相應的頁面瀏覽器

大功告成!!!
相關文章
相關標籤/搜索