Java SSM整合学习总结

SSM学习总结

SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。

学习思路

-单独使用Mybatis
-有mapper实现类
-无mapper实现类
-mapper接口扫描
-JDBC整合事务
-业务层调用

为方便记录,整个项目完成后所需要的所有Jar包

image.png

一、单独使用Mybatis

image.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实现类整合

项目结构

1、在Mybatis单独使用基础上有如上改变
2、删除了sqlMapConfig.xml文件,jdbc.properties常规操作,以下为applicationContext.xml;
注意!!!!:这里为Jar包下的类文件路径


配置数据源的class属性为jar包下所需类位置的类名,id自定义

配置SqlSessionFactory同理
<?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实现类整合

image.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接口扫描

image.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事务整合

image.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基本整合

image.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文件访问


image.png

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 225,641评论 6 525
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 96,754评论 3 408
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 173,075评论 0 370
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 61,369评论 1 303
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 70,386评论 6 402
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,800评论 1 317
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,122评论 3 431
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 41,130评论 0 281
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 47,689评论 1 327
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,693评论 3 348
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,804评论 1 356
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,399评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,128评论 3 341
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,528评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,705评论 1 278
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,409评论 3 383
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,878评论 2 368