文章目录
一、环境准备
1.1、创建数据库和表
create database ssm;
use ssm;
create table t_account(
id int primary key auto_increment,
name varchar(30),
age int,
balance int
);
insert into t_account values(default,'HelloWorld',23,100);
1.2、导入框架依赖的jar包
由于我们整合的是SpringMVC、Spring和MyBatis,所以需要将这三个框架所需要的jar包导入到项目中。注意:由于要连接数据库,所以仍需要数据库驱动包。
注意:MyBatis框架和Spring框架整合需要一个mybatis-spring的jar包,该jar包的作用是两个框架的转换包。
<dependencies><!-- MyBatis框架核心jar包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.3</version></dependency><!-- MySQL数据库驱动包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><!-- 导入Spring的jar包--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.1.RELEASE</version></dependency><!-- 添加对AOP的支持 --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.4</version></dependency><!-- 事务的jar包 --><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.2.1.RELEASE</version></dependency><!-- 操作数据库的支持 --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.1.RELEASE</version></dependency><!--包含web应用开发时,用到spring框架时所需的核心类、文件上传以及工具类等--><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.2.1.RELEASE</version></dependency><!--与SpringMVC框架相关的jar包--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.1.RELEASE</version></dependency><!--与json相关的jar包--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.5</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.5</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.5</version></dependency><!--原生的servlet的jar包--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><!-- JSTL表达式 --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!--文件上传的jar包--><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><!-- log4j日志包 --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- spring的测试包--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.1.RELEASE</version><scope>test</scope></dependency><!-- 单元测试框架 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!-- MyBatis框架和Spring框架转换的转换包--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.3</version></dependency><!-- 阿里巴巴的数据源 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.21</version></dependency></dependencies>
1.3、修改Maven的编译版本
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties>
1.4、完善Maven目录
1.5、编写项目需要的包
cn.bdqn.domain
cn.bdqn.mapper
cn.bdqn.service
cn.bdqn.controller
cn.bdqn.utils
cn.bdqn.exception
1.6、编写实体、Mapper、Service
publicclassAccount{privateint id;privateString name;privateInteger age;privateInteger balance;// 生成get和set方法、toString方法}
publicinterfaceAccountMapper{// 查询所有的账号publicList<Account>selectAll();// 保存账号publicvoidinsert(Account account);}
publicinterfaceAccountService{// 查询所有账号publicList<Account>queryAll();// 保存账号publicvoidsave(Account account);}
publicclassAccountServiceImplimplementsAccountService{// 查询全部账号publicList<Account>queryAll(){System.out.println("查询全部账号");returnnull;}// 保存账号publicvoidsave(Account account){System.out.println("保存账号");}}
二、配置MyBatis环境
2.1、配置mybatis的主配置文件
主配置文件:mybaits-config.xml.
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><!-- mybatis的主配置文件 --><configuration><typeAliases><!-- 批量起别名 --><packagename="cn.bdqn.domain"/></typeAliases><!-- 配置环境 --><environmentsdefault="mysql"><!-- 配置mysql的环境--><environmentid="mysql"><!-- 配置事务的类型--><transactionManagertype="JDBC"></transactionManager><!-- 配置数据源(连接池) --><dataSourcetype="POOLED"><!-- 配置连接数据库的4个基本信息 --><propertyname="driver"value="com.mysql.jdbc.Driver"/><propertyname="url"value="jdbc:mysql:///ssm?allowMultiQueries=true"/><propertyname="username"value="root"/><propertyname="password"value="1234567"/></dataSource></environment></environments><mappers><packagename="cn.bdqn.mapper"/></mappers></configuration>
2.2、编写映射文件
在resources目录下新建与mapper接口同名的目录。即:cn/bdqn/mapper
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="cn.bdqn.mapper.AccountMapper"><!-- 查询全部账号信息--><selectid="selectAll"resultType="cn.bdqn.domain.Account">
select
id,name,age,balance
from
t_account
</select><!-- 新增账号 --><insertid="insert">
insert into t_account(name,age,balance) values (#{name},#{age},#{balance})
</insert></mapper>
2.3、测试环境是否正确
@TestpublicvoidtestMyBatis()throwsException{InputStream is =Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory ssf =newSqlSessionFactoryBuilder().build(is);SqlSession session = ssf.openSession();AccountMapper accountMapper = session.getMapper(AccountMapper.class);List<Account> accounts = accountMapper.selectAll();System.out.println(accounts);
is.close();
session.close();}
三、配置Spring环境
3.1、编写主配置文件
注意:由于是SSM项目整合,在Spring主配置文件中配置扫描包的时候仅仅针对Service业务层、Mapper持久化层等注解的扫描,对于Web层,交由SpringMVC框架去处理。
<beansxmlns="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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"><!-- 1、配置扫描包,排除Controller层的注解 --><context:component-scanbase-package="cn.bdqn"><context:exclude-filtertype="annotation"expression="org.springframework.stereotype.Controller"/></context:component-scan></beans>
3.2、测试Spring环境是否正确
@TestpublicvoidtestSpring()throwsException{ApplicationContext ac =newClassPathXmlApplicationContext("beans.xml");AccountService accountService =(AccountService) ac.getBean("accountService");System.out.println(accountService);}
四、Spring整合MyBaits框架
注意:我们在配置MyBaits环境的时候,数据源配置在了MyBatis上,现在由于Spring整合MyBaits,则对于在MyBatis中配置的数据源要交给Spring去管理。在这里,我们用的阿里巴巴的数据源。
官网
4.1、定义数据库配置
定义db.properties数据库配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm?allowMultiQueries=true
jdbc.username=root
jdbc.password=1234567
4.2、主配置文件中引入properties配置文件
<context:property-placeholderlocation="classpath:db.properties"/>
4.3、注册数据源
<beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"init-method="init"destroy-method="close"><propertyname="driverClassName"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></bean>
4.4、定义事务管理器
<beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><propertyname="dataSource"ref="dataSource"/></bean>
4.5、开启事务的注解驱动支持
<tx:annotation-driventransaction-manager="transactionManager"/>
4.6、配置SqlSessionFactoryBean
<!--作用:创建SqlSessionFactory工厂--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/></bean>
4.7、配置自动扫描所有 Mapper 接口和文件
<!-- 作用:能够扫描所有的Mapper接口的实现,让这些Mapper能够自动注入--><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><propertyname="basePackage"value="cn.bdqn.mapper"/></bean>
4.8、测试
@TestpublicvoidtestSpringAndMyBatis()throwsException{ApplicationContext ac =newClassPathXmlApplicationContext("beans.xml");AccountService accountService =(AccountService) ac.getBean("accountService");List<Account> accounts = accountService.queryAll();System.out.println(accounts);}
五、配置SpringMVC环境
5.1、主配置文件
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mv="http://www.springframework.org/schema/mvc"xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置扫描包 --><context:component-scanbase-package="cn.bdqn"use-default-filters="false"><context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- 配置视图解析器,作用是配置目录前缀和文件后缀,然后解析为一个资源文件 --><beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><propertyname="prefix"value="/WEB-INF/jsp/"/><propertyname="suffix"value=".jsp"/></bean><mvc:annotation-driven/></beans>
5.2、web.xml配置前端控制器
<?xml version="1.0" encoding="utf-8"?><web-appxmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0"><servlet><servlet-name>frontDispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:SpringMVC.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>frontDispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>
六、Spring集成SpringMVC环境
在web.xml文件中配置。
<!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 手动指定 spring 配置文件位置 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:beans.xml</param-value></context-param>
版权归原作者 陈橘又青 所有, 如有侵权,请联系我们删除。