使用的版本为:Struts 2.1.6 + Spring 2.5 + Hibernate 3.2
开发环境为:MyEclipse 7.1.1 + Jdk 1.6.0_13 + Tomcat 6.0.18 + MySQL 6.0.10 alpha
所用表:test.employee
id int(11) NO PRI | NULL auto_increment

name varchar(255) YES NULL

address varchar(255) YES NULL

phone varchar(255) YES NULL


这个实例主要是实现简单的CRUD方法。在搭建环境前,需要处理一个问题:因为Spring2.5 AOP Liberaries里的asm2.2.3.jar和Hiberate中的生成代理用的asm.jar冲突,我们需要删除asm2.2.3.jar,不然就会发生异常:java.lang.NoClassDefFoundError: org/objectweb/asm/CodeVisitor 。具体的删除方法(避免在Tomcat中的lib下删除了,然后又重新发布项目时此jar又重新发不到lib下):在MyEclipse中【Window】à【Preferences】à【MyEclipse Enterprise Workbench】à【Project Capabilities】à【Spring】在spring2.5 AOP Libraries中删除asm2.2.3.jar
在开发S2SH架构时,先整合Spring + Hibernate ,然后再整合Struts + Spring 完成S2SH架构的搭建。
一、Srping 与 Hibnernate 的整合
(1)添加Hibernate支持
在添加Hibernate支持之前,我们先在【MyEclipse DataBase Explorer】中设置数据库连接。所用的mysql/jdbc的jar包为mysql-connector-java-5.1.8-bin.jar。

注意:MySQL的URL为:jdbc:mysql://localhost:3306/test(我所根据学的视频案例是连接oracle的,根据视频中所学的时候,url没有添加数据库,在测试过程当中怎么样也找到实体,原因就是因为在url中没有添加数据库的选择。)
后面按照默认设置一直到【finish】即可。
(a)在导航中找到【MyEclipse】,然后选择【Add Hibernate Capbilities】

这里可以直接选择jar包拷贝到lib下面,也可以先不拷贝,到时候MyEclipse会自动拷贝到lib下。
(b)由于Hibernate要与Spring整合,所以在这一步无需再配置更详细的hibernate.cfg.xml

在这个按列中,我们使用JDBC Driver模式。
(c)不创建sessionFactory。然后【finish】



(2)添加Spring支持
(a)在导航中找到【MyEclipse】,然后选择【Add Spring Capbilities】
添加5个类库。

(b)生成applicationContext.xml,建议将其放在WEB-INF下面。

(c)创建sessionFactory。然后【finish】


(3)整合Spring和Hibernate
打开applicationContext,在当中增加DataSource和SessionFactory
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
|
先将原先自动生成的上述代码删除。

然后再Outline的导航中选择【New DataSource and SessionFactory】

后面要用到Mapping Resources,所以你可以在这里随便填一个值进去。

最后添加部分属性(添加了hibernate.show_sql)后形成代码如下:
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingDirectoryLocations">
<list>
<value>file:src</value>
</list>
</property>
</bean>
|
自此已经完成了Spring与Hibernate的整合。