SSM学习总结
SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。
学习思路
-单独使用Mybatis
-有mapper实现类
-无mapper实现类
-mapper接口扫描
-JDBC整合事务
-业务层调用
为方便记录,整个项目完成后所需要的所有Jar包
![](https://img.haomeiwen.com/i15119378/ec8784ba612622b3.png)
一、单独使用Mybatis
![](https://img.haomeiwen.com/i15119378/2cc4d6a4fe904441.png)
1、Dao下的CustomerMapper负责写接口实现方法。
2、Entity下的Customer作为对象类,所有属性与数据库保持一致
3、sqlMapConfig.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>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理,事务控制由mybatis-->
<transactionManager type="JDBC" />
<!-- 数据库连接池,由mybatis管理-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/ssm" />
<property name="username" value="root" />
<property name="password" value="123" />
</dataSource>
</environment>
</environments>
<!-- 加载 映射文件 -->
<mappers>
<mapper resource="CustomerMapper.xml"/>
</mappers>
</configuration>
4、CustomerMapper.xml文件,负责编写sql语句
<?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">
<!-- 该文件别写mybaits中的mapper接口里边的方法提供对应的sql语句 -->
<mapper namespace="Dao.CustomerMapper">
<!-- 添加客户 -->
<insert id="savaCustomer" parameterType="Entity.Customer">
INSERT INTO ssm.customer
(name,gender,tel,address)
VALUES(
#{name},
#{gender},
#{tel},
#{address}
)
</insert>
<delete id="deleteCustomer" parameterType="java.lang.String">
delete from ssm.customer where name=#{name}
</delete>
<update id="updateCustomerForname" parameterType="java.lang.String">
update ssm.customer set name=#{name},gender=#{gender},tel=#{tel},address=#{address} where name=#{name}
</update>
<select id="selectCustomerForId" parameterType="int" resultType="Entity.Customer">
select * from ssm.customer
</select>
</mapper>
5、log4j.properties日志输出(可不要)
log4j.rootLogger = debug,stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.err
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
log4j.appender = org.apache.log4j.DailyRollingFileAppender
log4j.appender.file =G:Javajar//Mybaits//logs/lzog.log
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
6、Test作为主函数测试,以下为核心代码
//1.创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
//加载sqlMapConfig.xml文件
InputStream in =Resources.getResourceAsStream("sqlMapConfig.xml");
//2.创建SqlSessionFactory
SqlSessionFactory factory =builder.build(in);
//3.打开Sqlsession
SqlSession session=factory.openSession();
//4.获取Mapper接口
CustomerMapper mapper = session.getMapper(CustomerMapper.class);
//5.实例化对象
Customer customer=new Customer();
customer.setName("黑马");
customer.setAddress("天上星河");
customer.setGender("男");
customer.setTel("111111111");
//6.调用方法
//添加
mapper.savaCustomer(customer);
//删除
//mapper.deleteCustomer("QQQ");
//更新
//mapper.updateCustomerForname(customer);
//查找
//List<Customer> selectCustomerForId = mapper.selectCustomerForId();
//7.提交事务
session.commit();
//System.out.println(selectCustomerForId.get(0).getName()+"\n");
//8.关闭session
session.close();
7、至此,MyBaties单独使用完毕
二、Spring-Mybatis有mapper实现类整合
![](https://img.haomeiwen.com/i15119378/369bbb0ce726c90b.png)
1、在Mybatis单独使用基础上有如上改变
2、删除了sqlMapConfig.xml文件,jdbc.properties常规操作,以下为applicationContext.xml;
注意!!!!:这里为Jar包下的类文件路径
![](https://img.haomeiwen.com/i15119378/cbdc982eb56c4dbf.png)
![](https://img.haomeiwen.com/i15119378/27923db180600a35.png)
<?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"
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/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 读取jdbc.properties配置 -->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!-- 创建DataSource数据源 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 最大连接数 -->
<property name="maxActive" value="10"></property>
<!-- 最大空闲数 -->
<property name="maxIdle" value="5"></property>
</bean>
<!-- 创建SQLSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 关联连接池 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 加载slq映射文件 -->
<property name="mapperLocations" value="classpath:CustomerMapper.xml"></property>
</bean>
<!-- 创建CustomerMapperImpl对象,注入SqlSessionFactory -->
<bean id="customerMapper" class="Impl.Impl">
<!-- 关联sqlSessionFactory -->
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
3、添加Dao接口的Impl实现类
package Impl;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import Dao.CustomerMapper;
import Entity.Customer;
public class Impl extends SqlSessionDaoSupport implements CustomerMapper{
//以下为一个保存用户的例子、当然还有删改查的操作
@Override
public void savaCustomer(Customer customer) {
// TODO Auto-generated method stub
SqlSession sqlSession = this.getSqlSession();
//参数一:方法名称 //参数二:保存类型
sqlSession.insert("savaCustomer", customer);
//不需要事务提交sqlSession.commit()
}
}
4、Test测试类核心代码如下:
因applicationContext.xml已经配置了SqlSessionFactory工厂,在Mybatis单独使用基础上有所改变
//1.加载Spring配置
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//2.获取对象
CustomerMapper customerMapper = (CustomerMapper) ac.getBean("customerMapper");
//3.实例化对象
Customer customer=new Customer("黑马","天空之城","男","111-111-111");
customerMapper.savaCustomer(customer);
5、至此,Spring-Mybatis有mapper实现类完毕。
三、Spring-Mybatis无mapper实现类整合
![](https://img.haomeiwen.com/i15119378/ac819a40bc499af8.png)
1、在Spring-Mybatis有mapper实现类基础上有如上改变,(删除了实现接口)
2、更改applicationContext.xml文件,更改如下,注意需要导入calss的类名的jar包
<!-- 创建CustomerMapperImpl对象,注入SqlSessionFactory -->
<!-- <bean id="customerMapper" class="Impl.Impl">
关联sqlSessionFactory
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean> -->
<!-- 配置Mapper接口 -->
<bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 关联Mapper接口 -->
<property name="mapperInterface" value="Dao.CustomerMapper"></property>
<!-- 关联SqlSessionFactory -->
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
3、其他不变,运行测试,至此,Spring-Mybatis无mapper实现类整合完毕
四、Spring-Mybatis接口扫描
![](https://img.haomeiwen.com/i15119378/66f6e9bc6ffa6a14.png)
1、目录结构与Spring-Mybatis无mapper实现类整合一致
2、更改applicationContext.xml文件,更改如下,注意需要导入calss的类名的jar包
<!-- 配置Mapper接口 -->
<!-- <bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
关联Mapper接口
<property name="mapperInterface" value="Dao.CustomerMapper"></property>
关联SqlSessionFactory
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean> -->
<!--
若使用扫描,mapper接口在spring容器中的id名称为类名 如CustomerMapper -> customerMapper
-->
<bean id="customerMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置Mapper接口所在包路径,自动扫描Dao包下的接口 -->
<property name="basePackage" value="Dao"></property>
</bean>
3、其他不变,运行测试,至此,Spring-Mybatis接口扫描整合完毕
五、Spring-Mybatis JDBC事务整合
![](https://img.haomeiwen.com/i15119378/941a7a69c8f99aac.png)
1、Spring-Mybatis接口扫描整合的基础上作如上更改,把之前的包放入了一个父包,请记得要更改applicationContext.xml的路径
2、添加了一个Service接口和ServiceImpl接口实现类
接口如下
import cn.wsx.MS.Entity.Customer;
public interface CustomerService {
public void savaCustomer(Customer customer);
}
实现类:注意这里有一个int i=100/0;正常运行会抛出异常;两条插入语句;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.wsx.MS.Dao.CustomerMapper;
import cn.wsx.MS.Entity.Customer;
import cn.wsx.MS.Service.CustomerService;
@Service
public class CustomerServiceImpl implements CustomerService{
//注入Mapper对象
@Resource
private CustomerMapper customerMapper;
@Override
public void savaCustomer(Customer customer) {
// TODO Auto-generated method stub
customerMapper.savaCustomer(customer);
//模拟异常
int i=100/0;
customerMapper.savaCustomer(customer);
}
}
3、测试类代码如下、运行测试代码,会发现抛出算术异常,就是int i=100/0;抛出的,查看数据库,发现有一条插入了,因此第四步应该添加JDBC事务整合
//1.加载Spring配置
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//2.实例化CustomerService CustomerService->customerService getBean(customerService )
CustomerService service = (CustomerService) ac.getBean("customerService");
//3.插入
Customer customer=new Customer("黑马","天空之城","男","111-111-111");
service.savaCustomer(customer);
4、更改applicationContext.xml,添加代码如下:
<!-- 开启Spring的IOC注解扫描 -->
<context:component-scan base-package="cn.wsx.MS"></context:component-scan>
<!-- 开启事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启用Spring事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
5、更改ServiceImpl实现类如下,其实是添加了注解Service和Transactional
package cn.wsx.MS.ServiceImpl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.wsx.MS.Dao.CustomerMapper;
import cn.wsx.MS.Entity.Customer;
import cn.wsx.MS.Service.CustomerService;
@Service("customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService{
//注入Mapper对象
@Resource
private CustomerMapper customerMapper;
@Override
public void savaCustomer(Customer customer) {
// TODO Auto-generated method stub
customerMapper.savaCustomer(customer);
//模拟异常
int i=100/0;
customerMapper.savaCustomer(customer);
}
}
6、再次运行Test,发现数据库不会插入,在接口类取消模拟异常,运行发现插入两条数据。
六、SpringMVC基本整合
![](https://img.haomeiwen.com/i15119378/a3e9836d4285eb10.png)
1、项目结构如上,网址访问,所以不需要Test类了
2、添加index.jsp作为首页,注意文件路径,Body中代码如下
<form action="${pageContext.request.contextPath}/customer/save" method="post">
客户姓名:<input type="text" name="name"><br/>
客户性别:<input type="radio" name="gender" value="男">男<br/>
客户性别:<input type="radio" name="gender" value="女">女<br/>
客户手机:<input type="text" name="tel"><br/>
客户地址:<input type="text" name="address"><br/>
<input type="submit" value="提交">
</form>
再新建success.jsp和error.jsp作为成功失败后返回的界面。
3、新建Controller类代码如下
package cn.wsx.MS.Controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.wsx.MS.Entity.Customer;
import cn.wsx.MS.Service.CustomerService;
@Controller
@RequestMapping("/customer")
public class CustomerController {
//注入业务对象
@Resource
private CustomerService customerService;
/**
* 进入首页 注意 访问这个网址http://localhost:8080/MySpringMVC-Use/customer/index
*/
@RequestMapping("/index")
public String index() {
return "index";
}
/**
* 保存客户 注意 访问这个网址http://localhost:8080/MySpringMVC-Use/customer/save
*/
@RequestMapping("/save")
public String save(Customer customer) {
customerService.savaCustomer(customer);
return "success";
}
}
4、编写Spring-mvc.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd">
<!-- 扫描Controller所在的包 -->
<context:component-scan base-package="cn.wsx.MS.Controller"></context:component-scan>
<!-- 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器:简化Controller类编写的视图路径 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 访问前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 访问后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
5、添加如下代码进Web.xml文件
<!-- 配置spring编码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 启动SpringMVC -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 启动spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 修改路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
6.访问测试:
这里注意几个问题
问题一:代码完全没错,报404错误,这时需要重新部署项目 > clean >重启服务 , 再不行可以新建html文件访问
![](https://img.haomeiwen.com/i15119378/bf4458fa104afef1.png)
![](https://img.haomeiwen.com/i15119378/e5080adcbfd7254e.png)
网友评论