FLEX4.6+SPEING3.0.5+HIBERNATE3.6集成

 工具准备:myeclipse8.6、flex4.6、SPEING3.0.5、HIBERNATE3.6;

      环境的搭建过程这里省略。

一、创建Flex web 工程。flex4.6与以前的版本不一样,当创建一个flex项目后,本flex项目就是一个web项目,可以直接部署到tomcat中;


修改输出文件夹为WebRoot,单击“应用”,然后切换到“Flex构建路径”,检查地址;



检查无误后确定。然后将项目部署到tomcat6.0,运行项目,这样一个新的项目就部署好。


二、集成SPRING3.0.5

第一步:修改flex.class.path路径

修改web配置,如下,修改前

<context-param>
		<param-name>flex.class.path</param-name>
		<param-value>/WEB-INF/flex/hotfixes,/WEB-INF/flex/jars</param-value>
</context-param>

修改后

<context-param>
	<param-name>flex.class.path</param-name>
	<param-value>/WEB-INF/lib</param-value>
</context-param>


第二步:集成SPRING3.0.5

下载spring包,Spring官网http://www.springsource.org,下载spring-framework-3.0.5.RELEASE.zip版本,解压后拷贝dist目录下的包到工程lib下。

第三步:让Spring来管理 MessageBroker

创建flex-application-config.xml,配置flex:message-broker,文件内容如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:flex="http://www.springframework.org/schema/flex"  
    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-2.5.xsd   
        http://www.springframework.org/schema/flex   
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">
	
    <flex:message-broker/> 
    
</beans>

修改web.xml配置文件MessageBroker Servlet;修改前

<!-- MessageBroker Servlet -->
	<servlet>
		<servlet-name>MessageBrokerServlet</servlet-name>
		<servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
		<init-param>
			<param-name>services.configuration.file</param-name>
			<param-value>/WEB-INF/flex/services-config.xml</param-value>
		</init-param>
		<init-param>
			<param-name>flex.write.path</param-name>
			<param-value>/WEB-INF/flex</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

修改后:

<!-- MessageBroker Servlet -->
    <servlet>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                         classpath:flex-application-config.xml,
				         classpath:resource/spring/**/application*.xml
		    </param-value>
       </init-param>
       <init-param>
			<param-name>flex.write.path</param-name>
			<param-value>/WEB-INF/flex</param-value>
		</init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

为保证工程正常启动还需要依赖如下jar包

org.springframework.flex-1.0.3.RELEASE.jar

aopalliance-1.0.0.jar

cglib-2.2.0.jar


第四步:集成HIBERNATE3.6

下载Hibernate3.6,hibernate官网http://www.hibernate.org,下载hibernate-distribution-3.6.4.Final-dist.zip,解压后将hibernate3.jar包和lib\required的必须依赖包,lib\jpa下的包拷贝到工程lib下。

 

在目录com.demo.common.dao下创建泛型DAO,只供测试,内容如下:

package com.demo.common.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

@SuppressWarnings("unchecked")
public class HibernateEntityDao<T>  extends HibernateDaoSupport {

	private Class<T> entityClass;
	
	public void setEntityClass(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	public List executeSQLRetMap(final String sql,final Object... values) {

		return (List)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) {
				Query query = session.createSQLQuery(sql);
				for (int i = 0; i < values.length; i++) {
					query.setParameter(i, values[i]);
				}
				return query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();
			}

		});
	}
}

在scr/resource/properties目录下创建数据库连接配置


内容如下dbconfig.properties

#DataBase Type, Oracle DataBase Set Value Oracle, SQLServer DataBase Set Value SQLServer, MySQL DataBase set Value MySQL
#dataBaseType=Oracle
dataBaseType=SQLServer
#SQLServer
jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;DatabaseName=test
jdbc.username=sa
jdbc.password=123
hibernate.dialect=com.demo.common.dao.SqlServerDialect

jdbc.initialPoolSize=5
#Output SQL statements to console,true:yes ,false:no
hibernate.show_sql=true
#Inquires the cache true:yes ,false:no
hibernate.cache.use_query_cache=true
hibernate.substitutions=true 1, false 0, yes 'Y', no 'N'
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.jdbc.batch_size=50

log4j. properties内容如下:

log4j.rootLogger=ERROR,fileout,stdout


log4j.logger.monitorLogger=ERROR,monitorAppender
log4j.additivity.monitorLogger=false

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d (%F:%L) %-5p %c - %m%n

log4j.appender.fileout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileout.File=D:/logs/wwfsgcjs_log.txt
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.ConversionPattern=%d [%t] (%F:%L) %-5p %c - %m%n

log4j.appender.monitorAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.monitorAppender.File=D:/logs/mt_wwfsgcjs_log.txt
log4j.appender.monitorAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.monitorAppender.layout.ConversionPattern=%m%n

log4j.appender.monitorAppender.DatePattern='.'yyyy-MM-dd-HH
log4j.appender.monitorAppender.BufferedIO=true

log4j.appender.monitorAppender.BufferSize=8192

在scr/resource/spring创建

applicationContext.xml及applicationContext-db.xml文件,内容如下

applicationContext.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:flex="http://www.springframework.org/schema/flex"  
    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-2.5.xsd   
        http://www.springframework.org/schema/flex   
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">
	
   <!-- org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean -->
	<!--<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
	</bean> -->
   <!-- 事务管理器,将委托给HibernateTransactionManager进行管理//-->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 事务处理的AOP配置 所有服务层bean声明都要继承此bean ,在proxy里没有定义target属性,所以一定要在bean里加上 abstract="true"  //-->
	<bean id="TransactionProxyTemplate" abstract="true"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager" ref="transactionManager" />
		<property name="transactionAttributes">
			<props>
				<!-- 为了保证服务层统一的事务处理。服务层接口,类的方法必须以下面的方法为开头  -->
				<!--spring 捕获到RuntimeException和其他一些异常时才会回滚,不是所有异常都会回滚,-Exception 设置 为任何异常都回滚  -->
				<prop key="user*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="insert*">
					PROPAGATION_REQUIRED,-Exception
				</prop>
				<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="up*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="mod*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="delete*">
					PROPAGATION_REQUIRED,-Exception
				</prop>
				<prop key="remove*">
					PROPAGATION_REQUIRED,-Exception
				</prop>
				<prop key="create*">
					PROPAGATION_REQUIRED,-Exception
				</prop>
				<prop key="execute*">
					PROPAGATION_REQUIRED,-Exception
				</prop>
				<prop key="do*">PROPAGATION_REQUIRED,-Exception</prop>
			</props>
		</property>
	</bean>
	
	<!-- 提供普java类获取spring上下文 通过上下文获取具体bean,调用其中的方法 -->
	<bean id="springApplicationContextUtil" class="com.demo.util.SpringApplicationContextUtil"></bean>
	
	<!-- 系统初始化的时候读取数据库配置文件配置的数据库类型 -->
	<bean class="com.demo.util.DBPropertiesUtil" lazy-init="false" init-method="init" />
	
	<!-- 基础DAO ,针对一些业务没有具体实体类,比如调用存储过程,但又要能使用泛型DAO的方法 -->
	<bean id="baseDAO" class="com.demo.common.dao.HibernateEntityDao">
		<property name="sessionFactory" ref="sessionFactory" />
		<property name="entityClass" value="java.lang.Object" />
	</bean>
		
	
</beans>

applicationContext-db.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <!-- To provide a placeholder, mainly for database configuration -->
	 <bean id="propertyConfigure" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
	     <property name="locations">
	        <list>
	        	<value>classpath:resource/properties/dbconfig.properties</value>
	        </list>
	     </property>
 	 </bean>
    <!--Database connection pool configuration -->
    <bean id="sysDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
      <property name="driverClass"><value>${jdbc.driverClassName}</value></property>
      <property name="jdbcUrl"><value>${jdbc.url}</value></property>
      <property name="user"><value>${jdbc.username}</value></property>
      <property name="password"><value>${jdbc.password}</value></property>
      <property name="initialPoolSize"><value>${jdbc.initialPoolSize}</value></property>
    </bean>
	
    <bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		
		<property name="dataSource">
			<ref bean="sysDataSource" />
		</property>
<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
                <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
			</props>
		</property>
		
		<!--<property name="mappingResources">
			<list>
			<value></value>
		   </list>
		</property>	-->
		
		 <!--  文件夹映射 -->
		 <property name="mappingDirectoryLocations">
		 	<list>
		 		<value>WEB-INF/classes/com/demo/</value>
		 	</list>
		 </property>
		
		<!-- 注解方式映射 -->
		 <property name="packagesToScan">
		 	<list>
		 	<value>com.demo.*</value>
		 	</list>
		</property>
   </bean>

下面是一些需要用到的类



SqlServerDialect.java

package com.demo.common.dao;

import java.sql.Types;

import org.hibernate.dialect.SQLServer2008Dialect;
import org.hibernate.type.DoubleType;
import org.hibernate.type.StringType;

public class SqlServerDialect extends SQLServer2008Dialect {
	
	 public SqlServerDialect() {
		super();
		registerHibernateType(Types.CHAR, StringType.INSTANCE.getName());
		registerHibernateType(Types.NVARCHAR, StringType.INSTANCE.getName());
		registerHibernateType(Types.LONGNVARCHAR, StringType.INSTANCE.getName());
		registerHibernateType(Types.DECIMAL, DoubleType.INSTANCE.getName());
		registerHibernateType(Types.NCHAR,StringType.INSTANCE.getName());
	}
}

DBPropertiesUtil.java

package com.demo.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
public final  class DBPropertiesUtil {
	
	private DBPropertiesUtil(){		
	}
	//数据库类型
	private static String dataBaseType;	
	/**
     * 初始化方法 bean 中配置
     * init-method="init" 
     */
    public void init() {
	   Properties prop = new Properties();
	   InputStream in = DBPropertiesUtil.class.getResourceAsStream("/resource/properties/dbconfig.properties");
	   try {
	       prop.load(in);
	       dataBaseType = StringUtils.trim(prop.getProperty("dataBaseType")); 
	   } catch (IOException e) {
	  	  System.out.println("读取 /resource/properties/dbconfig.properties 配置数据库类型错误!");
	      e.printStackTrace();
	   }
    }
	
	/**
	 * 获取dbconfig.properties文件中配置数据库类型
	 * @return
	 */
	public static String getDataBaseType() {
		if (StringUtils.isBlank(dataBaseType)) {
			dataBaseType = "ORACLE";
		}
		return dataBaseType;
	}	
}

下面,在com.demo.service.imp下新建一个实现类

在类中添加

private HibernateEntityDao<Object>baseDAO;

private HibernateEntityDao<Test>testDAO;



在弹出的对话框中选择两个setter,并生成类,最后生成的内容如下

package com.demo.service.imp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.demo.common.dao.HibernateEntityDao;
import com.demo.pojo.Test;
import com.demo.service.TestService;
public class TestServiceImp implements TestService {
	private HibernateEntityDao<Object> baseDAO;
	private HibernateEntityDao<Test> testDAO;
	public void setBaseDAO(HibernateEntityDao<Object> baseDAO) {
		this.baseDAO = baseDAO;
	}
	public void setTestDAO(HibernateEntityDao<Test> testDAO) {
		this.testDAO = testDAO;
	}
	
	@Override
	public String getStr() {
		return "HelloWorld!";
	}

	@SuppressWarnings("unchecked")
	public List getList(Map<String, String> o) throws Exception {
		String sql="select * from TEST";
		System.out.println(sql);
		List list =baseDAO.executeSQLRetMap(sql.toString());
		return list;
	}

}

在src/resource/spring/demo目录下创建配置文件

applicationContext-test.xml,内容如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:flex="http://www.springframework.org/schema/flex" 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-3.0.xsd   
        http://www.springframework.org/schema/flex   
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">

	<bean id="testt" parent="TransactionProxyTemplate">
		<flex:remoting-destination />
		<property name="target">
			<bean class="com.demo.test">
			</bean>
		</property>
	</bean>
	
	<bean id="te" parent="TransactionProxyTemplate">
		<flex:remoting-destination />
		<property name="target">
			<bean class="com.demo.service.imp.TestServiceImp">
			</bean>
		</property>
	</bean>
	
	<!--Service -->
	<bean id="testService" parent="TransactionProxyTemplate">
		<flex:remoting-destination/>
		<property name="target">
			<bean class="com.demo.service.imp.TestServiceImp">
				<property name="testDAO" ref="testDAO"/>
				<property name="baseDAO" ref="baseDAO"/>
			</bean>
		</property>
	</bean>
	
	<!--DAO -->
	<bean id="testDAO" class="com.demo.common.dao.HibernateEntityDao">
		<property name="sessionFactory" ref="sessionFactory"/>
		<property name="entityClass" value="com.demo.pojo.Test"/>
	</bean>
</beans>

 

接着,在flex_src/com/util目录下创建

Config.as,用作前后台交互

package com.util {
	import mx.messaging.config.ServerConfig;

	public class Config {
		private static var _path:String;

		public static function get path():String {
			if (Config._path) {
				return Config._path;
			} else {
				var point:String = ServerConfig.getChannel("my-amf", false).endpoint;
				var index:int = point.indexOf("/WebRoot/messagebroker/amf");
				point = point.substring(0, index);
				if(point.lastIndexOf("/") !=-1){
					return point;
				}
				return point + "/";
			}
		}
	}
}


ServiceProxy.as

package com.util {
	import flash.net.URLRequest;
	import flash.net.navigateToURL;

	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.rpc.AbstractOperation;
	import mx.rpc.AsyncResponder;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;


	public class ServiceProxy {
		public static function execute(destination:String, method:String, onResult:Function, ... params:Array):void {
			var service:RemoteObject = new RemoteObject(destination);
			service.showBusyCursor = true;
			service.endpoint = Config.path + '/syFrame/messagebroker/amf';
			Alert.show(Config.path);
			var asyncToken:AsyncToken;
			var operation:AbstractOperation = service.getOperation(method);
			if (params && params.length != 0) {
				asyncToken = operation.send.apply(operation, params);
			} else {
				asyncToken = operation.send();
			}
			asyncToken.addResponder(new AsyncResponder(function(event:ResultEvent, asyncToken:AsyncToken):void {
				onResult(event);
			}, function(event:FaultEvent, asyncToken:AsyncToken):void {
				var msg:String = event.fault.rootCause;
				if (msg && msg.hasOwnProperty('cause') && msg.cause) {
					msg = msg.cause.message;
				} else {
					msg = event.fault.faultString;
					msg = msg.replace('java.lang.Exception :', '');
				}
				Alert.show(msg, '警告', 0x4, null, function(event:CloseEvent):void {
					if (msg && msg.indexOf('请重新登录') != -1)
						navigateToURL((new URLRequest("javascript:location.reload()")), "_self");
				});
			}, asyncToken));
		}
	}
}

在flex应用程序中,添加测试代码,test.mxml内容如下

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import com.util.ServiceProxy;
			
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			import mx.rpc.events.ResultEvent;
			private function clickHandler():void{
				ServiceProxy.execute("testt","getTest",RE,txt.text);
			}
			private function RE(e:ResultEvent):void{
				txt.text=e.result.toString();
			}
			
			private function clickHandler2():void{
				var o:Object=new Object();
				o.STNM="n";
				ServiceProxy.execute("testService","getList",RE2,o);
			}
			private function RE2(e:ResultEvent):void{
				var list:ArrayCollection=e.result as ArrayCollection;
				Alert.show(list.length.toString());
			}
			
		]]>
	</fx:Script>
	<s:Button x="154" y="174" label="Button" click="clickHandler()"/>
	<s:TextInput id="txt" x="118" y="93"/>
	
	<s:Button x="279" y="174" label="查询数据库" click="clickHandler2()"/>
</s:Application>

第五步:实体生成

新建别一个项目,通过向导,添加hibernate



Myeclipse切换到数据库透视图,连接到需要生成实体的数据库







在弹出对话框中选择注解方式生成实体,如下


生成实体后,只保留name属性,如下图



以上是全部的步骤了,虽然顺序上不够严谨,但最后测试结果是可以的。












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值