Spring+Spring MVC+MyBatis+Mavencss
SSM整合的核心仍是Spring+MyBatis的整合,回顧一下MyBatis操做數據庫流程,咱們是使用一個SQLSessionFactory對象來得到SQLSession,以後再進行CRUD操做。html
如今,有了spring,咱們就把SQLSessionFactory經過spring進行裝載和管理。java
若是是想直接使用的話,請去SSM-Maven-Archetypemysql
<?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>com.wan</groupId> <artifactId>SSM-Template</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>SSM-Template Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--日誌--> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.9.release</version> </dependency> <!--AOP--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.9.release</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>RELEASE</version> </dependency> <!-- springmvc依賴的json庫(若是使用@responsebody註解返回json數據) --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!-- jstl 1.2.5 version libarary --> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-spec</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-impl</artifactId> <version>1.2.5</version> </dependency> <!-- oracle driver --> <dependency> <groupId>com.github.noraui</groupId> <artifactId>ojdbc8</artifactId> <version>12.2.0.1</version> </dependency> <!-- mybatis orm框架 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--阿里巴巴鏈接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!-- spring整合mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> <!--文件上傳--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- 日誌庫 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> <!-- apache libraries --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.5</version> </dependency> <!--MyBatis分頁插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <!--自動下載最新版本 --> <version>5.1.6</version> </dependency> </dependencies> <build> <finalName>SSM-Template</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
前三步主要是整合Spring+SpringMVC框架,能夠參考一下這篇Spring MVC框架,這裏不過多補充git
spring中,完美地整合了MyBatis,因此,能夠不須要MyBatis的配置的文件,若是須要的話,也能夠配置MyBatis的配置文件,以後引入便可github
主要流程爲:web
下面是個人spring配置,使用了阿里巴巴的鏈接池開源庫,以及MyBatis的分頁插件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:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd"> <!-- 1. 掃描Service 組件, Mapper 組件 @Service, @Repository 2. 配置數據源 3. 集合mybatis一些相關配置 4. 數據庫事務管理器 5. AOP事務,即經過AOP方式將數據庫事務切到指定的Service組件 --> <context:annotation-config /> <!-- 掃描dao類(service),能夠有多個包使用逗號分隔包名,以完成Bean建立和自動依賴注入的功能--> <!--<context:component-scan base-package="dao" />--> <!-- 引用屬性文件中的數據庫資源--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:db.properties"/> </bean> <!-- 聲明一個alibaba druid 數據源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本屬性 url、user、password --> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- <property name="driverClassName" value="${jdbc.driver}"></property> --> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置獲取鏈接等待超時的時間 --> <property name="maxWait" value="60000" /> <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x' FROM DUAL" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打開PSCache,而且指定每一個鏈接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置監控統計攔截的filters --> <property name="filters" value="stat,log4j" /> </bean> <!-- 聲明 mybatis SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 須要的話,能夠引入單獨的myBatis配置文件 --> <!--<property name="configLocation" value="classpath:mybatis-config.xml"/>--> <!--能夠在此處配置SQL映射文件,但其中不能有相同id的parameterMap, resultMap或sql等--> <property name="mapperLocations" value="classpath*:mapper/*.xml" /> <property name="typeAliasesPackage" value="model" /> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <!--使用下面的方式配置參數,一行配置一個 --> <value> <!-- 支持經過Mapper接口參數來傳遞分頁參數 helperDialect=oracle,mysql,mariadb,sqlite,hsqldb,postgresql,db2,sqlserver,informix,h2,sqlserver2012,derby --> helperDialect=oracle supportMethodsArguments=true rowBoundsWithCount=true offsetAsPageNum=true pageSizeZero=false reasonable=true </value> </property> </bean> </array> </property> </bean> <!-- Scan Mapper Files --> <!-- 這種方式也可掃描Mapper接口 --> <!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>--> <!-- scan for mappers and let them be autowired --> <mybatis:scan base-package="dao" /> <!--================事務相關控制===================--> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- AOP事務 Service: newAccount(){ DAO: 1. from 2. to 3. log } <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> propagation: 事務的傳播行爲 read-only:是不是隻讀事務,此事務內只能作查詢,不能作insert,update,delete操做 rollback-for: 當出現此類異常時,該事務回滾 // 必須開啓事務 UserService.insertUser(){ // otherService.findX() otherService.insertXxx(); // c) Requires_New: 新事務 } --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="new*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> <tx:method name="query*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!--aop配置--> <aop:config> </aop:config> </beans>
打開IDEA中的命令行窗口,輸入下面命令(得配置好maven的環境變量)sql
mvn archetype:create-from-project
出現build success就說明成功了數據庫
PS: 保留空白文件夾的解決方法
上述建立的項目有幾個是空白文件夾,可是安裝骨架以後,使用骨架建立maven項目的時候發現,空白文件夾被忽略了,找到了網上的兩個解決方法
這裏就講一下第二種方法,是在Stack Overflow找到的方法
執行mvn archetype:create-from-project
以後,修改target/generated-sources/archetype/src/main/resources/META-INF/maven archetype-metadata.xml
<fileSet encoding="UTF-8"> <directory>src/main/application/controller</directory> </fileSet>
下面是個人添加部分:
<fileSet filtered="true" encoding="UTF-8"> <directory>src/main/java</directory> <includes> <include>**/*.java</include> </includes> </fileSet> <fileSet encoding="UTF-8"> <directory>src/main/java/controller</directory> </fileSet> <fileSet encoding="UTF-8"> <directory>src/main/java/dao</directory> </fileSet> <fileSet encoding="UTF-8"> <directory>src/main/java/model</directory> </fileSet> <fileSet encoding="UTF-8"> <directory>src/main/resources/mapper</directory> </fileSet> <fileSet encoding="UTF-8"> <directory>src/main/webapp/css</directory> </fileSet> <fileSet encoding="UTF-8"> <directory>src/main/webapp/img</directory> </fileSet> <fileSet encoding="UTF-8"> <directory>src/main/webapp/js</directory> </fileSet> <fileSet encoding="UTF-8"> <directory>src/main/webapp/view</directory> </fileSet>
除此以外,還有幾個文件須要修改
target\generated-sources\archetype\src\main\resources\archetype-resources\src\main\resources
下面的spring和springmvc兩個配置文件
target\generated-sources\archetype\src\main\resources\archetype-resources\src\main\webapp
中的web.xml
裏面的xml版本莫名其妙變成了1.0-SNAPSHOT
,咱們所有改爲固定的1.0
命令行路徑進入到target\generated-sources\archetype
cd target\generated-sources\archetype
輸入安裝命令
mvn clean install
出現build success表示成功
打開target\generated-sources\archetype
目錄下的pom.xml
,記住下面的前三個座標信息
從新新建一個maven項目,以後,選擇添加一個archetype,輸入座標
以後就是能夠看到列表由咱們的自定義骨架了
像以前同樣,選擇咱們的自定義骨架,新建一個maven項目
根據本身的要求,進行配置的更改
首先是數據源的配置db.properties
spring-config.xml
72行 mapper的路徑(相對於resources目錄來講)
105行 dao類中的包,
<mybatis:scan base-package="dao" />
是會自動掃描Mapper所在的包,並生成一個id爲xx的bean(Dao對象),以後咱們就能夠經過spring容器得到這個對象,使用這個對象來進行CRUD操做
至關於下面的代碼
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
Mybatis中,咱們能夠按照約定,把接口類和mapper.xml文件對應起來,從而更爲簡單地實現CRUD操做
項目中,我有這樣的對應的接口類和mapper.xml文件
UserMapper中的namespace就是爲dao.UserDao,這裏namespace必定要對應上接口類UserDao
UserMapper.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"> <!-- namespace: 命名空間,用於標識每個Mapper XML文件中的語句,預防在不一樣的Mapper XML文件中存在相同的語句ID --> <mapper namespace="dao.UserDao"> <!-- resultType: 也稱爲自動映射,只有在表的列名與POJO類的屬性徹底一致時使用,會比較方便,全類名 --> <select id="select" resultType="model.Users"> select * from USERS </select> </mapper>
UserDao.java
package dao; import java.util.List; import model.Users; /** * @author StarsOne * @date Create in 2019/10/11 0011 20:22 * @description */ public interface UserDao { List<Users> select(); }
使用的話就經過這樣
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-config.xml"); //spring中自動裝載,第一個字母小寫,若是是EmployeeDao,則是就是employeeDao UserDao userMapper = (UserDao) context.getBean("userDao"); List<Users> users = userMapper.selectAll(); for (Users user : users) { System.out.println(user.toString()); }
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-config.xml"); AccountDao acountDao = (AccountDao) context.getBean("accountDao"); //查詢第一頁,每頁有兩條數據 PageHelper.startPage(1, 2); List<Account> accounts = acountDao.selectAll(); for (Account account : accounts) { System.out.println(account.toString()); }