Struts2 + Spring + Hibernate的集成
我們以綜合示例為例子來一步步的完成我們框架的集成
首先建一個web工程, 并將包建好
包名詳解:
com.wdpc.ssh.action: 放置Struts2的Action
com.wdpc.ssh.commons: 放置公用組件,工具類
com.wdpc.ssh.dao: 放置dao層的接口
com.wdpc.ssh.dao.impl: 放置dao層的實現類
com.wdpc.ssh.model: 放置實體對象的模型
com.wdpc.ssh.service: 放置業務層的接口
com.wdpc.ssh. service.impl: 放置業務層的實現類
com.wdpc.ssh.test: 放置單元測試類
首先集成Spring + Hibernate
第一步:導入Hiberante的包
注意我這里的Hibernate包中已經帶有c3p0連接池,mysql的驅動包,以及sqljdbc4的包(SQLServer, mysql的驅動包只需要保留一個就可以了, 用什么數據庫就保留對應的驅動包.)
將Hibernate中的jar包copy到我們工程的lib目錄下
第二步:導入Spring的包
注意這里,我的Spring包中有重復的c3p0連接池,mysql的驅動包, 可以刪除掉
還需要刪除Spring中的asm-2.2.3.jar, commons-logging.jar, log4j-1.2.15.jar這些和Hibernate中重復的包.
第三步,加入配置文件
我們現在開始要將Spring的配置文件進行分離,以免項目大了以后,文件過大,不利于管理.
在src目錄下包config, 采用build path將config編譯成源目錄, 并在此包下建立6個Spring的配置文件
spring_action.xml : 用于配置Struts2的action
spring_aop.xml : 用于配置AOP
spring_common.xml : 用于配置組件類
spring_dao.xml : 用于配置dao層類
spring_service.xml : 用于配置service類
spring_transation.xml : 用于配置事務
所有Spring文件中的內容模板如下:
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
?????????? http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
?????????? http://www.springframework.org/schema/context
?????????? http://www.springframework.org/schema/context/spring-context-2.5.xsd??????????
?????????? http://www.springframework.org/schema/aop
?????????? http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
?????????? http://www.springframework.org/schema/tx
?????????? http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
</beans>
此頭文件加入了IOC,AOP,事務的支持
但是spring_common.xml中的內容需要做一些全局配置:
我們需要做以下一些準備功能
1. 打開IOC注釋的功能
2. AOP注釋的功能
3. IOC全局掃描的功能
4. 配置事務管理器,并打開事務的注釋功能
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
?????????? http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
?????????? http://www.springframework.org/schema/context
?????????? http://www.springframework.org/schema/context/spring-context-2.5.xsd??????????
?????????? http://www.springframework.org/schema/aop
?????????? http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
?????????? http://www.springframework.org/schema/tx
?????????? http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.wdpc.ssh" />
<aop:aspectj-autoproxy />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
??????? "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
??????? "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 設置使用數據庫的語言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="Hibernate.current_session_context_class">thread</property>
<!-- 設置是否顯示執行的語言 -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!-- 數據庫連接屬性設置 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8</property>
<property name="connection.username">root</property>
<property name="connection.password">wdpc</property>
<!-- 設置 c3p0連接池的屬性-->
<property name="connection.useUnicode">true</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<property name="hibernate.c3p0.validate">true</property>
<property name="hibernate.c3p0.max_size">3</property>
<property name="hibernate.c3p0.min_size">1</property>
<!-- 加載映射文件-->
<mapping resource="com/wdpc/ssh/model/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
我們以前在單獨使用Hibernate的時候,需要一個HibernateUitl工具類,
Spring已經提供了這樣一個類給我們(LocalSessionFactoryBean),但是我們需要給這個類的屬性值進行配置, 我們需要告訴它,怎么進行連接數據庫, Hibernate的Model類的映射文件在哪里, 已經Hibernate的一些常用開關的配置信息.
事務和JDBC事務管理類不一樣,可以看到有一個Hibernate專用的HibernateTransactionManager事務管理類,我們同樣需要告訴事務管理類數據庫的一些信息,但是和JDBC事務管理類不一樣, 它需要一個sessionFactory類,而不是一個dataSource.
第四步: 編寫Model類,并添加映射文件,并將映射文件路徑添加到spring_common.xml文件的sessionFactory類的配置信息中.
public class User {
private String id;
private String name;
public User() {
super();
}
public User(String name) {
super();
this.name = name;
}
public User(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
映射文件:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.wdpc.ssh.model.User" table="users">
<id name="id" type="java.lang.String" column="id" length="32">
<generator class="uuid.hex" />
</id>
<property name="name" type="java.lang.String" column="name"
length="20" />
</class>
</hibernate-mapping>
將映射文件路徑加入到Spring_commons.xml的配置文件中
<property name="mappingResources">
<list>
<value>com/wdpc/ssh/model/User.hbm.xml</value>
</list>
</property>
第五步: 編寫Dao層接口與實現類,并將其納入到Spring的管理
接口:
public interface UserDao {
public void create(User user) throws Exception;
public void delete(Integer id) throws Exception;
public void update(User user) throws Exception;
public User findById(Integer id) throws Exception;
public List<User> findAll() throws Exception;
}
實現類:
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
public void create(User user) throws Exception {
sessionFactory.getCurrentSession().save(user);
}
public void delete(Integer id) throws Exception {
sessionFactory.getCurrentSession().delete(findById(id));
}
public void update(User user) throws Exception {
sessionFactory.getCurrentSession().update(user);
}
public List<User> findAll() throws Exception {
return sessionFactory.getCurrentSession().createQuery("from User")
.list();
}
public User findById(Integer id) throws Exception {
return (User) sessionFactory.getCurrentSession().get(User.class, id);
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
將UserDao納入到Spring的管理,我們需要在Spring_dao.xml配置文件中配置
<bean id="userDao" class="com.wdpc.ssh.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
第六步: 編寫Service層接口與實現類:
接口:
public interface UserService {
public void create(User user) throws Exception;
public void delete(Integer id) throws Exception;
public void update(User user) throws Exception;
public User findById(Integer id) throws Exception;
public List<User> findAll() throws Exception;
}
實現類:
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void create(User user) throws Exception {
userDao.create(user);
}
public void delete(Integer id) throws Exception {
userDao.delete(id);
}
public List<User> findAll() throws Exception {
return userDao.findAll();
}
public User findById(Integer id) throws Exception {
return userDao.findById(id);
}
public void update(User user) throws Exception {
userDao.update(user);
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
同樣的,Service層需要Dao層,需要注入進來.在spring_service.xml中配置
<bean id="userService" class="com.wdpc.ssh.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
第七步:給Service層添加事務處理
在spring_transation.xml文件中加入服務層事務的支持
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true" />
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut"
expression="execution(* com.wdpc.ssh.service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
第八步:Test
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] { "spring_action.xml", "spring_aop.xml",
"spring_common.xml", "spring_dao.xml",
"spring_service.xml", "spring_transation.xml" });
UserService userService = (UserService) ctx.getBean("userService");
try {
userService.create(new User("張海當"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
我們以綜合示例為例子來一步步的完成我們框架的集成
首先建一個web工程, 并將包建好

包名詳解:
com.wdpc.ssh.action: 放置Struts2的Action
com.wdpc.ssh.commons: 放置公用組件,工具類
com.wdpc.ssh.dao: 放置dao層的接口
com.wdpc.ssh.dao.impl: 放置dao層的實現類
com.wdpc.ssh.model: 放置實體對象的模型
com.wdpc.ssh.service: 放置業務層的接口
com.wdpc.ssh. service.impl: 放置業務層的實現類
com.wdpc.ssh.test: 放置單元測試類
首先集成Spring + Hibernate
第一步:導入Hiberante的包

注意我這里的Hibernate包中已經帶有c3p0連接池,mysql的驅動包,以及sqljdbc4的包(SQLServer, mysql的驅動包只需要保留一個就可以了, 用什么數據庫就保留對應的驅動包.)
將Hibernate中的jar包copy到我們工程的lib目錄下
第二步:導入Spring的包

注意這里,我的Spring包中有重復的c3p0連接池,mysql的驅動包, 可以刪除掉
還需要刪除Spring中的asm-2.2.3.jar, commons-logging.jar, log4j-1.2.15.jar這些和Hibernate中重復的包.
第三步,加入配置文件
我們現在開始要將Spring的配置文件進行分離,以免項目大了以后,文件過大,不利于管理.
在src目錄下包config, 采用build path將config編譯成源目錄, 并在此包下建立6個Spring的配置文件

spring_action.xml : 用于配置Struts2的action
spring_aop.xml : 用于配置AOP
spring_common.xml : 用于配置組件類
spring_dao.xml : 用于配置dao層類
spring_service.xml : 用于配置service類
spring_transation.xml : 用于配置事務
所有Spring文件中的內容模板如下:
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
?????????? http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
?????????? http://www.springframework.org/schema/context
?????????? http://www.springframework.org/schema/context/spring-context-2.5.xsd??????????
?????????? http://www.springframework.org/schema/aop
?????????? http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
?????????? http://www.springframework.org/schema/tx
?????????? http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
</beans>
此頭文件加入了IOC,AOP,事務的支持
但是spring_common.xml中的內容需要做一些全局配置:
我們需要做以下一些準備功能
1. 打開IOC注釋的功能
2. AOP注釋的功能
3. IOC全局掃描的功能
4. 配置事務管理器,并打開事務的注釋功能
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
?????????? http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
?????????? http://www.springframework.org/schema/context
?????????? http://www.springframework.org/schema/context/spring-context-2.5.xsd??????????
?????????? http://www.springframework.org/schema/aop
?????????? http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
?????????? http://www.springframework.org/schema/tx
?????????? http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.wdpc.ssh" />
<aop:aspectj-autoproxy />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
??????? "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
??????? "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 設置使用數據庫的語言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="Hibernate.current_session_context_class">thread</property>
<!-- 設置是否顯示執行的語言 -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!-- 數據庫連接屬性設置 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8</property>
<property name="connection.username">root</property>
<property name="connection.password">wdpc</property>
<!-- 設置 c3p0連接池的屬性-->
<property name="connection.useUnicode">true</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<property name="hibernate.c3p0.validate">true</property>
<property name="hibernate.c3p0.max_size">3</property>
<property name="hibernate.c3p0.min_size">1</property>
<!-- 加載映射文件-->
<mapping resource="com/wdpc/ssh/model/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
我們以前在單獨使用Hibernate的時候,需要一個HibernateUitl工具類,
Spring已經提供了這樣一個類給我們(LocalSessionFactoryBean),但是我們需要給這個類的屬性值進行配置, 我們需要告訴它,怎么進行連接數據庫, Hibernate的Model類的映射文件在哪里, 已經Hibernate的一些常用開關的配置信息.
事務和JDBC事務管理類不一樣,可以看到有一個Hibernate專用的HibernateTransactionManager事務管理類,我們同樣需要告訴事務管理類數據庫的一些信息,但是和JDBC事務管理類不一樣, 它需要一個sessionFactory類,而不是一個dataSource.
第四步: 編寫Model類,并添加映射文件,并將映射文件路徑添加到spring_common.xml文件的sessionFactory類的配置信息中.
public class User {
private String id;
private String name;
public User() {
super();
}
public User(String name) {
super();
this.name = name;
}
public User(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
映射文件:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.wdpc.ssh.model.User" table="users">
<id name="id" type="java.lang.String" column="id" length="32">
<generator class="uuid.hex" />
</id>
<property name="name" type="java.lang.String" column="name"
length="20" />
</class>
</hibernate-mapping>
將映射文件路徑加入到Spring_commons.xml的配置文件中
<property name="mappingResources">
<list>
<value>com/wdpc/ssh/model/User.hbm.xml</value>
</list>
</property>
第五步: 編寫Dao層接口與實現類,并將其納入到Spring的管理
接口:
public interface UserDao {
public void create(User user) throws Exception;
public void delete(Integer id) throws Exception;
public void update(User user) throws Exception;
public User findById(Integer id) throws Exception;
public List<User> findAll() throws Exception;
}
實現類:
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
public void create(User user) throws Exception {
sessionFactory.getCurrentSession().save(user);
}
public void delete(Integer id) throws Exception {
sessionFactory.getCurrentSession().delete(findById(id));
}
public void update(User user) throws Exception {
sessionFactory.getCurrentSession().update(user);
}
public List<User> findAll() throws Exception {
return sessionFactory.getCurrentSession().createQuery("from User")
.list();
}
public User findById(Integer id) throws Exception {
return (User) sessionFactory.getCurrentSession().get(User.class, id);
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
將UserDao納入到Spring的管理,我們需要在Spring_dao.xml配置文件中配置
<bean id="userDao" class="com.wdpc.ssh.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
第六步: 編寫Service層接口與實現類:
接口:
public interface UserService {
public void create(User user) throws Exception;
public void delete(Integer id) throws Exception;
public void update(User user) throws Exception;
public User findById(Integer id) throws Exception;
public List<User> findAll() throws Exception;
}
實現類:
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void create(User user) throws Exception {
userDao.create(user);
}
public void delete(Integer id) throws Exception {
userDao.delete(id);
}
public List<User> findAll() throws Exception {
return userDao.findAll();
}
public User findById(Integer id) throws Exception {
return userDao.findById(id);
}
public void update(User user) throws Exception {
userDao.update(user);
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
同樣的,Service層需要Dao層,需要注入進來.在spring_service.xml中配置
<bean id="userService" class="com.wdpc.ssh.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
第七步:給Service層添加事務處理
在spring_transation.xml文件中加入服務層事務的支持
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true" />
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut"
expression="execution(* com.wdpc.ssh.service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
第八步:Test
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] { "spring_action.xml", "spring_aop.xml",
"spring_common.xml", "spring_dao.xml",
"spring_service.xml", "spring_transation.xml" });
UserService userService = (UserService) ctx.getBean("userService");
try {
userService.create(new User("張海當"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
