一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

2021-04-20 14:45佳先森 Java教程

SSH是 struts+spring+hibernate的一個集成框架,是目前比較流行的一種Web應用程序開源框架。本篇文章主要介紹了Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn),非常具有實用價值,需要的朋友可以參考下

ssh框架整合

前言:有人說,現(xiàn)在還是流行主流框架,ssm都出來很久了,更不要說ssh。我不以為然?,F(xiàn)在許多公司所用的老項目還是ssh,如果改成主流框架,需要成本。再說比如金融it這一塊,數(shù)據(jù)庫dao層還是推薦使用的是hibernate,因為能夠快速開發(fā)上手,除非是互聯(lián)網(wǎng),因涉及到高并發(fā),dao層用的是mybatis,數(shù)據(jù)交互效率較快。所以,ssh不容忽略。

一、什么是ssh

ssh是 struts+spring+hibernate的一個集成框架,是目前比較流行的一種web應用程序開源框架。

集成ssh框架的系統(tǒng)從職責上分為四層:表示層、業(yè)務邏輯層、數(shù)據(jù)持久層和域模塊層,以幫助開發(fā)人員在短期內(nèi)搭建結(jié)構(gòu)清晰、可復用性好、維護方便的web應用程序。其中使用struts作為系統(tǒng)的整體基礎架構(gòu),負責mvc的分離,在struts框架的模型部分,控制業(yè)務跳轉(zhuǎn),利用hibernate框架對持久層提供支持,spring做管理,管理struts和hibernate。具體做法是:用面向?qū)ο蟮姆治龇椒ǜ鶕?jù)需求提出一些模型,將這些模型實現(xiàn)為基本的java對象,然后編寫基本的dao(data access objects)接口,并給出hibernate的dao實現(xiàn),采用hibernate架構(gòu)實現(xiàn)的dao類來實現(xiàn)java類與數(shù)據(jù)庫之間的轉(zhuǎn)換和訪問,最后由spring做管理,管理struts和hibernate。

---------百度百科

二、ssh所涉及的部分

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

三、快速部署環(huán)境

這里利用保存客戶的小demo來演示整合ssh

1.導入所需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的插件包

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

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                                   -- 日志實現(xiàn)

* mysql-connector-java-5.1.7-bin.jar                        -- mysql的驅(qū)動包

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

3). spring框架

* ioc核心包

* aop核心包

* jdbc模板和事務核心包

* spring整合junit測試包

* spring整合hibernate核心包

* spring整合struts2核心包

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

2、在web.xml中配置spring與struts的相關代碼

1)配置struts2核心過濾器

這里定義為攔截所有

?
1
2
3
4
5
6
7
8
9
<!-- 配置核心過濾器 -->
 <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)聽器

當服務啟動時,就會先加載spring的配置文件

?
1
2
3
4
<!-- 配置spring框架整合web的監(jiān)聽器 -->
  <listener>
   <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
 </listener>

3)配置默認加載路徑

?
1
2
3
4
5
<!-- 監(jiān)聽器默認加載web-inf文件下,需要配置參數(shù)來加載指定文件 -->
 <context-param>
   <param-name>contextconfiglocation</param-name>
   <param-value>classpath:applicationcontext.xml</param-value>
</context-param>

總結(jié):web.xml全部代碼為

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 配置spring框架整合web的監(jiān)聽器 -->
  <listener>
   <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
 </listener>
 <!-- 監(jiān)聽器默認加載web-inf文件下,需要配置參數(shù)來加載指定文件 -->
 <context-param>
   <param-name>contextconfiglocation</param-name>
   <param-value>classpath:applicationcontext.xml</param-value>
 </context-param>
 <!-- 配置核心過濾器 -->
 <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下編寫相關配置文件

1)spring:applicationcontext.xml

導入相關約束

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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

導入相關約束,并配置數(shù)據(jù)庫

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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>
  
  <!-- 不能配置綁定當前的線程的操作 -->
  <!-- 映射配置文件 -->
  <mapping resource="com/clj/domain/customer.hbm.xml"/>
 </session-factory>
 
</hibernate-configuration>

3)配置log4j.properties

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
### 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

導入相關約束

?
1
2
3
4
5
6
<?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所需配置文件如圖

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

3、配置dao層

定義一個接口和其實現(xiàn)類

?
1
2
3
public interface customerdao {
 public void save(customer customer);
}
?
1
2
3
4
5
6
public class customerdaoimpl implements customerdao {
 public void save(customer customer) {
  
 }
 
}

4、定義業(yè)務層接口和實現(xiàn)類

?
1
2
3
4
5
6
7
package com.clj.service;
 
import com.clj.domain.customer;
 
public interface customerservice {
 public void save(customer customer);
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.clj.service;
 
import org.springframework.transaction.annotation.transactional;
 
import com.clj.dao.customerdao;
import com.clj.domain.customer;
/**
 * 客戶的業(yè)務層
 * @author administrator
 *
 */
public class customerserviceimpl implements customerservice{//用來保存客戶
 public void save(customer customer) {
  
 }
 
}

5、定義pojo類

hibernate通過操作pojo類來操作數(shù)據(jù)庫表,做到對象關系映射

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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

此配置文件關乎customer這個pojo類,此文件需放在customer pojo類同個包下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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>

項目構(gòu)建大致圖

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

四、demo之保存客戶初步演示

這里先初略的定義持久層交給heibernate,業(yè)務層交個struts2,創(chuàng)建實例交給spring

1、定義一個保存客戶的界面,利用form表單進行數(shù)據(jù)的提交

根據(jù)域名可知,這里利用的是struts2的通配符方式進行訪問

?
1
2
3
4
5
<form id=form1 name=form1
  action="${pagecontext.request.contextpath }/customer_add.action"
  method=post>
   <!--table部分省略-->
</form>

2、在struts.xml中配置接受請求,根據(jù)action名和方法跳轉(zhuǎn)指定的action,執(zhí)行指定的方法

spring整合struts2方式一:action由struts2框架管理

* 因為導入的struts2-spring-plugin-2.3.24.jar 包自帶一個配置文件 struts-plugin.xml ,該配置文件中有如下代碼

* <constant name="struts.objectfactory" value="spring" />   開啟一個常量,如果該常量開啟,那么下面的常量就可以使用

* struts.objectfactory.spring.autowire = name,該常量是可以讓action的類來自動裝配bean對象!

?
1
2
3
4
5
6
7
8
9
10
11
12
<?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="/">
   <!-- 配置客戶的action -->
   <!-- 方式一:aciton由struts2框架管理-->
      <action name="customer_*" class="com.clj.web.action.customeraction" method="{1}"/>
    </package>
 </struts>

3、在spring的applicationcontext.xml中配置相對應的bean以及事務

這里利用spring中ioc(控制反轉(zhuǎn))的特性,將創(chuàng)建實例的任務交給spring框架管理

?
1
2
3
4
5
6
7
8
9
10
11
<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àn)類相關代碼

這里利用hibernate提供的模板類,內(nèi)部封轉(zhuǎn)了session,從而可以調(diào)用session中的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * 持久層
 *
 * @author administrator
 *
 */
public class customerdaoimpl implements customerdao {
 //將數(shù)據(jù)保存到數(shù)據(jù)庫中(調(diào)用模板類(hibernate提供,內(nèi)部封裝了session))
 private hibernatetemplate hibernatetemplate;
 
 public void sethibernatetemplate(hibernatetemplate hibernatetemplate) {
  this.hibernatetemplate = hibernatetemplate;
 }
 
 /**
  * 保存客戶
  */
 public void save(customer customer) {
  system.out.println("持久層:保存客戶");
  hibernatetemplate().save(customer);
 }
 
}

5、編寫業(yè)務層實現(xiàn)類相關代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.clj.service;
 
import org.springframework.transaction.annotation.transactional;
 
import com.clj.dao.customerdao;
import com.clj.domain.customer;
/**
 * 客戶的業(yè)務層
 * @author administrator
 *
 */
@transactional
public class customerserviceimpl implements customerservice{
 private customerdao customerdao;
 
 public void setcustomerdao(customerdao customerdao) {
  this.customerdao = customerdao;
 }
 
 //用來保存客戶
 public void save(customer customer) {
  system.out.println("業(yè)務層,保存客戶");
  customerdao.save(customer);
 }
 
}

6、編寫action相關代碼

這里通過struts2的模板類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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;
 
/**
 * 客戶的控制層
 * @author administrator
 *
 */
public class customeraction extends actionsupport implements modeldriven<customer>{
 //不要忘記手動new
 private customer customer=new customer();
 public customer getmodel() {
  return customer;
 }
 //提供service成員屬性,提供set方法
 private customerservice customerservice;
 
 
 
 public void setcustomerservice(customerservice customerservice) {
  this.customerservice = customerservice;
 }
 
 
 
 /**
  * 保存客戶
  * @return
  */
 public string add(){
  system.out.println("web層,保存客戶");
  //方式一:創(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;
 }
 
 
}

五、項目優(yōu)化之整合

1、 spring整合struts2方式二:action由spring框架管理

把具體的 action類配置文件applicatoncontext.xml的配置文件中,但是注意:struts.xml需要做修改

?
1
2
3
4
5
6
7
8
9
10
<struts>
 <!-- 配置包結(jié)構(gòu) -->
  <package name="crm" extends="struts-default" namespace="/">
   <!-- 配置客戶的action -->
   <!-- 方式一:aciton由struts2框架管理
   <action name="customer_*" class="com.clj.web.action.customeraction" method="{1}"/>-->
   <!-- 方式二:action由spring管理,class標簽上只需要編寫srping配置bean的id值既可以-->
    <action name="customer_*" class="customeraction" method="{1}"></action>
  </package>
</struts>

2、在applicationcontext.xml中配置action類

注意:1)spring框架默認生成customeraction是單例的,而struts2框架是多例的。所以需要配置 scope="prototype"

2)此時沒有struts2的自動裝配,在action需要手動配置customerservice屬性,并在action類中生成set方法

?
1
2
3
4
5
6
7
8
9
<!-- 配置客戶模塊 -->
 <!-- 強調(diào):配置的aciton,必須是多列的 -->
 <bean id="customeraction" class="com.clj.web.action.customeraction" scope="prototype">
  <!--注意:struts管理action時,基于其中有個struts-plugin的jar包,其中更改了一個
  常量struts.objectfactory.spring.autowire = name將其打開了,可以自動裝配,只需要提供set方法
  但是此時action由spring管理,自動裝配失效,所以需要手動進行配置注入
  -->
  <property name="customerservice" ref="customerservice"></property>
</bean>

3、.配置事務

spring整合hibernate方式一: (帶有 hibernate.cfg.xml的配置文件。強調(diào):不能加綁定當前線程的配置)

以前玩hibernate時,hibernate.cfg.xml都是由hibernate框架管理,其配置文件能生成sessionfactory,持久層加載此配置文件獲取sessionfactory,從而創(chuàng)建工廠生成session,進行數(shù)據(jù)的增刪改成,此時其配置文件應該交給spring管理,充分利用spring的ioc特性

spring框架提供了一個hibernatedaosupport的工具類,以后dao都可以繼承該類!!在引入hibernate核心配置文件之前,得讓dao層繼承一個父類hibernatedaosupport,此父類內(nèi)部封裝了事務模板

看源碼:

Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)

1)修改相對應的持久層實現(xiàn)類,讓他繼承hibernatedaosupport

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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ù)庫中(調(diào)用模板類(hibernate提供,內(nèi)部封裝了session))
 /*private hibernatetemplate hibernatetemplate;
 
 public void sethibernatetemplate(hibernatetemplate hibernatetemplate) {
  this.hibernatetemplate = hibernatetemplate;
 }*/
 
 /**
  * 保存客戶
  */
 public void save(customer customer) {
  system.out.println("持久層:保存客戶");
  this.gethibernatetemplate().save(customer);
 }
 
}

2)修改業(yè)務層讓,開啟事務注解

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.clj.service;
 
import org.springframework.transaction.annotation.transactional;
 
import com.clj.dao.customerdao;
import com.clj.domain.customer;
/**
 * 客戶的業(yè)務層
 * @author administrator
 *
 */
@transactional
public class customerserviceimpl implements customerservice{
 private customerdao customerdao;
 
 public void setcustomerdao(customerdao customerdao) {
  this.customerdao = customerdao;
 }
 
 //用來保存客戶
 public void save(customer customer) {
  system.out.println("業(yè)務層,保存客戶");
  customerdao.save(customer);
 }
 
}

3)修改applicationcontext.xml文件

先引入hibernate配置文件

?
1
2
3
4
5
<!-- 編寫bean,名稱都是固定的,由spring提供,用來加載hibernate.cfg.xml的配置文件-->
 <bean id="sessionfactory" class="org.springframework.orm.hibernate5.localsessionfactorybean">
 <!-- 配置路徑:當啟動服務器時 ,該對象就會被創(chuàng)建,從而加載hibernate.cfg.xml文件,從而生成sessionfactory對象-->
  <property name="configlocation" value="classpath:hibernate.cfg.xml"/>
</bean>

配置平臺事務管理:用來管理事務, 注意現(xiàn)在使用的是 hibernate框架,所以需要使用hibernate框架的事務管理器

?
1
2
3
4
5
<!-- 先配置平臺事務管理器 -->
 <bean id="transactionmanager" class="org.springframework.orm.hibernate5.hibernatetransactionmanager">
  <!-- 注入事務,session能夠管理事務,工廠能夠創(chuàng)建session -->
  <property name="sessionfactory" ref="sessionfactory"/>
 </bean>

開啟事務注解

?
1
2
 <!-- 開啟事務的注解 -->
<tx:annotation-driven transaction-manager="transactionmanager"/>

去除模板類配置,并為持久層配置sessionfactory

?
1
2
3
4
5
6
<!-- 以后,dao都需要繼承hibernatedaosupport,注入sessionfactory -->
 <bean id="customerdao" class="com.clj.dao.customerdaoimpl">
  <!--<property name="hibernatetemplate" ref="hibernatetemplate"/>-->
  <!-- 這里不注入模板類,而是注入sessionfactory,因為模板需要session(封裝了session)-->
  <property name="sessionfactory" ref="sessionfactory"/>
 </bean>

全部代碼如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?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">
 <!-- 編寫bean,名稱都是固定的,有spring提供,用來加載hibernate.cfg.xml的配置文件-->
 <bean id="sessionfactory" class="org.springframework.orm.hibernate5.localsessionfactorybean">
 <!-- 配置路徑:當啟動服務器時 ,該對象就會被創(chuàng)建,從而加載hibernate.cfg.xml文件,從而生成sessionfactory對象-->
  <property name="configlocation" value="classpath:hibernate.cfg.xml"/>
 </bean>
 
 <!-- 先配置平臺事務管理器 -->
 <bean id="transactionmanager" class="org.springframework.orm.hibernate5.hibernatetransactionmanager">
  <!-- 注入事務,session能夠管理事務,工廠能夠創(chuàng)建session -->
  <property name="sessionfactory" ref="sessionfactory"/>
 </bean>
 
 <!-- 開啟事務的注解 -->
 <tx:annotation-driven transaction-manager="transactionmanager"/>
 
 <!-- 配置客戶模塊 -->
 <!-- 強調(diào):配置的aciton,必須是多列的 -->
 <bean id="customeraction" class="com.clj.web.action.customeraction" scope="prototype">
  <!--注意:struts管理action時,基于其中有個struts-plugin的jar包,其中更改了一個
  常量struts.objectfactory.spring.autowire = name將其打開了,可以自動裝配,只需要提供set方法
  但是此時action由spring管理,自動裝配失效,所以需要手動進行配置注入
  -->
  <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"/>-->
  <!-- 這里不注入模板類,而是注入sessionfactory,因為模板需要session(封裝了session)-->
  <property name="sessionfactory" ref="sessionfactory"/>
 </bean>
 <!-- 配置模板類(hibernate框架提供的,內(nèi)部封裝了session),此時交給spring管理,如果持久層繼承了hibernatedaosupport,則無需配置-->
 <!-- <bean id="hibernatetemplate" class="org.springframework.orm.hibernate5.hibernatetemplate">
  注入sessionfactory
  <property name="sessionfactory"/>
 </bean>-->
</beans>

4)修改action類

因為注入了業(yè)務層實現(xiàn)類,所以此時可以直接調(diào)用業(yè)務層方法,無須加載bean

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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;
 
/**
 * 客戶的控制層
 * @author administrator
 *
 */
public class customeraction extends actionsupport implements modeldriven<customer>{
 //不要忘記手動new
 private customer customer=new customer();
 public customer getmodel() {
  return customer;
 }
 //提供service成員屬性,提供set方法
 private customerservice customerservice;
 public void setcustomerservice(customerservice customerservice) {
  this.customerservice = customerservice;
 }
 /**
  * 保存客戶
  * @return
  */
 public string add(){
  system.out.println("web層,保存客戶");
  //方式一:創(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的配置文件)

這里準備刪除hibernate的核心配置文件,在刪除之前,需要將其配置文件中的相關內(nèi)容配置到spring的applicatioincontext.xml文件中取

1、查看hibernate.cfg.xml文件中的相關內(nèi)容

* 數(shù)據(jù)庫連接基本參數(shù)(4大參數(shù))

* hibernate相關的屬性

* 連接池

* 映射文件

2、引入配置

引入連接池

?
1
2
3
4
5
6
7
<!-- 先配置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>

修改對應的sessionfactory: 因為已經(jīng)沒有了 hibernate.cfg.xml的配置文件,所以需要修改該配置,注入連接池

引入對象映射文件:因為已經(jīng)沒有了hibernate.cfg.xml的配置文件,不會掃描到該配置文件,需要注入

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- 編寫bean,名稱都是固定的,有spring提供,用來加載hibernate.cfg.xml的配置文件-->
<bean id="sessionfactory" class="org.springframework.orm.hibernate5.localsessionfactorybean">
 <!--先加載連接池 -->
 <property name="datasource" ref="datasource"/>
 <!-- 加載方言,加載可選項 -->
 <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全部代碼如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?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>
 
 <!-- 編寫bean,名稱都是固定的,有spring提供,用來加載hibernate.cfg.xml的配置文件-->
 <bean id="sessionfactory" class="org.springframework.orm.hibernate5.localsessionfactorybean">
  <!--先加載連接池 -->
  <property name="datasource" ref="datasource"/>
  <!-- 加載方言,加載可選項 -->
  <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>
 
 <!-- 先配置平臺事務管理器 -->
 <bean id="transactionmanager" class="org.springframework.orm.hibernate5.hibernatetransactionmanager">
  <!-- 注入事務,session能夠管理事務,工廠能夠創(chuàng)建session -->
  <property name="sessionfactory" ref="sessionfactory"/>
 </bean>
 
 <!-- 開啟事務的注解 -->
 <tx:annotation-driven transaction-manager="transactionmanager"/>
 
 <!-- 配置客戶模塊 -->
 <!-- 強調(diào):配置的aciton,必須是多列的 -->
 <bean id="customeraction" class="com.clj.web.action.customeraction" scope="prototype">
  <!--注意:struts管理action時,基于其中有個struts-plugin的jar包,其中更改了一個
  常量struts.objectfactory.spring.autowire = name將其打開了,可以自動裝配,只需要提供set方法
  但是此時action由spring管理,自動裝配失效,所以需要手動進行配置注入
  -->
  <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"/>-->
  <!-- 這里不注入模板類,而是注入sessionfactory,因為模板需要session(封裝了session)-->
  <property name="sessionfactory" ref="sessionfactory"/>
 </bean>
 <!-- 配置模板類(hibernate框架提供的,內(nèi)部封裝了session),此時交給spring管理,如果持久層繼承了hibernatedaosupport,則無需配置-->
 <!-- <bean id="hibernatetemplate" class="org.springframework.orm.hibernate5.hibernatetemplate">
  注入sessionfactory
  <property name="sessionfactory"/>
 </bean>-->
</beans>

此時可以安心的刪除hibernate.cfg.xml文件了

這樣ssh整合完畢

六、hibernate模板常用方法

注意:以下代碼省略了接口中的演示(偷了個懶,相信初學者不會看不懂)

1)插入:

持久層

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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è)務層

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.clj.service;
 
import java.util.list;
 
import org.springframework.transaction.annotation.transactional;
 
import com.clj.dao.customerdao;
import com.clj.domain.customer;
/**
 * 客戶的業(yè)務層
 * @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);
 }
}

測試類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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;
 
/**
 * 測試hiberante模板類的簡單方法
 * @author administrator
 *
 */
@runwith(springjunit4classrunner.class)
@contextconfiguration("classpath:applicationcontext.xml")
public class demo1 {
 @resource(name="customerservice")
 private customerservice customerservice;
 /**
  * 測試插入
  */
 @test
 public void run1(){
  customer customer=new customer();
  customer.setcust_id(1l);
  customer.setcust_name("測試");
  customerservice.update(customer);
 }
 
}

2)以下為指定查詢、查詢所有、離線查詢代碼

持久層

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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ù)庫中(調(diào)用模板類(hibernate提供,內(nèi)部封裝了session))
 /*private hibernatetemplate hibernatetemplate;
 
 public void sethibernatetemplate(hibernatetemplate hibernatetemplate) {
  this.hibernatetemplate = hibernatetemplate;
 }*/
 
 /**
  * 保存客戶
  */
 public void save(customer customer) {
  system.out.println("持久層:保存客戶");
  this.gethibernatetemplate().save(customer);
 }
 
 @override
 public void update(customer customer) {
  // todo auto-generated method stub
  this.gethibernatetemplate().update(customer);
 }
 
 /**
  * 通過主鍵查詢
  */
 public customer getbyid(long id) {
  return this.gethibernatetemplate().get(customer.class, id);
 }
 /**
  * 查詢所有
  */
 @override
 public list<customer> findall() {
  string sql="from customer";
  list<customer> list=(list<customer>) this.gethibernatetemplate().find(sql);
  return list;
 }
 /**
  * qbc離線查詢
  */
 @override
 public list<customer> findallbyqbc() {
  detachedcriteria criteria=detachedcriteria.forclass(customer.class);
  list<customer> list=(list<customer>) this.gethibernatetemplate().findbycriteria(criteria);
  return list;
 }
}

業(yè)務層

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.clj.service;
 
import java.util.list;
 
import org.springframework.transaction.annotation.transactional;
 
import com.clj.dao.customerdao;
import com.clj.domain.customer;
/**
 * 客戶的業(yè)務層
 * @author administrator
 *
 */
@transactional
public class customerserviceimpl implements customerservice{
 private customerdao customerdao;
 
 public void setcustomerdao(customerdao customerdao) {
  this.customerdao = customerdao;
 }
 
 //用來保存客戶
 public void save(customer customer) {
  system.out.println("業(yè)務層,保存客戶");
  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();
 }
}

測試類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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;
 
/**
 * 測試hiberante模板類的簡單方法
 * @author administrator
 *
 */
@runwith(springjunit4classrunner.class)
@contextconfiguration("classpath:applicationcontext.xml")
public class demo1 {
 @resource(name="customerservice")
 private customerservice customerservice;
 /**
  * 測試插入
  */
 @test
 public void run1(){
  customer customer=new customer();
  customer.setcust_id(1l);
  customer.setcust_name("測試");
  customerservice.update(customer);
 }
 /**
  * 測試查詢指定的客戶
  */
 @test
 public void run2(){
  customer customer=customerservice.getbyid(2l);
  system.out.println(customer);
 }
 /**
  * 查詢所有的客戶
  */
 @test
 public void run3(){
  list<customer> list=customerservice.findall();
  system.out.println(list);
 }
 /**
  * qbc(離線查詢)
  */
 @test
 public void run4(){
  list<customer> list=customerservice.findallbyqbc();
  system.out.println(list);
 }
}

七、關于ssh延遲加載問題

1. 使用延遲加載的時候,再web層查詢對象的時候程序會拋出異常!

* 原因是延遲加載還沒有發(fā)生sql語句,在業(yè)務層session對象就已經(jīng)銷毀了,所以查詢到的javabean對象已經(jīng)變成了托管態(tài)對象!

* 注意:一定要先刪除javassist-3.11.0.ga.jar包(jar包沖突了)

2. 解決辦法

spring框架提供了一個過濾器,讓session對象在web層就創(chuàng)建,在web層銷毀。只需要配置該過濾器即可

* 但是:要注意需要在struts2的核心過濾器之前進行,spring監(jiān)聽器之后配置

?
1
2
3
4
5
6
7
8
9
<!-- 解決延遲加載的問題 -->
   <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方法,此方法時延遲加載的

?
1
2
3
4
5
6
7
8
/**
  * 延遲加載
  */
 @override
 public customer loadbyid(long id) {
  // todo auto-generated method stub
  return this.gethibernatetemplate().load(customer.class, id);
 }

業(yè)務層

?
1
2
3
4
5
@override
 public customer loadbyid(long id) {
  // todo auto-generated method stub
  return customerdao.loadbyid(id);
 }

測試類

?
1
2
3
4
5
@test
 public void run5(){
  customer customer=customerservice.loadbyid(2l);
  system.out.println(customer);
 }

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://www.cnblogs.com/cailijia52o/p/8724710.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日韩妹妹 | 小寡妇水真多好紧 | 国产精品29页 | 国产小视频免费看 | daring国家队在线观看樱花动漫 | 国产精品视频一区二区三区不卡 | 99热久久国产精品这里 | 久久久久激情免费观看 | 国产成人亚洲综合网站不卡 | 国产免费午夜 | 亚洲国产五月综合网 | 亚洲成色WWW久久网站夜月 | 向日葵视频app下载18岁以下勿看 | 免费二区| 精品丰满人妻无套内射 | 国产综合图区 | 滑进了柔佳火热紧夹的 | 好女孩韩剧免费观看 | 母性本能在线观看 | 免费久久久久 | 欧美性xxx狂流白浆 欧美性f | 欧洲网色偷偷亚洲男人的天堂 | 好大用力深一点 | 无码AV免费精品一区二区三区 | 特黄特色大片免费影院 | 日本免费一区二区三区a区 日本免费三片在线观看 | 国产一区二区三区免费在线视频 | 午夜办公室在线观看高清电影 | 动漫肉在线观看 | 91在线老师啪国自产 | 欧美成人手机 | 精品国产品香蕉在线观看75 | videos欧美肥婆 | 男人午夜禁片在线观看 | free service性v极品 | 9久热久爱免费精品视频在线观看 | 3d动漫免费 | 我的家教老师 | 天美蜜桃精东乌鸦传媒 | 亚洲高清视频网站 | 91麻豆精品国产自产在线观看 |