1. 程式人生 > >maven中spring+springmvc+mybatis整合詳細配置

maven中spring+springmvc+mybatis整合詳細配置

首先配置mybatis,可以參考這篇部落格的前期基礎配置使用。

https://blog.csdn.net/qq_41520636/article/details/84146699

下面配置結構:

 需要的jar,在pom.xml中引入

  <!--統一jar包-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.vision>5.1.1.RELEASE</spring.vision>
        <shiro.version>1.2.3</shiro.version>
    </properties>
    <dependencies>
        <!--mybatis框架-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- JUnit單元測試工具 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <!-- 表示開發的時候引入,釋出的時候不會載入此包 -->
            <scope>test</scope>
        </dependency>
        <!--mysql連線池jar包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!--快取-->
        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!--列印日誌-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        <!--自動生成bean-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--toString與過載方法過濾-->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!--分頁-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.8</version>
        </dependency>
        <!--spring框架核心庫-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.vision}</version>
        </dependency>
        <!-- spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.vision}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.vision}</version>
        </dependency>
        <!--Spring java資料庫訪問包,在本例中主要用於提供資料來源 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.vision}</version>
        </dependency>
        <!--Spring Web-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.vision}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.vision}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.vision}</version>
        </dependency>
        <!--spring和mybatis整合-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- aspectjweaver 切面-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <!--最新版c3p0連線池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

下面是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: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
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--引入屬性檔案,在配置中佔位使用 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置C3P0資料來源-->
    <bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <!--連線資料庫的基本資訊-->
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="driverClass" value="${jdbc.driver}" />
        <!--連線池的相應配置-->
        <property name="maxPoolSize" value="${maxPoolSize}"></property>
        <property name="minPoolSize" value="${minPoolSize}"></property>
        <property name="initialPoolSize" value="${initialSize}"></property>
        <property name="acquireIncrement" value="${acquireIncrement}"></property>
        <property name="autoCommitOnClose" value="${autoCommitOnClose}"></property>
    </bean>

    <!--配置mybatis的工廠-->
    <bean id="sessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--資料來源-->
        <property name="dataSource" ref="ds"></property>
        <!-- 配置MyBaties全域性配置檔案:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!--類的別名的包-->
        <property name="typeAliasesPackage" value="org.lisonglin.entity"></property>
        <!-- 掃描sql配置檔案:mapper需要的xml檔案 -->
        <property name="mapperLocations" value="classpath:org/lisonglin/mapper/*.xml" />
    </bean>

    <!--spring和mybatis整合 (自動掃描對映介面)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定ioc容器中的mybatis工廠的bean的名字-->
        <property name="sqlSessionFactoryBeanName" value="sessionFactoryBean"></property>
        <!--mapper所在的包-->
        <property name="basePackage" value="org.lisonglin.mapper"></property>
    </bean>

    <!--宣告式事務管理-->
    <!--定義事物管理器,由spring管理事務 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="ds"></property>
    </bean>

    <!--支援註解驅動的事務管理,指定事務管理器 -->
    <!--事務屬性-->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" isolation="READ_COMMITTED" propagation="REQUIRED"/>
            <tx:method name="insert*" isolation="SERIALIZABLE" propagation="REQUIRED"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--配置事務(攔截service)-->
    <aop:config>
        <!--切入點表示式-->
        <aop:pointcut id="pc" expression="execution(* org.lisonglin.service.*.*(..))"></aop:pointcut>
        <!--關聯切入點表示式和事務屬性-->
        <aop:advisor advice-ref="advice" pointcut-ref="pc"></aop:advisor>
    </aop:config>

    <!--使事務註解起作用-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

    <!--只掃描controller的包以外的包-->
    <context:component-scan base-package="org.lisonglin">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
    </context:component-scan>

    <!--aspectj支援自動代理實現AOP功能-->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

    <!-- 攔截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="append*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="repair" propagation="REQUIRED" />
            <tx:method name="delAndRepair" propagation="REQUIRED" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
</beans>

 對應的jdbc.properties配置,如果出現以下錯誤

spring連線c3p0出現錯誤 Connections could not be acquired from the underlying database!

可以檢視這篇部落格解決方案

https://blog.csdn.net/qq_41520636/article/details/84344133

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/stus?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123
#最大連線數
maxPoolSize=100
#最小連線數
minPoolSize=20
# 關閉連線後不自動commit
autoCommitOnClose=false
# 獲取連線超時時間
checkoutTimeout=10000
# 初始化連線
initialSize=30
#driver default 指定由連線池所建立的連線的只讀(read-only)狀態。
#如果沒有設定該值,則“setReadOnly”方法將不被呼叫。(某些驅動並不支援只讀模式,如:Informix)
defaultReadOnly=
#driver default 指定由連線池所建立的連線的事務級別(TransactionIsolation)。
#可用值為下列之一:(詳情可見javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
#連線數
acquireIncrement=30

在然後是mybatis-config.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>
        <!--允許返回多個結果集-->
        <setting name="multipleResultSetsEnabled" value="true"></setting>
        <!-- 使用jdbc的getGeneratedKeys獲取資料庫自增主鍵值 -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 使用列別名替換列名 預設:true -->
        <setting name="useColumnLabel" value="true" />
        <!-- 開啟駝峰命名轉換:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
        <!--二級快取開關-->
        <setting name="cacheEnabled" value="true"></setting>
        <!--允許返回多個結果集-->
        <setting name="multipleResultSetsEnabled" value="true"></setting>
        <!--日誌-->
        <setting name="logImpl" value="LOG4J"></setting>
        <!-- 延遲載入總開關 -->
        <setting name="lazyLoadingEnabled" value="false"/>
        <!-- 侵入懶載入,設定為false則按需載入,否則會全部載入 -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!--設定一個時限,以決定讓驅動器等待資料庫迴應的多長時間為超時-->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>
    <!-- mybatis分頁外掛 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
</configuration>

接著是log4j.properties的配置

#---- global logging configuration
#---- level: FATAL,ERROR,WARN,INFO,DEBUG
#---- appender: console, file, mail
### set log levels ###
log4j.rootLogger = DEBUG,console

### 輸出到控制檯 ###
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern =  %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}:%L - %m%n

### 輸出到日誌檔案 ###
log4j.appender.file = org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File = ${webapp.root}/WEB-INF/logs/platform.log
log4j.appender.file.DatePattern=_yyyyMMdd'.log'
#log4j.appender.file.Append = true
#log4j.appender.file.Threshold = INFO
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}  [ %t\:%r ] - [ %p ]  %m%n

### 列印SQL ###
#log4j.logger.com.ibatis=DEBUG
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
#log4j.logger.java.sql.ResultSet=DEBUG

最後是spring-mvc.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"
       xmlns:p="http://www.springframework.org/schema/p"
       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 ">

    <!-- 自動掃描controller包下所有的類,成為spring mvc 的控制器-->
    <context:component-scan base-package="org.lisonglin" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

    <!--檢視解析器-->
    <!--定義JSP檔案的位置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
        <property name="order" value="0"></property>
    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
        <property name="prefix" value="/WEB-INF/html/" />
        <property name="order" value="10"></property>
        <property name="suffix" value=".html" />
    </bean>

    <!-- 檢視解析器:通用檢視名來解析檢視(Excel) -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="100"></property>
    </bean>

    <context:annotation-config/>

    <!-- 開啟註解( 用於將物件轉換為 JSON) -->
    <mvc:annotation-driven/>
    <!--處理靜態資源-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

    <!--
        配置靜態資源,直接對映到對應的資料夾,不被DispatcherServlet處理,3.04新增功能,需要重新設定spring-mvc-3.0.xsd
    -->
    <mvc:resources mapping="/img/**" location="/img/" />
    <mvc:resources mapping="/js/**" location="/js/" />
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/html/**" location="/WEB-INF/html/" />

    <!-- 定義檔案上傳解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  p:defaultEncoding="UTF-8">
        <!-- 設定檔案上傳的最大值為100MB,100*1024*1024 -->
        <property name="maxUploadSize">
            <value>104857600</value>
        </property>
        <property name="maxInMemorySize">
            <value>40960</value>
        </property>
    </bean>
</beans>