Spring框架学习笔记(4)——SSM整合以及创建Maven自定义模版骨架
spring+spring mvc+mybatis+maven
ssm整合的核心还是spring+mybatis的整合,回顾一下mybatis操作数据库流程,我们是使用一个sqlsessionfactory对象来获得sqlsession,之后再进行crud操作。
现在,有了spring,我们就把sqlsessionfactory通过spring进行装载和管理。
如果是想直接使用的话,请去ssm-maven-archetype
步骤
1.创建maven项目
2.添加依赖
<?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>
3.整合springmvc
前三步主要是整合spring+springmvc框架,可以参考一下这篇spring mvc框架,这里不过多补充
4.整合spring和mybatis
spring中,完美地整合了mybatis,所以,可以不需要mybatis的配置的文件,如果需要的话,也可以配置mybatis的配置文件,之后引入即可
主要流程为:
- 创建一个db.properties,存放数据库url、账户和密码
- 创建datasource的bean对象(使用连接池,利用上面的db.properties)
- 创建mybatis的sqlsessionfactory的bean对象(使用上面的datasourcebean的bean对象)
- 配置自动装载mapper接口
下面是我的spring配置,使用了阿里巴巴的连接池开源库,以及mybatis的分页插件
<?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>
5.生成maven骨架
打开idea中的命令行窗口,输入下面命令(得配置好maven的环境变量)
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
6.安装并添加maven骨架
命令行路径进入到target\generated-sources\archetype
cd target\generated-sources\archetype
输入安装命令
mvn clean install
出现build success表示成功
打开target\generated-sources\archetype
目录下的pom.xml
,记住下面的前三个坐标信息
重新新建一个maven项目,之后,选择添加一个archetype,输入坐标
之后就是可以看到列表由我们的自定义骨架了
7.使用maven骨架
像之前一样,选择我们的自定义骨架,新建一个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使用
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()); }