ssm(spring + Springmvc + mybatis)框架整合 · 筆記
一、環境配置
材料準備:
- JDK1.8
- Maven
- Tomcat7
- Eclipse
- MySQL
1、下載完後的maven配置:
(1)配置本地倉庫 :開啟conf資料夾中的 settings.xml 將藍下滑線中的內容複製出來填寫自己的本地倉庫地址
<localRepository>目標位置( 例:D:\myProject\myRepository )</localRepository>
(2)配置阿里雲映象源 :在<mirrors></mirrors>
標籤裡面增加:
<!-- 阿里雲倉庫 --> <mirror> <id>alimaven</id> <mirrorOf>central</mirrorOf> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/repositories/central/</url> </mirror>
(3)配置建立工程時的 jdk依賴的版本 :在<profiles></profiles>
標籤中新增:
<profile> <id>jdk-1.8</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> </profile>
2、Eclipse配置:
(1)配置maven 配置你的settings.xml檔案位置,update 之後,確定就好了 (2)配置tomcat 然後會發現多了新建立的tomcat服務 選中,再點選旁邊的edit按鈕,選擇自己的tomcat位置,和jre版本
二、建立工程,導包
匯入的包有:
- spring-webmvc、spring jdbc、spring-aspects
- mybatis
- mybatis-spring
- c3p0、mysql-connector-java
- junit、servlet-api、jstl
pom.xml 內容
<dependencies> <!--springmvc--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- spring jdbc --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- spring面向切面 --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- mybatis --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <!-- mybatis 整合spring的適配包 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- 資料庫連線池、驅動 --> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> <!-- junit servlet-api jstl --> <!-- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
其餘要使用的包,在使用時再匯入
三、寫配置檔案
web.xml
<!-- 啟動spring的容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springMVC 的前端控制器 , 攔截所有的請求-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 字元編碼過濾器 一定要放在所有的過濾器前面-->
<filter>
<filter-name>CharacterEncodingFilter</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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceRseponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 使用rest風格的URL 將頁面請求的普通URL轉換成delete或者put請求 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
springMVC的配置:dispatcherServlet-servlet.xml
<!-- springMVC的配置檔案,包含網站的跳轉邏輯的控制 -->
<context:component-scan base-package="com.ssm" use-default-filters="false">
<!-- 只掃描控制器 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置檢視解析器,方便返回頁面內容 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 兩個標準配置 -->
<!-- 將springMVC不能處理的請求交給Tomcat處理 -->
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
引入了使用 aop 和 tx 功能,spring配置檔案頭:(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: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/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">
...
</beans>
(為什麼在Spring的配置裡,最好不要配置xsd檔案的版本號?) 可檢視這篇博文 點選這裡
spring配置檔案:aplicationContext.xml
<!-- 資料來源,事物控制等 -->
<context:property-placeholder location="classpath:dbconfig.properties" />
<bean id="PooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置和mybatis的整合 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定mybatis全域性配置檔案的位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="dataSource" ref="PooledDataSource"></property>
<!-- 指定mybatis的mapper檔案 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<!-- 配置掃描器,將mybatis介面的實現加入到IOC容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 掃描所有的dao介面的實現,加入到ioc容器中 -->
<property name="basePackage" value="com.ssm.crud.dao"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 控制資料來源 -->
<property name="dataSource" ref="PooledDataSource"></property>
</bean>
<!-- 使用xml配置形式的事物 -->
<aop:config>
<!-- 切入點表示式 -->
<aop:pointcut expression="execution(* com.ssm.crud.service..*(..))" id="txPoint"/>
<!-- 配置事物增強 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
<!-- 配置事物增強,事物如何切入 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- spring配置的核心:資料來源、與mybatis的整合、事物控制 -->
mybatis全域性配置: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="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.ssm.crud.bean"/>
</typeAliases>
</configuration>
四、Mybatis逆向工程
1、逆向工程配置和使用:
匯入逆向工程使用的 jar 包
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
逆向工程的配置檔案:mbg.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>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 是否生成註釋 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置資料庫 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false&"
userId="root"
password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定javabean生成的位置 -->
<javaModelGenerator
targetPackage="com.ssm.crud.bean" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 指定sql對映檔案生成的位置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="./src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 指定dao介面生成的位置,mapper介面 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.ssm.crud.dao" targetProject=".\src\main\java" />
<!-- 指定每個的生成策略 -->
<table tableName="tbl_emp" domainObjectName="Employee"></table>
<table tableName="tbl_dept" domainObjectName="Department"></table>
</context>
</generatorConfiguration>
使用 java程式碼+配置檔案的方式來跑逆向工程: MBGTest.java
package com.ssm.crud.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.exception.*;
import org.mybatis.generator.internal.*;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.config.xml.ConfigurationParser;
public class MBGTest {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback cellback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, cellback, warnings);
myBatisGenerator.generate(null);
}
}
(執行java程式碼,生成的檔案還需要修改以適應自己開發所需的業務邏輯)
注意:要重新生成程式碼一定要刪掉之前生成的,避免重複
逆向工程可能出現的問題:
1.資料庫版本8之後與之前所使用的密碼驗證不一樣 caching_sha2_password 和 sha256_password
使用新的資料庫連線驅動jar包,
老:driverClass="com.mysql.jdbc.Driver"
新:driverClass="com.mysql.cj.jdbc.Driver"
2.時間格式問題,就在jdbc連線的url後面加上引數
connectionURL="jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false&"
五、測試
後面有測試可能出現的問題和解決方法
1、測試插入
Department t1 = new Department();
t1.setDeptId(null);
t1.setDeptName("資訊部");
Department t2 = new Department();
t2.setDeptId(null);
t2.setDeptName("技術部");
departmentMapper.insertSelective(t1);
departmentMapper.insertSelective(t2);
//這裡插入兩條資料
2、測試批量操作
新增批量操作:applicationContext.xml 新增以下內容
<!-- 配置一個可以執行批量的sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>
java程式碼
//批量插入1000條資訊
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
for (int i = 0; i < 1000; i++) {
String name = UUID.randomUUID().toString().substring(0, 5) + i;
Employee e1 = new Employee();
e1.setdId(1);
e1.setEmail(name + "@tom.com");
e1.setEmpName(name);
e1.setGender("M");
mapper.insertSelective(e1);
}
測試成功
測試過程出現的問題:
1、找不到com.mchange.v2.c3p0.ComboPooledDataSource
更換高版本的 c3p0 解決問題
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
2、出現@RunWith(SpringJUnit4ClassRunner.class)
報錯問題
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
(SpringJUnit4ClassRunner.class 報錯解決)
並且
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
改為
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- <scope>test</scope> -->
</dependency>
(解決@RunWith報錯的問題)
3、failed to parse the connection string near';characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false'
出現這樣的問題是dbconfig.properties檔案裡使用了&
,將其改為&
。(&
和&
使用區別)
Url=jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
4、Public Key Retrieval is not allowed 錯誤:mysql連結新增
allowPublicKeyRetrieval=true