Spring+Hibernate+Struts(SSH)框架整合實(shí)戰(zhàn)
SSH框架整合
前言:有人說(shuō),現(xiàn)在還是流行主流框架,SSM都出來(lái)很久了,更不要說(shuō)SSH。我不以為然。現(xiàn)在許多公司所用的老項(xiàng)目還是ssh,如果改成主流框架,需要成本。再說(shuō)比如金融IT這一塊,數(shù)據(jù)庫(kù)dao層還是推薦使用的是hibernate,因?yàn)槟軌蚩焖匍_(kāi)發(fā)上手,除非是互聯(lián)網(wǎng),因涉及到高并發(fā),dao層用的是mybatis,數(shù)據(jù)交互效率較快。所以,SSH不容忽略。
一、什么是SSH
SSH是 struts+spring+hibernate的一個(gè)集成框架,是目前比較流行的一種Web應(yīng)用程序開(kāi)源框架。
集成SSH框架的系統(tǒng)從職責(zé)上分為四層:表示層、業(yè)務(wù)邏輯層、數(shù)據(jù)持久層和域模塊層,以幫助開(kāi)發(fā)人員在短期內(nèi)搭建結(jié)構(gòu)清晰、可復(fù)用性好、維護(hù)方便的Web應(yīng)用程序。其中使用Struts作為系統(tǒng)的整體基礎(chǔ)架構(gòu),負(fù)責(zé)MVC的分離,在Struts框架的模型部分,控制業(yè)務(wù)跳轉(zhuǎn),利用Hibernate框架對(duì)持久層提供支持,Spring做管理,管理struts和hibernate。具體做法是:用面向?qū)ο蟮姆治龇椒ǜ鶕?jù)需求提出一些模型,將這些模型實(shí)現(xiàn)為基本的Java對(duì)象,然后編寫(xiě)基本的DAO(Data Access Objects)接口,并給出Hibernate的DAO實(shí)現(xiàn),采用Hibernate架構(gòu)實(shí)現(xiàn)的DAO類(lèi)來(lái)實(shí)現(xiàn)Java類(lèi)與數(shù)據(jù)庫(kù)之間的轉(zhuǎn)換和訪問(wèn),最后由Spring做管理,管理struts和hibernate。
---------百度百科
二、SSH所涉及的部分
三、快速部署環(huán)境
這里利用保存客戶(hù)的小Demo來(lái)演示整合SSH
1.導(dǎo)入所需jar包
1). Struts2框架
* struts-2.3.24\apps\struts2-blank\WEB-INF\lib\*.jar -- Struts2需要的所有jar包
* struts2-spring-plugin-2.3.24.jar ---Struts2整合Spring的插件包
2). Hibernate框架
* hibernate-release-5.0.7.Final\lib\required\*.jar -- Hibernate框架需要的jar包
* slf4j-api-1.6.1.jar -- 日志接口
* slf4j-log4j12-1.7.2.jar -- 日志實(shí)現(xiàn)
* mysql-connector-java-5.1.7-bin.jar -- MySQL的驅(qū)動(dòng)包
3). Spring框架
* IOC核心包
* AOP核心包
* JDBC模板和事務(wù)核心包
* Spring整合JUnit測(cè)試包
* Spring整合Hibernate核心包
* Spring整合Struts2核心包
2、在web.xml中配置spring與struts的相關(guān)代碼
1)配置struts2核心過(guò)濾器
這里定義為攔截所有
<!-- 配置核心過(guò)濾器 --> <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> <url-pattern>/*</url-pattern> </filter-mapping>
2)配置spring的監(jiān)聽(tīng)器
當(dāng)服務(wù)啟動(dòng)時(shí),就會(huì)先加載spring的配置文件
<!-- 配置Spring框架整合WEB的監(jiān)聽(tīng)器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
3)配置默認(rèn)加載路徑
<!-- 監(jiān)聽(tīng)器默認(rèn)加載Web-INF文件下,需要配置參數(shù)來(lái)加載指定文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
總結(jié):web.xml全部代碼為
<!-- 配置Spring框架整合WEB的監(jiān)聽(tīng)器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 監(jiān)聽(tīng)器默認(rèn)加載Web-INF文件下,需要配置參數(shù)來(lái)加載指定文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置核心過(guò)濾器 --> <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> <url-pattern>/*</url-pattern> </filter-mapping>
2、src下編寫(xiě)相關(guān)配置文件
1)spring:applicationContext.xml
導(dǎo)入相關(guān)約束
<?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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> </beans>
2)hibernate:hibernate.cfg.xml
導(dǎo)入相關(guān)約束,并配置數(shù)據(jù)庫(kù)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 必須配置 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://192.168.174.130:3306/SSH</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 可選配置 --> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 配置C3P0的連接池 --> <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!-- 不能配置綁定當(dāng)前的線程的操作 --> <!-- 映射配置文件 --> <mapping resource="com/clj/domain/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>
3)配置log4j.properties
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c\:mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=info, stdout
4)struts2:struts.xml
導(dǎo)入相關(guān)約束
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> </struts>
總結(jié):src所需配置文件如圖
3、配置dao層
定義一個(gè)接口和其實(shí)現(xiàn)類(lèi)
public interface CustomerDao { public void save(Customer customer); }
public class CustomerDaoImpl implements CustomerDao { public void save(Customer customer) { } }
4、定義業(yè)務(wù)層接口和實(shí)現(xiàn)類(lèi)
package com.clj.service; import com.clj.domain.Customer; public interface CustomerService { public void save(Customer customer); }
package com.clj.service; import org.springframework.transaction.annotation.Transactional; import com.clj.dao.CustomerDao; import com.clj.domain.Customer; /** * 客戶(hù)的業(yè)務(wù)層 * @author Administrator * */ public class CustomerServiceImpl implements CustomerService{//用來(lái)保存客戶(hù) public void save(Customer customer) { } }
5、定義pojo類(lèi)
hibernate通過(guò)操作pojo類(lèi)來(lái)操作數(shù)據(jù)庫(kù)表,做到對(duì)象關(guān)系映射
package com.clj.domain; public class Customer { private Long cust_id; private String cust_name; private Long cust_user_id; private Long cust_create_id; private String cust_source; private String cust_industry; private String cust_level; private String cust_linkman; private String cust_phone; private String cust_mobile; public Long getCust_id() { return cust_id; } public void setCust_id(Long cust_id) { this.cust_id = cust_id; } public String getCust_name() { return cust_name; } public void setCust_name(String cust_name) { this.cust_name = cust_name; } public Long getCust_user_id() { return cust_user_id; } public void setCust_user_id(Long cust_user_id) { this.cust_user_id = cust_user_id; } public Long getCust_create_id() { return cust_create_id; } public void setCust_create_id(Long cust_create_id) { this.cust_create_id = cust_create_id; } public String getCust_source() { return cust_source; } public void setCust_source(String cust_source) { this.cust_source = cust_source; } public String getCust_industry() { return cust_industry; } public void setCust_industry(String cust_industry) { this.cust_industry = cust_industry; } public String getCust_level() { return cust_level; } public void setCust_level(String cust_level) { this.cust_level = cust_level; } public String getCust_linkman() { return cust_linkman; } public void setCust_linkman(String cust_linkman) { this.cust_linkman = cust_linkman; } public String getCust_phone() { return cust_phone; } public void setCust_phone(String cust_phone) { this.cust_phone = cust_phone; } public String getCust_mobile() { return cust_mobile; } public void setCust_mobile(String cust_mobile) { this.cust_mobile = cust_mobile; } @Override public String toString() { return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_user_id=" + cust_user_id + ", cust_create_id=" + cust_create_id + ", cust_source=" + cust_source + ", cust_industry=" + cust_industry + ", cust_level=" + cust_level + ", cust_linkman=" + cust_linkman + ", cust_phone=" + cust_phone + ", cust_mobile=" + cust_mobile + "]"; } }
6、定義Customer.hbm.xml
此配置文件關(guān)乎Customer這個(gè)pojo類(lèi),此文件需放在Customer pojo類(lèi)同個(gè)包下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.clj.domain.Customer" table="cst_customer"> <id name="cust_id" column="cust_id"> <generator class="native"/> </id> <property name="cust_name" column="cust_name"/> <property name="cust_user_id" column="cust_user_id"/> <property name="cust_create_id" column="cust_create_id"/> <property name="cust_source" column="cust_source"/> <property name="cust_industry" column="cust_industry"/> <property name="cust_level" column="cust_level"/> <property name="cust_linkman" column="cust_linkman"/> <property name="cust_phone" column="cust_phone"/> <property name="cust_mobile" column="cust_mobile"/> </class> </hibernate-mapping>
項(xiàng)目構(gòu)建大致圖
四、demo之保存客戶(hù)初步演示
這里先初略的定義持久層交給heibernate,業(yè)務(wù)層交個(gè)struts2,創(chuàng)建實(shí)例交給spring
1、定義一個(gè)保存客戶(hù)的界面,利用form表單進(jìn)行數(shù)據(jù)的提交
根據(jù)域名可知,這里利用的是struts2的通配符方式進(jìn)行訪問(wèn)
<FORM id=form1 name=form1 action="${pageContext.request.contextPath }/customer_add.action" method=post> <!--table部分省略--> </FORM>
2、在struts.xml中配置接受請(qǐng)求,根據(jù)action名和方法跳轉(zhuǎn)指定的action,執(zhí)行指定的方法
spring整合struts2方式一:action由struts2框架管理
* 因?yàn)閷?dǎo)入的struts2-spring-plugin-2.3.24.jar 包自帶一個(gè)配置文件 struts-plugin.xml ,該配置文件中有如下代碼
* <constant name="struts.objectFactory" value="spring" /> 開(kāi)啟一個(gè)常量,如果該常量開(kāi)啟,那么下面的常量就可以使用
* struts.objectFactory.spring.autoWire = name,該常量是可以讓Action的類(lèi)來(lái)自動(dòng)裝配Bean對(duì)象!
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 配置包結(jié)構(gòu) --> <package name="crm" extends="struts-default" namespace="/"> <!-- 配置客戶(hù)的Action --> <!-- 方式一:aciton由struts2框架管理--> <action name="customer_*" class="com.clj.web.action.CustomerAction" method="{1}"/> </package> </struts>
3、在spring的applicationContext.xml中配置相對(duì)應(yīng)的bean以及事務(wù)
這里利用spring中IOC(控制反轉(zhuǎn))的特性,將創(chuàng)建實(shí)例的任務(wù)交給spring框架管理
<bean id="customerService" class="com.clj.service.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"></property> </bean> <bean id="customerDao" class="com.clj.dao.CustomerDaoImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"/> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <!-- 注入sessionFactory --> <property name="sessionFactory"/> </bean> </beans>
4、編寫(xiě)持久層實(shí)現(xiàn)類(lèi)相關(guān)代碼
這里利用hibernate提供的模板類(lèi),內(nèi)部封轉(zhuǎn)了session,從而可以調(diào)用session中的方法
/** * 持久層 * * @author Administrator * */ public class CustomerDaoImpl implements CustomerDao { //將數(shù)據(jù)保存到數(shù)據(jù)庫(kù)中(調(diào)用模板類(lèi)(hibernate提供,內(nèi)部封裝了session)) private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } /** * 保存客戶(hù) */ public void save(Customer customer) { System.out.println("持久層:保存客戶(hù)"); hibernateTemplate().save(customer); } }
5、編寫(xiě)業(yè)務(wù)層實(shí)現(xiàn)類(lèi)相關(guān)代碼
package com.clj.service; import org.springframework.transaction.annotation.Transactional; import com.clj.dao.CustomerDao; import com.clj.domain.Customer; /** * 客戶(hù)的業(yè)務(wù)層 * @author Administrator * */ @Transactional public class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } //用來(lái)保存客戶(hù) public void save(Customer customer) { System.out.println("業(yè)務(wù)層,保存客戶(hù)"); customerDao.save(customer); } }
6、編寫(xiě)action相關(guān)代碼
這里通過(guò)struts2的模板類(lèi)
package com.clj.web.action; import org.apache.struts2.ServletActionContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.clj.domain.Customer; import com.clj.service.CustomerService; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; /** * 客戶(hù)的控制層 * @author Administrator * */ public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{ //不要忘記手動(dòng)new private Customer customer=new Customer(); public Customer getModel() { return customer; } //提供service成員屬性,提供set方法 private CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } /** * 保存客戶(hù) * @return */ public String add(){ System.out.println("WEB層,保存客戶(hù)"); //方式一:創(chuàng)建web的工廠(action由struts2創(chuàng)建) WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext()); CustomerService cs=(CustomerService) context.getBean("customerService"); //調(diào)用方法 cs.save(customer);return NONE; } }
五、項(xiàng)目?jī)?yōu)化之整合
1、 spring整合struts2方式二:action由spring框架管理
把具體的 Action類(lèi)配置文件applicatonContext.xml的配置文件中,但是注意:struts.xml需要做修改
<struts> <!-- 配置包結(jié)構(gòu) --> <package name="crm" extends="struts-default" namespace="/"> <!-- 配置客戶(hù)的Action --> <!-- 方式一:aciton由struts2框架管理 <action name="customer_*" class="com.clj.web.action.CustomerAction" method="{1}"/>--> <!-- 方式二:action由spring管理,class標(biāo)簽上只需要編寫(xiě)srping配置bean的ID值既可以--> <action name="customer_*" class="customerAction" method="{1}"></action> </package> </struts>
2、在applicationContext.xml中配置Action類(lèi)
注意:1)Spring框架默認(rèn)生成CustomerAction是單例的,而Struts2框架是多例的。所以需要配置 scope="prototype"
2)此時(shí)沒(méi)有struts2的自動(dòng)裝配,在action需要手動(dòng)配置customerService屬性,并在action類(lèi)中生成set方法
<!-- 配置客戶(hù)模塊 --> <!-- 強(qiáng)調(diào):配置的Aciton,必須是多列的 --> <bean id="customerAction" class="com.clj.web.action.CustomerAction" scope="prototype"> <!--注意:struts管理action時(shí),基于其中有個(gè)struts-plugin的jar包,其中更改了一個(gè) 常量struts.objectFactory.spring.autoWire = name將其打開(kāi)了,可以自動(dòng)裝配,只需要提供set方法 但是此時(shí)action由spring管理,自動(dòng)裝配失效,所以需要手動(dòng)進(jìn)行配置注入 --> <property name="customerService" ref="customerService"></property> </bean>
3、.配置事務(wù)
spring整合hibernate方式一: (帶有 hibernate.cfg.xml的配置文件。強(qiáng)調(diào):不能加綁定當(dāng)前線程的配置)
以前玩hibernate時(shí),hibernate.cfg.xml都是由hibernate框架管理,其配置文件能生成sessionFactory,持久層加載此配置文件獲取sessionFactory,從而創(chuàng)建工廠生成session,進(jìn)行數(shù)據(jù)的增刪改成,此時(shí)其配置文件應(yīng)該交給spring管理,充分利用spring的IOC特性
Spring框架提供了一個(gè)HibernateDaoSupport的工具類(lèi),以后DAO都可以繼承該類(lèi)!!在引入hibernate核心配置文件之前,得讓dao層繼承一個(gè)父類(lèi)HibernateDaoSupport,此父類(lèi)內(nèi)部封裝了事務(wù)模板
看源碼:
1)修改相對(duì)應(yīng)的持久層實(shí)現(xiàn)類(lèi),讓他繼承HibernateDaoSupport
package com.clj.dao; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.clj.domain.Customer; /** * 持久層 * 繼承HibernateDaoSupport,內(nèi)部封裝了HibernateTemplate * @author Administrator * */ public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { //將數(shù)據(jù)保存到數(shù)據(jù)庫(kù)中(調(diào)用模板類(lèi)(hibernate提供,內(nèi)部封裝了session)) /*private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; }*/ /** * 保存客戶(hù) */ public void save(Customer customer) { System.out.println("持久層:保存客戶(hù)"); this.getHibernateTemplate().save(customer); } }
2)修改業(yè)務(wù)層讓?zhuān)_(kāi)啟事務(wù)注解
package com.clj.service; import org.springframework.transaction.annotation.Transactional; import com.clj.dao.CustomerDao; import com.clj.domain.Customer; /** * 客戶(hù)的業(yè)務(wù)層 * @author Administrator * */ @Transactional public class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } //用來(lái)保存客戶(hù) public void save(Customer customer) { System.out.println("業(yè)務(wù)層,保存客戶(hù)"); customerDao.save(customer); } }
3)修改applicationContext.xml文件
先引入hibernate配置文件
<!-- 編寫(xiě)bean,名稱(chēng)都是固定的,由spring提供,用來(lái)加載hibernate.cfg.xml的配置文件--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 配置路徑:當(dāng)啟動(dòng)服務(wù)器時(shí) ,該對(duì)象就會(huì)被創(chuàng)建,從而加載hibernate.cfg.xml文件,從而生成sessionFactory對(duì)象--> <property name="configLocation" value="classpath:hibernate.cfg.xml"/> </bean>
配置平臺(tái)事務(wù)管理:用來(lái)管理事務(wù), 注意現(xiàn)在使用的是 Hibernate框架,所以需要使用Hibernate框架的事務(wù)管理器
<!-- 先配置平臺(tái)事務(wù)管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <!-- 注入事務(wù),session能夠管理事務(wù),工廠能夠創(chuàng)建session --> <property name="sessionFactory" ref="sessionFactory"/> </bean>
開(kāi)啟事務(wù)注解
<!-- 開(kāi)啟事務(wù)的注解 --> <tx:annotation-driven transaction-manager="transactionManager"/>
去除模板類(lèi)配置,并為持久層配置sessionFactory
<!-- 以后,Dao都需要繼承HibernateDaoSupport,注入sessionFactory --> <bean id="customerDao" class="com.clj.dao.CustomerDaoImpl"> <!--<property name="hibernateTemplate" ref="hibernateTemplate"/>--> <!-- 這里不注入模板類(lèi),而是注入sessionFactory,因?yàn)槟0逍枰猻ession(封裝了session)--> <property name="sessionFactory" ref="sessionFactory"/> </bean>
全部代碼如下
<?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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 編寫(xiě)bean,名稱(chēng)都是固定的,有spring提供,用來(lái)加載hibernate.cfg.xml的配置文件--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 配置路徑:當(dāng)啟動(dòng)服務(wù)器時(shí) ,該對(duì)象就會(huì)被創(chuàng)建,從而加載hibernate.cfg.xml文件,從而生成sessionFactory對(duì)象--> <property name="configLocation" value="classpath:hibernate.cfg.xml"/> </bean> <!-- 先配置平臺(tái)事務(wù)管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <!-- 注入事務(wù),session能夠管理事務(wù),工廠能夠創(chuàng)建session --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 開(kāi)啟事務(wù)的注解 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置客戶(hù)模塊 --> <!-- 強(qiáng)調(diào):配置的Aciton,必須是多列的 --> <bean id="customerAction" class="com.clj.web.action.CustomerAction" scope="prototype"> <!--注意:struts管理action時(shí),基于其中有個(gè)struts-plugin的jar包,其中更改了一個(gè) 常量struts.objectFactory.spring.autoWire = name將其打開(kāi)了,可以自動(dòng)裝配,只需要提供set方法 但是此時(shí)action由spring管理,自動(dòng)裝配失效,所以需要手動(dòng)進(jìn)行配置注入 --> <property name="customerService" ref="customerService"></property> </bean> <bean id="customerService" class="com.clj.service.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"></property> </bean> <bean id="customerDao" class="com.clj.dao.CustomerDaoImpl"> <!--<property name="hibernateTemplate" ref="hibernateTemplate"/>--> <!-- 這里不注入模板類(lèi),而是注入sessionFactory,因?yàn)槟0逍枰猻ession(封裝了session)--> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置模板類(lèi)(hibernate框架提供的,內(nèi)部封裝了session),此時(shí)交給spring管理,如果持久層繼承了HibernateDaoSupport,則無(wú)需配置--> <!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> 注入sessionFactory <property name="sessionFactory"/> </bean>--> </beans>
4)修改action類(lèi)
因?yàn)樽⑷肓藰I(yè)務(wù)層實(shí)現(xiàn)類(lèi),所以此時(shí)可以直接調(diào)用業(yè)務(wù)層方法,無(wú)須加載bean
package com.clj.web.action; import org.apache.struts2.ServletActionContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.clj.domain.Customer; import com.clj.service.CustomerService; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; /** * 客戶(hù)的控制層 * @author Administrator * */ public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{ //不要忘記手動(dòng)new private Customer customer=new Customer(); public Customer getModel() { return customer; } //提供service成員屬性,提供set方法 private CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } /** * 保存客戶(hù) * @return */ public String add(){ System.out.println("WEB層,保存客戶(hù)"); //方式一:創(chuàng)建web的工廠(action由struts2創(chuàng)建) /*WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext()); CustomerService cs=(CustomerService) context.getBean("customerService"); //調(diào)用方法 cs.save(customer);*/ customerService.save(customer); return NONE; } }
spring整合hibernate方式二: (不帶有 hibernate.cfg.xml的配置文件)
這里準(zhǔn)備刪除hibernate的核心配置文件,在刪除之前,需要將其配置文件中的相關(guān)內(nèi)容配置到spring的applicatioinContext.xml文件中取
1、查看hibernate.cfg.xml文件中的相關(guān)內(nèi)容
* 數(shù)據(jù)庫(kù)連接基本參數(shù)(4大參數(shù))
* Hibernate相關(guān)的屬性
* 連接池
* 映射文件
2、引入配置
引入連接池
<!-- 先配置C3p0的連接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean>
修改對(duì)應(yīng)的sessionFactory: 因?yàn)橐呀?jīng)沒(méi)有了 hibernate.cfg.xml的配置文件,所以需要修改該配置,注入連接池
引入對(duì)象映射文件:因?yàn)橐呀?jīng)沒(méi)有了hibernate.cfg.xml的配置文件,不會(huì)掃描到該配置文件,需要注入
<!-- 編寫(xiě)bean,名稱(chēng)都是固定的,有spring提供,用來(lái)加載hibernate.cfg.xml的配置文件--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!--先加載連接池 --> <property name="dataSource" ref="dataSource"/> <!-- 加載方言,加載可選項(xiàng) --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 引入映射的配置文件 --> <property name="mappingResources"> <list> <value>com/clj/domain/Customer.hbm.xml</value> </list> </property> </bean>
現(xiàn)在:applicationContext.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" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 先配置C3p0的連接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.174.130:3306/SSH"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 編寫(xiě)bean,名稱(chēng)都是固定的,有spring提供,用來(lái)加載hibernate.cfg.xml的配置文件--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!--先加載連接池 --> <property name="dataSource" ref="dataSource"/> <!-- 加載方言,加載可選項(xiàng) --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 引入映射的配置文件 --> <property name="mappingResources"> <list> <value>com/clj/domain/Customer.hbm.xml</value> </list> </property> </bean> <!-- 先配置平臺(tái)事務(wù)管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <!-- 注入事務(wù),session能夠管理事務(wù),工廠能夠創(chuàng)建session --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 開(kāi)啟事務(wù)的注解 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置客戶(hù)模塊 --> <!-- 強(qiáng)調(diào):配置的Aciton,必須是多列的 --> <bean id="customerAction" class="com.clj.web.action.CustomerAction" scope="prototype"> <!--注意:struts管理action時(shí),基于其中有個(gè)struts-plugin的jar包,其中更改了一個(gè) 常量struts.objectFactory.spring.autoWire = name將其打開(kāi)了,可以自動(dòng)裝配,只需要提供set方法 但是此時(shí)action由spring管理,自動(dòng)裝配失效,所以需要手動(dòng)進(jìn)行配置注入 --> <property name="customerService" ref="customerService"></property> </bean> <bean id="customerService" class="com.clj.service.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"></property> </bean> <!-- 以后,Dao都需要繼承HibernateDaoSupport,注入sessionFactory --> <bean id="customerDao" class="com.clj.dao.CustomerDaoImpl"> <!--<property name="hibernateTemplate" ref="hibernateTemplate"/>--> <!-- 這里不注入模板類(lèi),而是注入sessionFactory,因?yàn)槟0逍枰猻ession(封裝了session)--> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置模板類(lèi)(hibernate框架提供的,內(nèi)部封裝了session),此時(shí)交給spring管理,如果持久層繼承了HibernateDaoSupport,則無(wú)需配置--> <!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> 注入sessionFactory <property name="sessionFactory"/> </bean>--> </beans>
此時(shí)可以安心的刪除hibernate.cfg.xml文件了
這樣SSH整合完畢
六、Hibernate模板常用方法
注意:以下代碼省略了接口中的演示(偷了個(gè)懶,相信初學(xué)者不會(huì)看不懂)
1)插入:
持久層
package com.clj.dao; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.clj.domain.Customer; /** * 持久層 * 繼承HibernateDaoSupport,內(nèi)部封裝了HibernateTemplate * @author Administrator * */ public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public void update(Customer customer) { // TODO Auto-generated method stub this.getHibernateTemplate().update(customer); } }
業(yè)務(wù)層
package com.clj.service; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.clj.dao.CustomerDao; import com.clj.domain.Customer; /** * 客戶(hù)的業(yè)務(wù)層 * @author Administrator * */ @Transactional public class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } @Override public void update(Customer customer) { // TODO Auto-generated method stub customerDao.update(customer); } }
測(cè)試類(lèi)
package com.clj.test; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.clj.domain.Customer; import com.clj.service.CustomerService; /** * 測(cè)試Hiberante模板類(lèi)的簡(jiǎn)單方法 * @author Administrator * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class Demo1 { @Resource(name="customerService") private CustomerService customerService; /** * 測(cè)試插入 */ @Test public void run1(){ Customer customer=new Customer(); customer.setCust_id(1L); customer.setCust_name("測(cè)試"); customerService.update(customer); } }
2)以下為指定查詢(xún)、查詢(xún)所有、離線查詢(xún)代碼
持久層
package com.clj.dao; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.clj.domain.Customer; /** * 持久層 * 繼承HibernateDaoSupport,內(nèi)部封裝了HibernateTemplate * @author Administrator * */ public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { //將數(shù)據(jù)保存到數(shù)據(jù)庫(kù)中(調(diào)用模板類(lèi)(hibernate提供,內(nèi)部封裝了session)) /*private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; }*/ /** * 保存客戶(hù) */ public void save(Customer customer) { System.out.println("持久層:保存客戶(hù)"); this.getHibernateTemplate().save(customer); } @Override public void update(Customer customer) { // TODO Auto-generated method stub this.getHibernateTemplate().update(customer); } /** * 通過(guò)主鍵查詢(xún) */ public Customer getById(Long id) { return this.getHibernateTemplate().get(Customer.class, id); } /** * 查詢(xún)所有 */ @Override public List<Customer> findAll() { String sql="from Customer"; List<Customer> list=(List<Customer>) this.getHibernateTemplate().find(sql); return list; } /** * QBC離線查詢(xún) */ @Override public List<Customer> findAllByQBC() { DetachedCriteria criteria=DetachedCriteria.forClass(Customer.class); List<Customer> list=(List<Customer>) this.getHibernateTemplate().findByCriteria(criteria); return list; } }
業(yè)務(wù)層
package com.clj.service; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.clj.dao.CustomerDao; import com.clj.domain.Customer; /** * 客戶(hù)的業(yè)務(wù)層 * @author Administrator * */ @Transactional public class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } //用來(lái)保存客戶(hù) public void save(Customer customer) { System.out.println("業(yè)務(wù)層,保存客戶(hù)"); customerDao.save(customer); } @Override public void update(Customer customer) { // TODO Auto-generated method stub customerDao.update(customer); } @Override public Customer getById(Long id) { // TODO Auto-generated method stub return customerDao.getById(id); } @Override public List<Customer> findAll() { return customerDao.findAll(); } @Override public List<Customer> findAllByQBC() { // TODO Auto-generated method stub return customerDao.findAllByQBC(); } }
測(cè)試類(lèi)
package com.clj.test; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.clj.domain.Customer; import com.clj.service.CustomerService; /** * 測(cè)試Hiberante模板類(lèi)的簡(jiǎn)單方法 * @author Administrator * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class Demo1 { @Resource(name="customerService") private CustomerService customerService; /** * 測(cè)試插入 */ @Test public void run1(){ Customer customer=new Customer(); customer.setCust_id(1L); customer.setCust_name("測(cè)試"); customerService.update(customer); } /** * 測(cè)試查詢(xún)指定的客戶(hù) */ @Test public void run2(){ Customer customer=customerService.getById(2L); System.out.println(customer); } /** * 查詢(xún)所有的客戶(hù) */ @Test public void run3(){ List<Customer> list=customerService.findAll(); System.out.println(list); } /** * QBC(離線查詢(xún)) */ @Test public void run4(){ List<Customer> list=customerService.findAllByQBC(); System.out.println(list); } }
七、關(guān)于SSH延遲加載問(wèn)題
1. 使用延遲加載的時(shí)候,再WEB層查詢(xún)對(duì)象的時(shí)候程序會(huì)拋出異常!
* 原因是延遲加載還沒(méi)有發(fā)生SQL語(yǔ)句,在業(yè)務(wù)層session對(duì)象就已經(jīng)銷(xiāo)毀了,所以查詢(xún)到的JavaBean對(duì)象已經(jīng)變成了托管態(tài)對(duì)象!
* 注意:一定要先刪除javassist-3.11.0.GA.jar包(jar包沖突了)
2. 解決辦法
Spring框架提供了一個(gè)過(guò)濾器,讓session對(duì)象在WEB層就創(chuàng)建,在WEB層銷(xiāo)毀。只需要配置該過(guò)濾器即可
* 但是:要注意需要在struts2的核心過(guò)濾器之前進(jìn)行,spring監(jiān)聽(tīng)器之后配置
<!-- 解決延遲加載的問(wèn)題 --> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3、演示延遲加載
持久層:調(diào)用load方法,此方法時(shí)延遲加載的
/** * 延遲加載 */ @Override public Customer loadById(long id) { // TODO Auto-generated method stub return this.getHibernateTemplate().load(Customer.class, id); }
業(yè)務(wù)層
@Override public Customer loadById(long id) { // TODO Auto-generated method stub return customerDao.loadById(id); }
測(cè)試類(lèi)
@Test public void run5(){ Customer customer=customerService.loadById(2L); System.out.println(customer); }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Spring5+SpringMvc+Hibernate5整合的實(shí)現(xiàn)
- Spring+SpringMVC+Hibernate整合實(shí)例講解
- Spring+SpringMVC+Hibernate項(xiàng)目環(huán)境搭建的步驟(圖文)
- SpringBoot 使用hibernate validator校驗(yàn)
- Springboot+hibernate實(shí)現(xiàn)簡(jiǎn)單的增刪改查示例
- Spring MVC+FastJson+hibernate-validator整合的完整實(shí)例教程
- springboot使用hibernate validator校驗(yàn)方式
- Springboot hibernate envers使用過(guò)程詳解
相關(guān)文章
SpringBoot跨域Access-Control-Allow-Origin實(shí)現(xiàn)解析
這篇文章主要介紹了SpringBoot跨域Access-Control-Allow-Origin實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12Spring?AOP操作的相關(guān)術(shù)語(yǔ)及環(huán)境準(zhǔn)備
這篇文章主要為大家介紹了Spring?AOP操作的相關(guān)術(shù)語(yǔ)及環(huán)境準(zhǔn)備學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05使用@Autowired注解引入server服務(wù)層方法時(shí)報(bào)錯(cuò)的解決
這篇文章主要介紹了使用@Autowired注解引入server服務(wù)層方法時(shí)報(bào)錯(cuò)的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11zookeeper節(jié)點(diǎn)類(lèi)型詳解
今天小編就為大家分享一篇關(guān)于zookeeper節(jié)點(diǎn)類(lèi)型詳解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01Java main方法String[]args原理實(shí)例解析
這篇文章主要介紹了Java main方法String[]args原理實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06Java并發(fā)中的ABA問(wèn)題學(xué)習(xí)與解決方案
這篇文章主要介紹了Java并發(fā)中的ABA問(wèn)題學(xué)習(xí)與解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05java:程序包org.springframework.boot不存在的完美解決方法
最近項(xiàng)目中運(yùn)行的時(shí)候提示了"java: 程序包org.springframework.boot不存在",下面這篇文章主要給大家介紹了關(guān)于java:程序包org.springframework.boot不存在的完美解決方法,需要的朋友可以參考下2023-05-05