SSM框架整合

SSM 框架整合

我已经开始学习SpringBoot 的内容了。但是还是要复习一下之前的内容。先补救一下SSM注解式开发与配置文件式的开发。

注解与配置文件的方式结合

一、Spring 和 Mybatis 的整合。

第一步:整合Dao层。Mybatis+spring整 合
	使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
第二层:管理service层。通过spring管理service接口
	使用配置方式 将serivce接口配置在spring配置文件中。
	实现事物控制。
第三步:整 合springMVC。
	由于springmvc是spring的子模块,所以不需要整合
1、整合思路
  1. 持久层的 mapper、dao 都需要由spring进行管理。
  2. 需要 spring 通过单例方式管理 sqlSessionFactory.
  3. Springmybatis 整合生成代理对象,使用sqlsessionFactory创建sqlsession.
2、整合环境
  • 创建一个新的 JAVA 工程。
  • Jar 包:
  1. Mybatis 的 Jar 包。
  2. Spring 的 Jar 包。
  3. Spring 和 Mybatis 的整合包。
  4. 数据库连接池的包。
  • 工程目录
    SM整合的工程目录
3、SqlSessionFactory
  • 在applicationContext.xml配置sqlSessionFactory和数据源。
  • sessionFactory在mybatis和spring的整合包下配置。
这里是 application.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.2.xsd  
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 数据源 使用dbcp连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}" />
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}" />
    </bean>
    
<!-- 第一步,创建SqlSessionFactory  ,这样创建的是单例的 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- 1.1 配置数据源 -->
	<property name="dataSource" ref="dataSource"></property>
	<!-- 1.2 指定mybatis的配置文件classpath: 可省略,不建议 -->
	<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" ></property>
	</bean>

还需要另外的配置文件。

// Mybatis 的配置文件 Sqlmapconfig.xml 
// Sqlmapconfig.xml 配置实体类别名与映射的xml文件。通用mapper与分页助手等Mybatis 的插件也配置在这个文件中。
<?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>
	<typeAliases>
	   <package name="cn.RebortChao.pojo"/>
	</typeAliases>
	<mappers>
		<mapper resource="sqlmap/User.xml"/>
		<package name="cn.RebortChao.mapper"/>
	</mappers>
</configuration>
4、原始Dao方式。
mapper.xml
<mapper namespace="test">
<!-- 在映射文件中配置很多的Sql语句 -->
<!-- 通过select执行数据库查询
id:标识映射文件中的sql,称 为statement的id
将Sql语句封装到mappedStatement对象中,所以将ID称为statement的id
parameterType 表示参数的类型,这里指定int
resultType表示输出结果的类型,select指定resultType表示将单条记录映射成的java对象。
#{}表示一个占位符号。
#{id}:其中的id表示接入输入的参数,参数名称就是ID,
              如果输入参数是简单类型 ,#{}中的参数名可以任意,可以value或其它。
 -->
<select id="findUserById" parameterType="int" resultType="cn.RebortChao.pojo.User">
	select * from user where id=#{id}
</select>
</mapper>
Dao层
userDao.java
public interface UserDao {
	//  根据ID查询用户信息
	public User findUserById()throws Exception;
}

编写 UserDaoImpl 实现类继承 SqlSessionDaoSupport 。

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
	@Override
	public User findUserById() throws Exception {
		//通过 工厂得到SqlSession
		SqlSession sqlSession=this.getSqlSession();
		//通过sqlSession操作数据库
		//第一个参数statementID (nameSpace+'.'+statementid   test.findUserById)
		//第二个参数指定和映射文件中所匹配的paramenterType类型的参数
		User user=sqlSession.selectOne("test.findUserById",1);
		return user;
	}
}
Dao接口实现类需要注入sqlSessionFactory,通过spring进行注入。
spring声明配置方法,配置dao的bean .完善 UserDao 中的注入内容。
<!-- 原始Dao接口 -->
<bean id="userDao" class="cn.RebortChao.dao.UserDaoImpl">
	<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
测试程序
public static void testFindUserById() throws Exception{
		//得到spring容器
		ApplicationContext  applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
		UserDao userDao= (UserDao) applicationContext.getBean("userDao");
		User user=userDao.findUserById();
		if(user!=null){
			System.out.println(user.getUserName());
		}else{
			System.out.println("没有找到用户!");
		}
	}
5、mapper 代理的方式
  • 项目构建目录发生变化
    mapper 代理的方式
UserMapper.java 是一个接口类,存放外部访问持久层的方法
UserMapper.xml 是一个编写Sql 的语句 ,里边存放访问数据库的sql。

**通过一种特殊的动态代理的方式,通过接口的名字直接返回namespace+id,执行使用的sql 语句。
**

配置文件需要修改
<!-- mapper扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
    <property name="basePackage" value="cn.com.systop.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>

二、SpringMVC 与 Mybatis 整合

这步完成,之后,整个SSM框架就等于整合完了。

所需要jar包:
  • 数据库驱动包:
  • Mybatis的jar包
  • Mybatis和spring的整合包
  • Log4j包
  • dbcp数据库连接池的包
  • Spring3.2所有jar包
  • Jstl包
检查 SqlMapConfig.xml 文件
主要进行setting 和 typeAliases 的配置。
<?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>
<!-- 全局setting配置 ,根据需要再加-->
<!-- 配置别名 -->
<typeAliases>
<!-- 批量扫描别名 -->
<package name="cn.com.systo.po"/>
</typeAliases>
<!--mapper配置
由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
必须遵循:mapper.xml和mapper.java文件同名且在一个目录 
  -->
</configuration>

除了上述改动之后,还需要配置很多内容
有些时候,我们将 application.xml 文件配置拆分为三个 application-dao.xml 配置 数据源、mapper扫描等配置,application-service.xml 配置扫描的@Service的内容、application-tran.xml 配置AOP切面编程、切面的内容。

// 1、Spring的数据源配置文件 applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:resource/*.properties" />
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <!-- 配置sqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置扫描包,加载mapper代理对象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xuebusi.xssm.mapper"></property>
    </bean>
</beans>
//  2、Spring的配置文件applicationContext-service.xml 扫描@Service注解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 扫描包加载Service实现类 -->
    <context:component-scan base-package="com.RobertChao.service"></context:component-scan>
</beans>
 // 3、Spring的事物配置 applicationContext-trans.xml
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 事务管理器,同样设置是单例的 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="create*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.RobertChao.service.*.*(..))"/>
    </aop:config>
</beans>
  • 上述的内容是 Spring 的配置文件,还需要配置SpringMVC 的内容。由前段控制器拦截请求,查找映射并执行方法。
// 配置 springmvc的配置文件 springmvc.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.RobertCHao.controller" />
    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 资源映射,配置的这些内容可以不被前段控制器拦截 -->
    <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
    <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
    
    <!-- 定义文件上传解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>
</beans> 

使用逆向工程生成 mapper 和 entity 的内容,然后加上Service 与Controller层。
**那么怎么判断整合成功了呢?**可以通过访问页面,通过页面上的按钮访问Controller层,前端控制拦截器拦截,然后通过Controller层的代码访问Service进行业务处理,处理dao 层传来的数据。这样就成功了。

三、需要注意几个配置。

web.xml 中的配置。
  • Spring 的上下文配置。
  • SpringMVC 的前端控制器。
springmvc.xml 中的配置。
  • 手动配置的处理请求映射器和适配器
<!-- 开启注解 -->
<context:annotation-config/> 
<!--注解配置映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<!--注解配置适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
  • 自动配置的注解配置映射器和适配器
<mvc:annotation-driven></mvc:annotation-driven>
	- 标签自动注册处理器映射器和适配器。
	- 还支持数据绑定支持,默认配置代替手动配置。
// 告知Spring,我们启用注解驱动。然后Spring会自动为我们注册上面说到的(开启注解,注解配置映射器和注解配置适配器)Bean到工厂中,来处理我们的请求。
1、添加上述内容的时候,Spring会自动加载
xmlns:mvc="http://www.springframework.org/schema/cache"
应该为
xmlns:mvc="http://www.springframework.org/schema/mvc"
  • 配置注解扫描
<context:component-scan/>标签是告诉Spring 来扫描指定包下的类,并注册被@Component,@Controller,@Service,@Repository等注解标记的组件。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值