double整合框架-spring+hibernate、spring+struts、spring+mybatis

本片文章主要介绍框架double整合的简介和使用、了解和熟悉了double整合,对于使用SSM、SSH等流行整合框架具有很重要的意义。本篇文章将带你一步步的完成double整合。

目录:

一:spring+hibernate

二:spring+struts

三:spring+mybatis

 

一:spring+hibernate

简介:spring+hibernate整合的思路就是不再使用hibernate的配置文件,而是通过spring注入的方式,连接数据库,配置hibernate。通过dao层继承hibernateTemplate这个类,这个类提供setSessionFactory方法,在spring中,给dao层注册一个bean,并注册一个bean,配置好hibernate需要的配置信息 ,并将这个bean注入到dao中的sessionFactory属性中。使用时获取该bean,因为dao继承了这个类,使用时可以直接通过dao调用save、get、update、dalete等方法完成操作数据库。

类似于工厂模式中的sessionFactory被创建 ,并被注入了hibernate的配置信息。

1. 创建实体类,hero

2. 配置实体类与数据库映射文件:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping package="pojo">
    <class name="Hero" table="hero">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" />
 
    </class>
     
</hibernate-mapping>

3. 创建spring的配置文件,applicationContext.xml文件,配置数据库、设置hibernate方言等、关联映射文件。并将这些信息注入到dao中的sessionFactory属性中。完成注入。内容如下:

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-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/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
      
    <bean name="dao" class="HeroDAO">
        <property name="sessionFactory" ref="sf" />
    </bean>
 
    <bean name="sf"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="ds" />
        <property name="mappingResources">
            <list>
                <value>pojo/Hero.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
                hibernate.show_sql=true
                hbm2ddl.auto=update
            </value>
        </property>
    </bean>   
         
    <bean name="ds"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>  
 
</beans>

4.编写测试类,完成spring+hibernate的搭配操作数据库 。在测试类中,读取spring的配置文件,获取dao这个bean,因为该bean继承了HibernateTemplate类,并被注入了sessionFactory属性。则该bean可以直接使用父类的方法,完成操作数据库。

 public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        HeroDAO dao = (HeroDAO) context.getBean("dao");
        Hero c = new Hero();
        c.setName("Heroyyy");        
        //增加
        dao.save(c);         
        //获取
        Hero c2 = dao.get(Hero.class, 1);         
        //修改
        c2.setName("Herozzz");
        dao.update(c2);         
        //删除
        dao.delete(c2);         
    }

至此,已经基本完成了spring与hibernate的整合。

5. 基本使用技巧:

因为spring+hibernate是使用HibernateTemplate来完成的,所以与hibernate的使用有所不同,这里是使用hibernateTemplate中的方法进行操作的。HibernateTemplate中的find方法,是Hql操作数据库的方法。

分页:

 public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        CategoryDAO dao = (CategoryDAO) context.getBean("dao");
         
        DetachedCriteria dc = DetachedCriteria.forClass(Hero.class);
        int start =5;//从多少开始查询
        int count =10;//每页显示数量
        List<Hero> cs= dao.findByCriteria(dc,start,count);
        System.out.println(cs);
    }

模糊查询:

        List<Hero> cs =dao.find("from Heroc where c.name like ?", "%c%");//HQL查询  
        for (Heroc : cs) {
            System.out.println(c.getName());
        }
  
        DetachedCriteria dc = DetachedCriteria.forClass(Hero.class);//Criteria查询
        dc.add(Restrictions.like("name", "%分类%"));
        cs =dao.findByCriteria(dc);  
        for (Heroc : cs) {
            System.out.println(c.getName());
        }

二:spring+struts整合

对于struts来说,我们最关注的是action的生命周期,spring+struts的整合思路就是struts的action交给你spring来管理。而spring配置的加载是通过web.xml中的监听器读取jar包,来加载该配置文件,注册好bean之后,在struts中声明它的对象工厂交给spring来管理。则该bean就可以用作struts的action来使用了。这里举例说明访问一个action,跳转后台方法,获取查询数据,返回jsp展示数据的过程,具体步骤如下:

1. 导入struts和spring以及spring+struts的jar包,在web.xml中设置struts的拦截器,和读取spring的监听器。配置文件如下:

<web-app>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>
 
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>       
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
   <!-- 该监听器负责tomcat启动时,扫描WEB-INF/lib目录下是否有 struts2-spring-plugin-2.2.3.1.jar!-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
     
</web-app>

2. 在WEB-INF下创建applicationContext.xml文件,创建struts需要的action-bean。指向类为Action业务逻辑类。

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-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/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
    <bean name="heroActionBean" class="action.HeroAction">
 
    </bean>
</beans>

3. 在src下创建struts的配置文件:struts.xml文件,设置action信息。

 <constant name="struts.objectFactory" value="spring"/>为声明struts的action创建交给spring来管理,指定objectFactory对象工厂的值为spring。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
  <constant name="struts.i18n.encoding" value="UTF-8"></constant>
   
  <constant name="struts.objectFactory" value="spring"/>
   
  <package name="basicstruts" extends="struts-default">  
        <action name="listHero" class="heroActionBean" method="list">
            <result name="list">list.jsp</result>
        </action>   
</package>
</struts>

4.HeroAction中提供list方法,并查询出heroList集合,return "list",并提供list.jsp文件,通过s标签或者c标签遍历循环出heroList集合,完成展示。

启动tomcat,访问localhost:8080/SS/listHero,整合完成。

三:spring+mybatis

spring+mybatis的整合就比较有意思了,而且也比较常见。整合思路是原本mybatis的配置文件所做的事情,通过spring来完成注入,并通过注入SqlsessionFactory的方式,加载mybatis的配置文件。并通过注入一些整合相关的属性值,完成double整合。主要整合方式有三种:

㈠注入映射器的方式:采用面对接口的方式,自动注册mapper中的bean;

㈡sqlsession的方式:

    ①使用SqlSession的实现类SqlSessionTemplate来完成配置;

    ②采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession完成配置;

下面进行分别介绍。

1. 注入映射器的方式,采用mapper接口注入:

此方式的思路就是,创建mapper接口类,在该类中创建与SQLID一致的方法名,并且SQL.xml中的namespace与该类的路径一致。

㈠配置过程:

①导入所需要的jar包,创建pojo实体类Hero,创建Hero.xml,创建HeroMapper接口并创建响应的方法。考虑到面对接口编程思维方式,还需要创建service接口和service实现类,实现类负责实现dao层接口也就是mapper的接口。这里为了方便,省去了service的使用,直接调用dao也就是mapper接口完成使用。

     <mapper namespace="mapper.HeroMapper">
        <insert id="add" parameterType="Hero" >
            insert into hero ( name ) values (#{name})   
        </insert>                            
        <select id="list" resultType="Hero">
            select * from   hero 
        </select>    
    </mapper>
public interface HeroMapper {
  
    public int add(Category category);      
        
    public List<Category> list();     
     
}

②在src下创建spring配置文件applicationContext.xml文件,在该配置文件中,给SqlSessionFactoryBean类注入dataSorece数据库配置、mybatis的配置(包括扫描哪些xml文件、xml中的别名、配置数据源、开启事务等等与mybatis相关的配置)。注册org.mybatis.spring.mapper.MapperScannerConfigurer类,告诉spring-mybatis需要扫描哪些mapper接口类,并自动注册为bean,并将扫描的xml文件根据namespace匹配注入到对应的mapper接口的方法中,相当于实现了mapper接口中的方法。因为有了这一步,所以在后面使用mapper接口时,通过@autowired自动获取该bean,可以直接调用方法,就可以调用SQL语句块操作数据库了。配置文件如下:

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
     
   <context:annotation-config /> //开启自动扫描包功能
     
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
        <property name="driverClassName"> 
            <value>com.mysql.jdbc.Driver</value> 
        </property> 
        <property name="url"> 
            <value>jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</value> 
     
        </property> 
        <property name="username"> 
            <value>root</value> 
        </property> 
        <property name="password"> 
            <value>root</value> 
        </property>  
   </bean>
     
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="typeAliasesPackage" value="pojo" />
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
 
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="mapper"/>
    </bean>
     
</beans>

注:虽然整合之后可以不需要mybatis的配置文件,但是一些细致的配置还是需要mybatis的配置文件来完成,在这里可以通过在sqlsessionFactoryBean这个类的注册时,可以通过configLocation属性添加mybatis的配置文件,通过读取该配置文件完成xml的映射和xml的别名等其他设置,在这里就可以免了。

 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
   		<property name="dataSource" ref="dataSource"/>
   		<!-- <property name="typeAliasesPackage" value="pojo" />
   		<property name="mapperLocations" value="classpath:mybatis/*.xml"/> -->
   		
   		<!-- 可以使用mybatis 的配置文件进行细节的配置,也可以代替这里的一些东西 -->
   		<property name="configLocation" value="classpath:mybatis-config.xml"/>  
   </bean>  
   

mybatis配置文件中:

<configuration>
	<typeAliases>
      <package name="pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="mybatis/Hero.xml"/>
    </mappers>
</configuration>

 

㈡测试类使用:

编写测试类:

@RunWith解释:代表运行测试环境,runwith是一个按照某个测试运行器进行运行测试的注解功能。也就是说,我们使用Junit中的test进行单元测试时,如果这个测试需要运行在某个环境中,例如本例需要运行在spring环境中,就需要用该注解加载这个环境。runwith中告诉程序测试运行环境是什么(本例中告诉程序我需要运行在spring的测试环境中),然后通过@ContextConfiguration来读取spring的配置文件,此时,spring环境被加载。

@Autowired:这是spring中的注解功能,该注解可以自动扫描spring中已经注册的bean,将该属性类型、属性名匹配spring中的bean,如果匹配到了,就把这个bean自动注入到这个属性中,就相当于做了getBean()操作。在改例中:heroMapper被它修饰,程序发现该属性是一个可以自动装配的bean,因为spring配置中通过自动扫描已经把mapper中的接口都注册成了bean,即HeroMapper接口类已经自动注册了heroMapper这个bean,并把xml文件注入到了改bean中。则找到了该bean,将这个bean自动装配到了这个属性中了。此时调用该属性中的方法即可调用SQL语句块。

自动装配过程中:spring会优先寻找属性名与beanID一致的完成匹配,如果名称不一致,则会去匹配同类型的bean,如果同类型的bean有多个,则自动注入失败,报错。——————这是我自己的猜测理解,没有理论依据的......

@test这是Junit提供的单元测试注解,可以不通过主线程main方法即可完成运行。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HeroAction {
    @Autowired
    private HeroMapper heroMapper;
 
    @Test
    public void testList() {
        List<Hero> cs=heroMapper.getList();
        for (Hero c : cs) {
            System.out.println(c.getName());
        }
    }     
}

在这个测试类中,加载spring环境,并且自动装配了heroMapper这个已经完成注入的bean到heroMapper属性中。通过调用该mapper中的方法调用SQL语句块,完成查询。

2. 采用sqlsession的实现类SqlSessionTemplate的配置方式:

此类方式的思路是:在使用映射器的配置基础上,抛弃掉MapperScannerConfigurer这个映射类扫描器。spring中添加自动扫描包,扫描的包为需要使用SqlSessionTemplate这个bean的包,然后注册一个bean:org.mybatis.spring.SqlSessionTemplate。将已经注入好的sqlsessionFactory这个bean作为构造方法的参数传递到该类中,用以实例化该对象。此时就完成了sqlsessionFactory的声明。就可以直接使用了。在使用时,这种配置方式一般是在dao层的实现类中,自动装配这个bean,然后操作数据库,也就是在dao实现层使用。当然,在业务逻辑层使用也可以,不会一般不会。

㈠配置方式:

在原有映射器的配置基础上,修改spring的配置文件如下:其他配置文件无需修改。

<beans   
   <context:annotation-config />   
   	<!-- 自动扫描类 ,配置第二种配置方式使用,是必须的 -->
  <!--  <context:component-scan base-package="dao" /> -->   
   								<!-- 配置数据源 -->
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   		<property name="driverClassName">
   			<value>com.mysql.jdbc.Driver</value>
   		</property>
   		<property name="url">
   			<value>jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</value>
   		</property>
   		<property name="username">
   			<value>root</value>
   		</property>
   		<property name="password">
   			<value>root</value>
   		</property>
   </bean>
   
   				<!-- 注册sqlsessionFactory -->
   <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
   		<property name="dataSource" ref="dataSource"/>
   		<!-- <property name="typeAliasesPackage" value="pojo" />
   		<property name="mapperLocations" value="classpath:mybatis/*.xml"/> -->
   		
   		<!-- 可以使用mybatis 的配置文件进行细节的配置,也可以代替这里的一些东西 -->
   		<property name="configLocation" value="classpath:mybatis-config.xml"/>  
   </bean>  

                   <!--映射器的配置方式,可以注释掉-->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
   		<property name="basePackage" value="mapper"/>
   		<property name="sqlSessionFactoryBeanName" value="sqlSession" />  
   </bean>

                    <!--sqlSessionTemplate的配置方式-->
   <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
   		<constructor-arg index="0" ref="sqlSession"></constructor-arg>
   </bean>
   
</beans>

㈡编写测试类,通过sqlSessionTemplate完成操作数据库。

在dao的实现类中,代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HeroDao {
	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;

	@Test
	public void list() {
		List<Hero> lh = sqlSessionTemplate.selectList("getList");
		for (Hero hero : lh) {
			System.out.println(hero.getName());
		}
	}
}

直接自动装配这个spring中的bean,然后使用该对象调用相应的方法,通过SQLID完成操作数据库。

3. 抽象类SqlSessionDaoSupport的配置方式(感觉类似于ibatis的使用):

该配置方式的思路是:spring配置文件中,抛弃上面MapperScannerConfigurer和SqlSessionTemplate的方式。保留sqlsessionFactory这个bean。在dao的实现类中,继承org.mybatis.spring.support.SqlSessionDaoSupport这个抽象类。并将sqlsessionFactory这个bean完成自动装配,通过父类的setSqlSessionFactory方法将该bean传入到父类中。然后通过调用父类的getSqlSession()获取一个sqlsession,通过该sqlsession完成操作数据库。

㈠配置文件:

该配置方式不需要额外的配置文件的修改。只要注入好了sqlsessionFactory即可。

㈡测试类:代码如下:

@Repository
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDaoSupport extends SqlSessionDaoSupport {	
	/**
	 * 通过autowired自动注入sqlsessionFactory这个对象,并将该对象放置在父类中,
	 */
	@Autowired
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		System.out.println("session:"+sqlSessionFactory);
		super.setSqlSessionFactory(sqlSessionFactory);
	}

	@Test
	public void getList() {
		List<Hero> lh = this.getSqlSession().selectList("getList");//调用父类的sqlsession对象
		for (Hero hero : lh) {
			System.out.println(hero.getName());
		}
	}
}

至此,完成了spring+mybatis的三种配置方式,目前用的最多的是映射器的使用,因为他更符合面对接口编程,而且管理起来也很方便。

4. spring 配置文件的子配置文件:

如果项目很大,并且有很多业务场景需要配置多个spring配置,创建多个springBean。如果所有的bean都在一个配置文件中的话,那管理起来很不方便。此时可以通过创建子spring配置文件来方便管理:

在spring总配置文件中添加:

 <import resource="spring/spring-*.xml"/>

意思是:加载src/spring/中所有spring-*的文件。我们在做项目时,可以把所有的spring配置文件放在spring这个文件夹下,命名方式为spring-xxxx.xml。并且在自配置文件中,可以共享总配置文件中的bean。

spring-hero.xml文件如下:创建了一个service的bean,类型是service的实现类,并在该类中的属性heroDao(需要有get/set方法)注入heroDao这个bean。使用时,可以直接通过装配heroService这个bean,来调用service实现类中的方法。此处的heroMapper为spring-mybatis自动注册的bean。

<?xml version="1.0" encoding="UTF-8"?>
<beans
   <bean id="heroService" class="com.wht.service.impl.HeroServiceImpl">
     	<property name="heroMapper" ref="heroMapper" />
     </bean>
</beans>

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值