maven版本:3.3.9 解壓便可使用html
spring版本:4.3.9 經過maven進行管理下載前端
mybatis版本:3.4.4 經過maven進行管理下載java
mysql版本:5.7 connector也是經過maven進行下載mysql
本工程的git地址:https://github.com/WQZ321123/springDemogit
首先,使用maven必定要網速好一點,否則在線下載jar包會很慢,其次,關於倉庫的問題,最好換成國內的阿里雲的倉庫,下載會更快。github
具體爲,修改maven的E:\Runtime\apache-maven-3.3.9\conf下的settings.xml文件:web
在 <mirrors>標籤內添加:spring
<mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> <mirror> <id>CN</id> <name>OSChina Central</name> <url>http://maven.oschina.net/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror>
而後再eclipse中直接在線安裝maven的插件,而後咱們新建一個maven工程,選擇:sql
以建立一個web工程。數據庫
而後在,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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.audi</groupId> <artifactId>testMavenSpring</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>testMavenSpring Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.9.RELEASE</version> <!-- <scope>runtime</scope> --> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.9.RELEASE</version> <!-- <scope>runtime</scope> --> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> </dependencies> <build> <finalName>testMavenSpring</finalName> <plugins> <!-- define the project compile level --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
保存之後,maven會自動開始下載jar包。
這裏遇到了一個問題:
所有的錯誤信息是:
Description Resource Path Location Type
Failure to transfer org.codehaus.plexus:plexus:pom:1.0.12 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.codehaus.plexus:plexus:pom:1.0.12 from/to central (https://repo.maven.apache.org/maven2): The operation was cancelled. pom.xml /testMavenSpring line 1 Maven Configuration Problem
解決方法以下:
在maven的本地倉庫中,好比個人路徑是C:\Users\Mike\.m2\repository下搜索last,
把這些文件所有刪除了,而後在eclipse中,項目右鍵——》maven更新一下項目,上述錯誤就解決了。
若是須要將web module改爲3.0版本的話,直接在項目右鍵——》properties——》project facets更改的話,可能會報錯。
報錯信息以下:
這個時候你須要更改下圖中選中的兩個文件(兩個文件都存在於當前工程路徑下):
將java的版本改成1.6以上,將 <installed facet="jst.web" version="2.3"/>改成3.0
同時,修改工程目錄下的web.xml,文件內容以下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="schedule-console" version="3.0"> </web-app>
這個時候,項目右鍵——》properties——》project facets中的dynamic web module應該自動變成3.0了,若是沒變就重啓一下eclipse就能夠了。
mysql的自動增加AUTO_INCREMENT,在咱們使用delete from table_name語句刪除了表中所有的數據之後,下一次在插入一條數據,那麼自增加依然會按照刪除以前自增加的值來增加,並不會回到默認值(而且,這個和使用哪一種存儲引擎是沒有關係的),解決的辦法就是直接使用truncate table table_name,這樣刪除數據自增加字段就能夠回到初始的值了。
關於存儲引擎的一片文章,http://www.cnblogs.com/gbyukg/archive/2011/11/09/2242271.html,寫的很好。
下面開始鏈接mysql
參考文章:http://blog.csdn.net/techbirds_bao/article/details/9233599/
使用mysql做爲數據庫,新建一個數據庫名爲mybatis,下面是建表語句:
#mysql註釋須要注意一點 在sql文件中最好使用#來進行註釋,由於使用-- 來註釋須要在它後面加上一個空格 不然運行sql文件會報錯 #建立表 Create TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(50) DEFAULT NULL, `userAge` int(11) DEFAULT NULL, `userAddress` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; #MySQL5.5之後默認使用InnoDB存儲引擎,提供事務安全表,其它存儲引擎都是非事務安全表。 ALTER TABLE `user` COMMENT '測試用戶表'; ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用戶id'; ALTER TABLE `user` MODIFY `userName` varchar(50) COMMENT '用戶';
eclipse中項目須要作的一些配置以下:
首先是一個映射文件User.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.audi.mybatis.UserMapper"> <select id="selectUserByID" parameterType="int" resultType="User"> select * from user where id = #{id} </select> <select id="selectUserAll" resultType="User"> select * from user </select> </mapper>
而後是鏈接數據庫須要作的一些配置Configuration.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> <typeAliases> <typeAlias alias="User" type="com.audi.mybatis.dto.User"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=UTC" /> <property name="username" value="root"/> <property name="password" value="yourcode"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/User.xml"/> </mappers> </configuration>
簡歷數據庫持久化對象DTO:
package com.audi.mybatis.dto; public class User { private int id; private String userName; private String userAge; private String userAddress; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserAge() { return userAge; } public void setUserAge(String userAge) { this.userAge = userAge; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", userAge=" + userAge + ", userAddress=" + userAddress + "]"; } }
下面是測試類,直接以java程序運行:
package com.audi.test; import java.io.Reader; import java.util.Iterator; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.audi.mybatis.dto.User; public class TestMybatis { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("config/Configuration.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } } public static SqlSessionFactory getSession() { return sqlSessionFactory; } public static void main(String[] args) { SqlSession session = sqlSessionFactory.openSession(); try { User user = (User) session.selectOne("com.audi.mybatis.UserMapper.selectUserByID", 3); System.out.println(user.getUserAddress()); System.out.println(user.getUserName()); List<User> list = session.selectList("com.audi.mybatis.UserMapper.selectUserAll"); Iterator<User> iterator= list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } finally { session.close(); } } }
如今運行程序應該就能夠得到數據庫保存的結果了,注意上面的語句可能會拋出空指針異常,這事由於數據庫裏沒有數據,查詢不到id爲1的用戶數據。
接下來咱們來進行spring集成,使用spring來管理一些bean,好比DataSource。以接口變成方式來訪問數據庫。
先看一下整個工程的目錄結構圖:
spring的一個配置文件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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!--本示例採用DBCP鏈接池,應預先把DBCP的jar包複製到工程的lib目錄下。 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC" /> <property name="username" value="root" /> <property name="password" value="yourcode" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--dataSource屬性指定要用到的鏈接池 --> <property name="dataSource" ref="dataSource" /> <!--configLocation屬性指定mybatis的核心配置文件 --> <property name="configLocation" value="config/Configuration.xml" /> </bean> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <!--sqlSessionFactory屬性指定要用到的SqlSessionFactory實例 --> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> <!--mapperInterface屬性指定映射器接口,用於實現此接口並生成映射器對象 --> <property name="mapperInterface" value="com.audi.mybatis.dao.IUserOperation" /> </bean> </beans>
Configuration.xml,這個是配置mybatis的一些屬性的,注意其中關於數據源都註釋了,這部分交給spring來管理了(注意下面配置文件的標籤的前後順序是不能夠變化的,詳情能夠參看那張截圖(來自 深刻淺出MyBatis技術原理與實戰)):
<?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> <typeAliases> <typeAlias alias="User" type="com.audi.mybatis.dto.User"/> </typeAliases> <!-- <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=UTC" /> <property name="username" value="root"/> <property name="password" value="w513723"/> </dataSource> </environment> </environments> --> <mappers> <mapper resource="mapper/User.xml"/> </mappers> </configuration>
映射文件User.xml:(注意其中的namespace和上面的user.xml文件不同了,這裏寫的是接口的地址)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.audi.mybatis.dao.IUserOperation"> <select id="selectUserByID" parameterType="int" resultType="User"> select * from user where id = #{id} </select> <select id="selectUserAll" resultType="User"> select * from user </select> </mapper>
接口超級簡單:IUserOperation.java
package com.audi.mybatis.dao; import com.audi.mybatis.dto.User; public interface IUserOperation { public User selectUserByID(int id); }
下面是測試代碼:
package com.audi.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.audi.mybatis.dao.IUserOperation; import com.audi.mybatis.dto.User; public class MybatisSprintTest { private static ApplicationContext ctx; static { // 使用ClassPathXmlApplicationContext來加載spring的配置文件 ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml"); } public static void main(String[] args) { IUserOperation mapper = (IUserOperation) ctx.getBean("userMapper"); // 測試id=1的用戶查詢,根據數據庫中的狀況,能夠改爲你本身的. System.out.println("獲得用戶id=3的用戶信息"); User user = mapper.selectUserByID(3); System.out.println(user); } }
測試結果:
我的以爲這種面向接口的變成方式其實很差,由於映射文件會和接口造成強關聯的關係,而且接口不寫實現類就直接調用,總感受怪怪的。
關於jsp頁面中文亂碼以及相關知識的解釋:http://www.cnblogs.com/chengkai/articles/2171848.html
個人解決方案是,將jsp使用記事本打開,先保存成ANSI格式,再保存成utf-8格式就能夠了。
今天遇到了java文件也存在亂碼的問題,解決方式和jsp亂碼解決的方式類似,而且將整個workspace改爲了utf-8編碼格式,可是這個時候發現使用mvn install命令,若是輸了中文就是亂碼。
亂碼以下:
解決辦法是在pom.xml文件的<project>標籤中加入:
<properties> <argLine>-Dfile.encoding=UTF-8</argLine> </properties>
而後再使用 mvn install就沒有亂碼了,效果以下。
對於不能注入的問題,考慮在applicationContext.xml文件中加入:
<!-- 配置掃描的包 --> <context:component-scan base-package="com.audi.*" /> <!-- 註冊HandlerMapper、HandlerAdapter兩個映射類 --> <mvc:annotation-driven />
接下來咱們引入日誌框架log4j。
其實log4j仍是很友好的,集成也比較簡單,只須要在web.xml文件中加入以下配置信息:
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>config/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener>
注意上面的listener是必須的,至少個人實踐是這樣的,沒有listener的話,日誌不會生效的。而後就是還須要一個日誌的格式配置文件log4j.properties文件。
log4j.rootLogger=INFO, stdout , R log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout #log4j.appender.stdout.layout.ConversionPattern=%d %p %t %c - %m%n log4j.appender.stdout.layout.ConversionPattern=[%d{MM/dd HH:mm:ss}] [%-5p] %c{1}: - %m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=d:/testMavenSpring.log log4j.appender.R.MaxFileSize=1024KB log4j.appender.R.MaxBackupIndex=10 log4j.appender.R.Encoding=utf-8 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=[%d{MM/dd HH:mm:ss}] [%-5p] %c{1}: - %m%n #log4j.appender.R.layout.ConversionPattern=%d %p %t %c - %m%n log4j.logger.org.springframework=DEBUG log4j.logger.org.mybatis=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 #必須加上下面這一句 不然sql語句不會打印出來 log4j.logger.com.audi=debug
如今整個工程的目錄結構以下:
實際運行日誌結果以下:
前端效果:
給mybatis配置事務支持
網上大部分都會說,在applicationContext中添加以下一些代碼:
<!-- 數據庫事務管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 使用註解來管理數據庫事務操做 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
而後說在service層上使用@Transactional註解就可使得事務生效了。
其實這樣不是很全面,事務可能不會生效。
主要的日誌信息以下:
[07/10 15:18:44] [DEBUG] SqlSessionUtils: - Creating a new SqlSession [07/10 15:18:44] [DEBUG] SqlSessionUtils: - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@46725c3] was not registered for synchronization because synchronization is not active [07/10 15:18:44] [DEBUG] DataSourceUtils: - Fetching JDBC Connection from DataSource [07/10 15:18:44] [DEBUG] SpringManagedTransaction: - JDBC Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC, UserName=root@localhost, MySQL Connector Java] will not be managed by Spring [07/10 15:18:44] [DEBUG] insertUser: - ==> Preparing: insert into user(id,userName,userAge,userAddress) VALUES(?,?,?,?) [07/10 15:18:44] [DEBUG] insertUser: - ==> Parameters: 17(Integer), 王全洲(String), 100(String), 深圳市福田區崗廈(String) [07/10 15:18:44] [DEBUG] insertUser: - <== Updates: 1 [07/10 15:18:44] [DEBUG] SqlSessionUtils: - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@46725c3] [07/10 15:18:44] [DEBUG] DataSourceUtils: - Returning JDBC Connection to DataSource [07/10 15:18:44] [DEBUG] SqlSessionUtils: - Creating a new SqlSession [07/10 15:18:44] [DEBUG] SqlSessionUtils: - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@291e6f56] was not registered for synchronization because synchronization is not active
標黃的部分大意就說spring沒有進行事務管理,沒有生效。
緣由是由於咱們在使用<context:component-scan配置註解的自動掃描的時候,屢次掃描了service包形成的。
解決的辦法就是在spring-mvc的xml配置文件中,只掃描加載controller 對應的包就能夠了,即springMVC-servlet.xml中使用:
<context:component-scan base-package="com.audi.mybatis.controller" />
applicationContext.xml中使用
<context:component-scan base-package="com.audi.mybatis" />
其實上面的兩個配置也體現了,spring和springMVC稍微的一點不一樣,兩者的配置都是應該要分開加載的。DAO和Service是屬於spring的,Controller是屬於SpringMVC的。
完整的源代碼:https://github.com/WQZ321123/springDemo
關於spring的上下文配置信息,springMVC的上下文配置信息,加載順序:
先加載spring的上下文的配置信息,再在家springMVC的上下文配置信息。具體的能夠參考http://blog.csdn.net/trigl/article/details/52073457
接下來,咱們給整個工程配置數據庫的batch操做,即多個sql語句一次性執行,這裏要說明的是咱們不是在xml文件的某個id內連續寫多個sql語句或者使用iterator關鍵字來拼裝sql語句。而是在一個事務內的語句,咱們一次性執行。
須要作的配置是將數據庫的鏈接url改成(後面的&allowMultiQueries=true就是新添加的):
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true
而後在mybatis的配置文件中加入(注意這個配置標籤是有位置要求的,具體順序能夠參照本博文上面的那張截圖):
<settings> <setting name="defaultExecutorType" value="BATCH" /> </settings>
而後,下面是不加batch操做的日誌打印數據:
[07/11 12:28:02] [DEBUG] DataSourceTransactionManager: - Creating new transaction with name [com.audi.mybatis.service.impl.UserServiceImpl.insertUser]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '',-java.lang.Exception Tue Jul 11 12:28:03 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. Tue Jul 11 12:28:03 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. [07/11 12:28:03] [DEBUG] DataSourceTransactionManager: - Acquired Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true, UserName=root@localhost, MySQL Connector Java] for JDBC transaction [07/11 12:28:03] [DEBUG] DataSourceTransactionManager: - Switching JDBC Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true, UserName=root@localhost, MySQL Connector Java] to manual commit [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Bound value [org.springframework.jdbc.datasource.ConnectionHolder@623561ab] for key [org.apache.commons.dbcp.BasicDataSource@616af965] to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Initializing transaction synchronization [07/11 12:28:03] [DEBUG] TransactionInterceptor: - Getting transaction for [com.audi.mybatis.service.impl.UserServiceImpl.insertUser] [07/11 12:28:03] [DEBUG] SqlSessionUtils: - Creating a new SqlSession [07/11 12:28:03] [DEBUG] SqlSessionUtils: - Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@63159810] [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Bound value [org.mybatis.spring.SqlSessionHolder@77acef79] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@6ccc4ab] to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@623561ab] for key [org.apache.commons.dbcp.BasicDataSource@616af965] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@623561ab] for key [org.apache.commons.dbcp.BasicDataSource@616af965] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] SpringManagedTransaction: - JDBC Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true, UserName=root@localhost, MySQL Connector Java] will be managed by Spring [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@623561ab] for key [org.apache.commons.dbcp.BasicDataSource@616af965] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] insertUser: - ==> Preparing: insert into user(id,userName,userAge,userAddress) VALUES(?,?,?,?) [07/11 12:28:03] [DEBUG] insertUser: - ==> Parameters: 16(Integer), 王全洲(String), 100(String), 深圳市福田區崗廈(String) [07/11 12:28:03] [DEBUG] insertUser: - <== Updates: 1 [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@77acef79] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@6ccc4ab] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@77acef79] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@6ccc4ab] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] SqlSessionUtils: - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@63159810] [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@77acef79] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@6ccc4ab] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] SqlSessionUtils: - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@63159810] from current transaction [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@623561ab] for key [org.apache.commons.dbcp.BasicDataSource@616af965] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] insertUser: - ==> Preparing: insert into user(id,userName,userAge,userAddress) VALUES(?,?,?,?) [07/11 12:28:03] [DEBUG] insertUser: - ==> Parameters: 17(Integer), 王全洲(String), 100(String), 深圳市福田區崗廈(String) [07/11 12:28:03] [DEBUG] insertUser: - <== Updates: 1 [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@77acef79] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@6ccc4ab] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@77acef79] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@6ccc4ab] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] SqlSessionUtils: - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@63159810] [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@77acef79] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@6ccc4ab] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] SqlSessionUtils: - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@63159810] from current transaction [07/11 12:28:03] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@623561ab] for key [org.apache.commons.dbcp.BasicDataSource@616af965] bound to thread [http-nio-8080-exec-3] [07/11 12:28:03] [DEBUG] insertUser: - ==> Preparing: insert into user(id,userName,userAge,userAddress) VALUES(?,?,?,?) [07/11 12:28:03] [DEBUG] insertUser: - ==> Parameters: 18(Integer), 王全洲(String), 100(String), 深圳市福田區崗廈(String) [07/11 12:28:03] [DEBUG] insertUser: - <== Updates: 1
能夠看到咱們雖然在一個事務內部,可是沒執行一次更新sql,就會執行一次。
接下來是,添加batch之後的日誌輸出:
[07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Creating new transaction with name [com.audi.mybatis.service.impl.UserServiceImpl.insertUser]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '',-java.lang.Exception Tue Jul 11 12:48:56 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. Tue Jul 11 12:48:56 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. [07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Acquired Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true, UserName=root@localhost, MySQL Connector Java] for JDBC transaction [07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Switching JDBC Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true, UserName=root@localhost, MySQL Connector Java] to manual commit [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Bound value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Initializing transaction synchronization [07/11 12:48:56] [DEBUG] TransactionInterceptor: - Getting transaction for [com.audi.mybatis.service.impl.UserServiceImpl.insertUser] [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Creating a new SqlSession [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Bound value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] SpringManagedTransaction: - JDBC Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true, UserName=root@localhost, MySQL Connector Java] will be managed by Spring [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] insertUser: - ==> Preparing: insert into user(id,userName,userAge,userAddress) VALUES(?,?,?,?) [07/11 12:48:56] [DEBUG] insertUser: - ==> Parameters: 16(Integer), 王全洲(String), 100(String), 深圳市福田區崗廈(String) [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] from current transaction [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] insertUser: - ==> Parameters: 17(Integer), 王全洲(String), 100(String), 深圳市福田區崗廈(String) [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] from current transaction [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] insertUser: - ==> Parameters: 18(Integer), 王全洲(String), 100(String), 深圳市福田區崗廈(String) [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] [07/11 12:48:56] [DEBUG] TransactionInterceptor: - Completing transaction for [com.audi.mybatis.service.impl.UserServiceImpl.insertUser] [07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Triggering beforeCommit synchronization [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Triggering beforeCompletion synchronization [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Removed value [org.mybatis.spring.SqlSessionHolder@2dafa469] for key [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3d89aecc] from thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] SqlSessionUtils: - Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@23f583c4] [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] bound to thread [http-nio-8080-exec-4] [07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Initiating transaction commit [07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Committing JDBC transaction on Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true, UserName=root@localhost, MySQL Connector Java] [07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Triggering afterCommit synchronization [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Clearing transaction synchronization [07/11 12:48:56] [DEBUG] DataSourceTransactionManager: - Triggering afterCompletion synchronization [07/11 12:48:56] [DEBUG] TransactionSynchronizationManager: - Removed value [org.springframework.jdbc.datasource.ConnectionHolder@4a1198e0] for key [org.apache.commons.dbcp.BasicDataSource@21d702b3] from thread [http-nio-8080-exec-4] [07/11 12:48:57] [DEBUG] DataSourceTransactionManager: - Releasing JDBC Connection [jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true, UserName=root@localhost, MySQL Connector Java] after transaction [07/11 12:48:57] [DEBUG] DataSourceUtils: - Returning JDBC Connection to DataSource
從上面的日誌咱們能夠看到,配置了batch之後,它不是一次執行一條,而是把每次循環的都看成參數,最後批量去數據庫提交。
項目靜態資源的訪問問題:
dispatchServlet的配置以下:
<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:spring-servlet.xml</param-value> 這裏能夠指定初始化servlet的xml文件的存放位置,多個配置文件使用逗號分開 </init-param> --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
上面的dispatchServlet配置會攔截全部的請求,包括靜態資源,這樣會致使靜態資源404,找不到。
網上的解決辦法都是大概的三種,我主要使用以下兩種方式:
<!-- 使用下面配置,告訴dispatchservlet不對靜態資源進行映射 --> <!-- 方法1 --> <!-- <mvc:default-servlet-handler/> --> <!-- 方法2 --> <mvc:resources mapping="/static/**" location="/static/" />
上面須要注意的static文件夾必須在webapp路徑下:
而後在.jsp頁面中有兩種方式引入靜態資源,一種是經過
<img src="${pageContext.request.contextPath}/static/image/testImg1.png" alt="brainMaster" />
一種是經過
<script src="<c:url value='/static/js/service/user_service.js' />"></script>
上面這種方式須要注意,要在jsp中加入以下代碼才行,以下代碼須要jstl1.2的jar包支持。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
spring的controller中返回string對象時,形以下面的形式
public ResponseEntity<String> deleteUserById(@PathVariable("id") int id)
前端會沒法解析,此時要麼在方法的produce屬性上聲明返回的是個字符串,要麼就使用
com.google.gson.Gson來完成字符串到json的轉換,參考https://stackoverflow.com/questions/18385361/return-json-for-responseentitystring
示例代碼以下:
@RequestMapping(value = "/deleteUserById/{id}", method = RequestMethod.DELETE,produces = Constant.TEXT_PLAIN) public ResponseEntity<String> deleteUserById(@PathVariable("id") int id) { UserDto user = userService.selectUserByID(id); if (user == null) { LOG.error("id爲:" + id + "的用戶數據不存在,沒法刪除"); return new ResponseEntity<>("id爲:" + id + "的用戶數據不存在,沒法刪除",HttpStatus.NO_CONTENT); } userService.deleteUserById(id); LOG.info("id爲:" + id + "的用戶數據刪除成功"); return new ResponseEntity<>("id爲:" + id + "的用戶數據刪除成功",HttpStatus.OK); // 像這樣將string轉成json也能夠,可是要注意此時方法的produce屬性也要相應的修改成json的 // return new ResponseEntity<>(GSON.toJson("用戶數據刪除成功"),HttpStatus.OK); }