当前位置:首页 > 开发 > 系统架构 > 架构 > 正文

Spring+MyBatis+Struts2整合

发表于: 2011-06-13   作者:citygu   来源:转载   浏览次数:
摘要: 框架环境: Spring 3.0.5 MyBatis 3.0.4(ibatis已正式更名为MyBatis) Struts2 MyBatis代码生成:mybatis-generator-core-1.3.1.jar 我是按照三个框架的整合步骤来做的。Spring+MyBatis+Struts2整合与传统的SSH框架不同的区别就在于把Spring和Hibernate的整合换成Spring+MyB
框架环境:
Spring 3.0.5 MyBatis 3.0.4(ibatis已正式更名为MyBatis) Struts2
MyBatis代码生成:mybatis-generator-core-1.3.1.jar
我是按照三个框架的整合步骤来做的。Spring+MyBatis+Struts2整合与传统的SSH框架不同的区别就在于把Spring和Hibernate的整合换成Spring+MyBatis。
代码层级的变动就是DAO层级以及实现的变更。
资料手册:MyBatis 3 User Guide Simplified Chinese.pdf(对照配置文件说明)
第一步:
新建Web工程,加入jar包。
第二部:
配置Web.xml 加入Struts2 和Spring Listener
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="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">
	<display-name>Web Application Tomcat 6 Servlet 3.0 JSP 2.2</display-name>
	<filter>
	<filter-name>struts2</filter-name>
	<filter-class>
		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  	</filter-class>
	<init-param>
		<param-name>config</param-name>
		<param-value>
			struts-default.xml,configs/struts/struts.xml
			</param-value>
	</init-param>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>

	<!-- 用于初始化Spring容器的Listener -->
	<listener>

		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param><!-- 配置spring配置文件的路径 -->
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:configs/spring/*-context.xml
		</param-value>
	</context-param>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	</web-app>


第三部:配置Spring配置文件
<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<!--配置数据源-->

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">

       <!-- 指定连接数据库的驱动 -->

       <property name="driverClass" value="com.mysql.jdbc.Driver"/>

       <!-- 指定连接数据库的URL -->

       <property name="jdbcUrl" value="jdbc:mysql://192.168.1.121/test?autoReconnect=true&amp;useUnicode=true&amp;createDatabaseIfNotExist=true&amp;characterEncoding=utf-8"/>

       <!-- 指定连接数据库的用户名 -->

       <property name="user" value="root"/>

       <!-- 指定连接数据库的密码 -->

       <property name="password" value="root"/>

       <!-- 指定连接数据库连接池的最大连接数 -->

       <property name="maxPoolSize" value="20"/>

       <!-- 指定连接数据库连接池的最小连接数 -->

       <property name="minPoolSize" value="1"/>

       <!-- 指定连接数据库连接池的初始化连接数 -->

       <property name="initialPoolSize" value="1"/>

       <!-- 指定连接数据库连接池的连接的最大空闲时间 -->

       <property name="maxIdleTime" value="20"/>

    </bean>

 	
	<!-- TransactionManager -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property></bean>
<!--MyBatis的会话工厂 注意配置文件路径-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:configs/mybatis-config.xml"></property>
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!--Mapper由Spring统一管理-->
	<bean id="StudentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
		<property name="mapperInterface" value="dao.StudentMapper"></property>
	</bean>
	<bean id="T1Mapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
		<property name="mapperInterface" value="mapper.T1Mapper"></property>
	</bean>

	<bean id="StudentService" class="service.StudentServiceImpl">
		<property name="studentMapper" ref="StudentMapper"></property>
	</bean>
	<!-- 事务拦截器 代理--> 	
	<bean id="baseTransactionProxy"
		class="org.springframework.transaction.interceptor.TransactionInterceptor">
		<property name="transactionManager">
			<ref bean="transactionManager" />
		</property>
		<!--    下面定义事务传播属性--> 
		<property name="transactionAttributes">
			<props>
				<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="add*">PROPAGATION_REQUIRED</prop>
				<prop key="modify*">PROPAGATION_REQUIRED</prop>
				<prop key="remove*">PROPAGATION_REQUIRED</prop>
				<prop key="do*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>

 <!-- 事务实例动态代理 --> 
	<bean id="autoProxyCreator"
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="interceptorNames">
			<list>
				<value>baseTransactionProxy</value>
			</list>
		</property>
		<property name="beanNames">
			<value>*Service</value>
		</property>
	</bean>
	
</beans>

第四步:配置MyBatis配置文件
mybatis-config.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>
<properties resource="configs/database/jdbc.properties">
</properties>
<settings>
<setting name="lazyLoadingEnabled" value="false" />
</settings>
<!--配置与数据库的链接 参数定义在jdbc.properties中 跟Spring整合 这段可以省略-->
	<environments default="development">

		<environment id="development">

			<transactionManager type="JDBC" />

			<dataSource type="POOLED">

				<property name="driver" value="${driverClassName}" />

				<property name="url" value="${url}" />

				<property name="username" value="${username}" />

				<property name="password" value="${password}" />

			</dataSource>

		</environment>
</environments> 
<mappers>
<mapper resource="model/T1-sqlMapper.xml"/>
<mapper resource="mapper/StudentMapper.xml"/>
</mappers>
</configuration>


第五步:学习如何用MyBatis代码生成器
新建mybatis-generator.xml放在src目录下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <classPathEntry location="D:\lib\mysql-connector-java-5.0.8-bin.jar" />

    <context id="DB2Tables" targetRuntime="MyBatis3">

        <commentGenerator>
            <property name="suppressDate" value="true" />
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://192.168.1.121:3306/test?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;zeroDateTimeBehavior=convertToNull" userId="root" password="root">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="model"
            targetProject="D:\workspace\SSI\src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"
            targetProject="D:\workspace\SSI\src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER"
            targetPackage="dao" targetProject="D:\workspace\SSI\src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table tableName="push_info" domainObjectName="PushInfo">
        </table>
 		<table tableName="stu" domainObjectName="Student">
        </table>
    </context>
</generatorConfiguration>




通过java类的方式直接执行MyBatis代码生成

public class MyBatisGeneratorTest {
	public static void main(String[] args) throws Exception {
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		File configFile = new File("src\\configs\\mybatis-generator.xml");
		System.out.println(configFile.getAbsolutePath());
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
				callback, warnings);
		myBatisGenerator.generate(null);

	}
}

Spring+MyBatis+Struts2整合

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
ssh三大框架简单整合,struts2整合JasperReport报表,解决HTML显示图片不出来,PDF中文不显示的问题
在上篇文章:SharePoint【整合Crystal Report水晶报表】-- 01. 如何在Sharepoint2010网站中整合Crys
上次成功升级了最土商业版,接下来就是整合公司的社区网站,先说明一下我现在工作的地方是个地方社
很多机器都用tomcat跟IIS部署不同网站、最近买了阿里云的服务器、于是也想玩一下、网上百度了很多方
1、Spring整合Struts2 <img src="ht
.NET快速开发整合框架(RDIFramework.NET) 4.2 平台自动升级模块 .NET快速开发整合框架(RDIFramew
Struts2.3.14+Spring3.2.0+Hibernate3.6整合说明文档 对于Struts2+Spring3+hibernate3.6的整合,都
转载请注明:来自http://changong.iteye.com/作者:张燕广 该篇主要编写整合Struts1.3.8的配置代码。S
.NET快速开发整合框架 (RDIFramework.NET) 【开发实例】之产品管理(WinForm) <div styl
.NET快速开发整合框架 (RDIFramework.NET) 【开发实例】之产品管理(WinForm) <strong style=
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号