SSHフレームワーク統合
序文:一部の人々は、主流のフレームワークが今でも人気があり、SSMはSSHはもちろん、長い間外出していると言っています。私はそうは思わない。現在、多くの企業がまだSSHを使用しており、それらが主流のフレームワークに変更すると、コストがかかります。たとえば、金融IT分野では、インターネットでない限り、迅速に開発できるため、データベースレイヤーでHibernateを使用することをお勧めします。高い並行性を伴うため、データベースレイヤーはMyBatisを使用します。これは、データ相互作用の効率が高速であることです。したがって、SSHは無視できません。
1。sshとは何ですか
SSHは、Struts+Spring+Hibernateの統合フレームワークであり、現在、Webアプリケーションに人気のあるオープンソースフレームワークです。
SSHフレームワークを統合するシステムは、プレゼンテーションレイヤー、ビジネスロジックレイヤー、データの永続性レイヤー、ドメインモジュールレイヤーの責任の観点から4つのレイヤーに分割されます。その中で、Strutsはシステムの全体的なインフラストラクチャとして使用され、MVCの分離を担当し、Strutsフレームワークのモデル部分で、ビジネスジャンプを制御し、Hibernate Frameworkを使用して持続層のサポートを提供し、Spring Manage、Manage、Hibernateをサポートします。特定のアプローチは、オブジェクト指向の分析方法を使用して、ニーズに応じていくつかのモデルを提案し、これらのモデルを基本的なJavaオブジェクトとして実装し、Basic DAO(Data Access Objects)インターフェイスを作成し、HibernateのDAO実装を提供します。 Hibernateアーキテクチャによって実装されたDAOクラスは、Javaクラスとデータベース間の変換とアクセスを実現するために使用されます。最後に、SpringはStrutsとHibernateを管理および管理します。
---------- Baidu Encyclopedia
2。SSHに関与する部品
3。環境の迅速な展開
ここでは、小さなデモを使用して顧客を保存して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のプラグインパッケージを統合します
2)。冬眠フレームワーク
* hibernate-release-5.0.7.final/lib/required/*.jar-hibernateフレームワークで必要なJARパッケージ
* SLF4J-API-1.6.1.jar-ログインターフェイス
* SLF4J-LOG4J12-1.7.2.JAR-ログ実装
* mysql-connector-java-5.1.7-bin.jar-mysqlドライバーパッケージ
3)。スプリングフレームワーク
* IOCコアパッケージ
* AOPコアパッケージ
* JDBCテンプレートとトランザクションコアパッケージ
* SpringはJunitテストパッケージを統合します
* Springは、Hibernate Coreパッケージを統合します
* SpringはStruts2コアパッケージを統合します
2。Web.xmlでSprut関連コードを構成します
1)Struts2コアフィルターを構成します
これは、すべてをインターセプトするものとして定義されます
<! - コアフィルターを構成 - > <filter> <filter-name> struts2 </filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter </filter-crass> </filter> <フィルターマッピング<url-pattern>/*</url-pattern> </フィルターマッピング>
2)スプリングリスナーを構成します
サービスが開始されると、Spring構成ファイルが最初にロードされます
<! - Webを統合するSpring Frameworkのリスナーを構成 - > <リスナー> <リスナークラス> org.springframework.web.context.contextloaderlistener </ristener-class> </ristener>
3)デフォルトの読み込みパスを構成します
<! - リスナーはデフォルトでWeb-INFファイルをロードします。指定されたファイルをロードするパラメーターを構成する必要があります - > <context-param> <param-name> contextconfiglocation </param-name> <param-value> classpath:applicationcontext.xml </param-value> </context-param> </context-param>
概要:web.xmlのすべてのコードはです
<! - スプリングフレームワークにWebを統合するリスナーを構成します - > <リスナー> <リスナークラス> org.springframework.web.context.contextloaderlistener </ristenerlistener </ristener> <! - リスナーは、デフォルトでWeb-infファイルをロードし、指定されたファイルをロードするための構成パラメーターを実行する必要があります - > <param-name> contextconfiglocation </param-name> <param-value> classpath:applicationcontext.xml </param-value> </context-param> <! - Configure core filters-> <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
関連する制約をインポートします
<?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 = " 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/ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> </beans>
2)Hibernate:hibernate.cfg.xml
関連する制約をインポートし、データベースを構成します
<?xml version = "1.0" encoding = "utf-8"?> <!doctype hibernate-configuration public " - // hibernate/hibernate構成<! - configure-> <プロパティ名= "hibernate.connection.driver_class"> com.mysql.jdbc.driver </property> <Property name = "hibernate.connection.url"> jdbc:mysql://192.168.174.130:3306/ssh </propiction name = "hibernate.connection.username"> root </property> <property name = "hibernate.connection.password"> root </property> <property name = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </property> < name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Configure connection pool for C3P0 --> <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!-- Cannot configure operations that bind the currentスレッド - > <! - マッピング構成ファイル - > <マッピングリソース= "com/clj/domain/customer.hbm.xml"/> </session-factory> </hibernate-configuration>
3)log4j.propertiesを構成します
### stdoutにログメッセージを直接### log4j.appender.stdout = org.apache.log4j.consoleappenderlog4j.appender.stdout.target = system.errlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.apptern.stdout.layout.conurs.patrut.conurs.patrut.conurs.conurs.patrut. %c {1}:%l -%m%n ### file mylog.logへの直接メッセージ### log4j.appender.file = org.apache.log4j.fileappenderlog4j.appender.file.file = c/:mylog.loglog4j.appender.file.layout = org.apache.log4j.patternlayoutlog4j4j4j {daptern.patrut.conurs.conurs.conurs.patrut.conurs %c {1}:%l-%m%n ###ログレベルを設定 - 詳細記録のために「debug」に「情報」を変更する### log4j.rootlogger = info、stdout4)Struts2:struts.xml
関連する制約をインポートします
<?xml version = "1.0" encoding = "utf-8"?> <!doctype struts public " - // apacheソフトウェア財団// dtd struts構成
概要:SRCが必要とする構成ファイルを図に示します
3。DAOレイヤーを構成します
インターフェイスとその実装クラスを定義します
パブリックインターフェイスcustomerdao {public void save(顧客顧客);}パブリッククラスのcustomerdaoimplを実装するcustomerdao {public void save(顧客顧客){}}4.ビジネスレイヤーインターフェイスと実装クラスを定義します
パッケージcom.clj.service;インポートcom.clj.domain.customer; public interface customerservice {public void save(customer Customer);}パッケージcom.clj.service; Import org.springframework.transaction.annotation.transactional; import com.clj.dao.customerdao; Import com.clj.domain.customer;/** *顧客のビジネスレイヤー * @author管理者 */パブリッククラスの顧客boidervice boidervice(顧客boidervice(顧客) }}
5. Pojoクラスを定義します
Hibernateは、POJOクラスを操作してオブジェクトリレーショナルマッピングを実現することにより、データベーステーブルを操作します
パッケージcom.clj.domain;パブリッククラスの顧客{private long cust_id;プライベート文字列cust_name; Private long Cust_user_id;プライベートcust_create_id;プライベート文字列cust_source; private string cust_industry;プライベート文字列cust_level;プライベート文字列cust_linkman;プライベート文字列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_surs + " cust_level = " + cust_level +"、cust_linkman = " + cust_linkman +"、cust_phone = " + cust_phone +"、cust_mobile = " + cust_mobile +"] "; }}6. customer.hbm.xmlを定義します
この構成ファイルは、顧客POJOクラスに関連しています。このファイルは、顧客Pojoクラスと同じパッケージの下に配置する必要があります
<?xml version = "1.0" encoding = "utf-8"?> <!doctype hibernate-mapping public " - // hibernate/hibernateマッピングdtd 3.0 // en" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> name = "com.clj.domain.customer" table = "cst_customer"> <id name = "cust_id" column = "cust_id"> <generator/> </id> <property name = "cust_name" column = "cust_name"/> <property name = "cust_user_id" column = "cust_user_id"/> <cust_id "cust_id" cust_id "列= "cust_create_id"/> <プロパティ名= "cust_source" column = "cust_source"/> <property name = "cust_industry" column = "cust_industry"/> <プロパティ名= "cust_level" column = "cust_level"/>> <プロパティ名= "cust_linkman" column " name = "cust_phone" column = "cust_phone"/> <プロパティname = "cust_mobile" column = "cust_mobile"/> </class> </hibernate-mapping>
プロジェクト構築図
4.顧客の保存のためのデモの予備的なデモ
ここでは、最初に刑事の持続層、struts2のビジネス層、および春の作成インスタンスを定義します
1.顧客を保存するインターフェイスを定義し、フォームフォームを使用してデータを送信します
ドメイン名によると、struts2のワイルドカード法がアクセスに使用されていることがわかります。
<form id = form1 name = form1 action = "$ {pagecontext.request.contextpath}/customer_add.action" method = post> <! - テーブルパート省略 - > </form>2。struts.xmlでリクエストを受け入れ、アクション名とメソッドに従って指定されたアクションにジャンプし、指定されたメソッドを実行する
spring統合struts2メソッド1:アクションはstruts2フレームワークによって管理されます
*インポートされたstruts2-spring-plugin-2.3.24.jarパッケージには構成ファイルstruts-plugin.xmlが付属しているため、次のコードが構成ファイルに含まれています
* <constant name = "structs.objectfactory" value = "spring" />定数をオンにします。定数がオンになっている場合、次の定数を使用できます
* struts.objectfactory.spring.autowire = name、この定数は、アクションがBeanオブジェクトを自動的に組み立てることを可能にするクラスです!
<?xml version = "1.0" encoding = "utf-8"?> <!doctype struts public " - // apacheソフトウェア財団// dtd struts構成2.1 // en" "http://struts.apache.org/dtds/struts-2.3.dtd" extends = "struts-default" namespace = "/"> <! - configure customer action-> <! - method 1:acitonはstruts2フレームワークによって管理されます - > <アクションname = "customer_*" method = "{1}"/> </package> </struts>3。Spring ApplicationContext.xmlで対応する豆とトランザクションを構成します
ここでは、春にIOC(Control Inversion)機能を使用して、インスタンスを作成するタスクがSpringフレームワーク管理に引き渡されます
<bean id = "customerservice"> <プロパティ名= "customerdao" ref = "customerdao"> </property> </bean id = "customerdao"> <property name = "hibernateTemplate" ref = "hibernateTemplate"/>> </bean> <bean id = "higbernateToryedplate"> < name = "sessionfactory"/> </bean> </bean>
4. Persistence Layerの実装クラス関連コードを書き込みます
ここでは、Hibernateが提供するテンプレートクラスを使用してセッションを内部的に囲み、セッションのメソッドを呼び出すことができます。
/** Persistence Layer * * @Author Administrator * */Public Class CustomerDaoImplはCustomerDaoを実装します{//データベースにデータを保存します(テンプレートクラスを呼び出します(Hibernateによって提供され、カプセル化されたセッション)プライベートHibernateTemplate hibernateTemplate; public void sethibernateTemplate(hibernateTemplate hibernateTemplate){this.hibernateTemplate = hibernateTemplate; } / *** customer* / public void save(customer customer){system.out.println( "permanent layer:save customer"); hibernateTemplate()。save(customer); }}5.ビジネスレイヤー実装クラス関連コードを書き込みます
パッケージcom.clj.service; Import org.springframework.transaction.annotation.transactional; import com.clj.dao.customerdao; Import com.clj.domain.customer;/** *顧客のビジネスレイヤー * @author管理者 */ @transactionalpublic customerpublic customerpublice customerdaerdaer public void setcustomerdao(customerdao customerdao){this.customerdao = customerdao; } //顧客のpublic void saveを保存するために使用されます(顧客顧客){system.out.println( "business layer、save the Customer"); customerdao.save(customer); }}6.アクション関連コードを書き込みます
これがStruts2のテンプレートクラスです
パッケージcom.clj.web.action; Import org.apache.struts2.servletactionContext; Import org.springframework.web.context.webapplicationcontext; import org.springframework.web.context.support.webapplicationcontextils; Import com.clj.clj.clj.domain.customer; com.clj.service.customerservice; Import com.opensymphony.xwork2.actionsupport; Import com.opensymphony.xwork2.modeldriven;/** * customer's Control layer * @author Administrator * */public class Customeractions extends ActionSupport Imprements Modeldiven> {customer> {/not ond ond customer> Public Customer getModel(){customerを返します。 } //サービスメンバーの属性を提供し、設定されたメソッドを提供しますプライベート顧客サービス顧客サービス。 public void setCustomerService(customerservice customerservice){this.customerservice = customerservice; } / *** customer* @return* / public string add(){system.out.println( "web layer、save the Customer"); //方法1:Web Factory(actionはstruts2によって作成されます)を作成しますwebapplicationcontext context = webapplicationcontextutils.getwebapplicationContext(servletactionContext.getServletContext()); customerservice cs =(customerservice)context.getBean( "customerservice"); //メソッドCs.Save(顧客)を呼び出す;なしなし; }}5。プロジェクトの最適化の統合
1。SpringIntegration Struts2 Method 2:アクションはSpring Frameworkによって管理されます
特定のアクションクラスの構成ファイルapplicatoncontext.xmlを構成ファイルに配置しますが、注:struts.xmlを変更する必要があります
<Struts> <! - パッケージ構造の構成 - > <パッケージname = "crm" extends = "struts-default" namespace = "/"> <! - configure customer's action-> <! - acitonはstruts2フレームワーク<アクションname = "customer_*" method = "{1}}" beanはクラスタグに必要です - > <アクションname = "customer_*" method = "{1}"> </action> </package> </struts>2。ApplicationContext.xmlでアクションクラスを構成します
注:1)Spruts2フレームワークは複数である一方で、スプリングフレームワークはデフォルトで顧客アクションを生成します。したがって、scope = "prototype"を構成する必要があります
2)現時点では、struts2の自動アセンブリはありません。アクションでは、customerserviceプロパティを手動で構成し、アクションクラスでSETメソッドを生成する必要があります。
<設定された方法を提供するだけです。ただし、アクションは春までに管理されており、自動アセンブリは無効であるため、構成インジェクションを手動で実行する必要があります - > <プロパティ名= "customerservice" ref = "customerservice"> </property> </bean>
3。トランザクションを構成します
SpringはHibernateメソッド1を統合します:( hibernate.cfg.xmlを使用した構成ファイル。
過去には、hibernateをプレイするとき、hibernate.cfg.xmlはHibernateフレームワークによって管理されていました。その構成ファイルは、SessionFactoryを生成できます。 Persistenceレイヤーは、この構成ファイルをロードしてSessionFactoryを取得し、ファクトリ生成セッションを作成し、データを追加、削除、変更します。この時点で、その構成ファイルはSpring Managementに引き渡され、SpringのIOC特性を最大限に活用する必要があります。
Spring Frameworkは、DAOによって将来的に継承できるHibernatedAoSupportツールクラスを提供します! ! Hibernate Core構成ファイルを導入する前に、DAOレイヤーは、トランザクションテンプレートを内部的にカプセル化する親クラスHibernatedAoSupportを継承する必要があります。
ソースコードを参照してください:
1)対応する永続性レイヤー実装クラスを変更し、冬眠装置を継承させます
パッケージcom.clj.dao; import org.springframework.orm.hibernate5.hibernateTemplate; Import org.springframework.orm.hibernate5.support.hibernatedaosupport; Import com.clj.domain.customer;/** Import com.clj.domain.customer;/**内部 * @Author Administrator * * /Public Class CustomerDaoImplは冬眠装置を拡張しますcustomerdao {//データをデータベースに保存(hebernate、capsupsulated 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)ビジネスレイヤーを変更し、トランザクション注釈を有効にします
パッケージcom.clj.service; Import org.springframework.transaction.annotation.transactional; import com.clj.dao.customerdao; Import com.clj.domain.customer;/** *顧客のビジネスレイヤー * @author管理者 */ @transactionalpublic customerpublic customerpublice customerdaerdaer public void setcustomerdao(customerdao customerdao){this.customerdao = customerdao; } //顧客のpublic void saveを保存するために使用されます(顧客顧客){system.out.println( "business layer、save the Customer"); customerdao.save(customer); }}3)ApplicationContext.xmlファイルを変更します
最初にHibernate構成ファイルを紹介します
< value = "classpath:hibernate.cfg.xml"/> </bean>
プラットフォームトランザクション管理の構成:トランザクションの管理に使用されます。 Hibernate Frameworkが使用されるようになったため、Hibernateフレームワークのトランザクションマネージャーが必要であることに注意してください。
<! - プラットフォームトランザクションマネージャーを最初に構成 - > <bean id = "transactionmanager"> <! - セッションはトランザクションを管理でき、工場はセッションを作成できます - > <プロパティ名= "SessionFactory" Ref = "SessionFactory"/> </bean> </bean>
オープントランザクションアノテーション
<! - トランザクションを有効にするための注釈 - > <TX:Annotation-driven Transaction-Manager = "TransactionManager"/>
テンプレートクラスの構成を削除し、永続性レイヤーのためにSessionFactoryを構成します
<! - 将来、DAOは冬眠装置を継承し、SessionFactoryを挿入する必要があります - > <bean id = "CustomerDao"> <! - <Property name = "hibernateTemplate" ref = "hibernateTemplate"/> <! - テンプレートクラスはここで注入されていませんが、テンプレートのニーズが描かれています。 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 = " 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/ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-書き込み豆、名前は修正されており、スプリングが提供され、hibernate.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfg.cfの構成ファイルをロードするために提供されます。 <! - 構成パス:サーバーが起動すると、オブジェクトが作成され、hibernate.cfg.xmlファイルがロードされ、セッション構成オブジェクトが生成されます - > <プロパティ名= "configlocation" value = "classpath:hibernate.cfg.xml"/>> </bean> <!セッションはトランザクションを管理でき、工場はセッションを作成できます - > <プロパティ名= "SessionFactory" Ref = "SessionFactory"/> </bean> <! - トランザクションを有効にするためのアノテーション - > <tx:annotation-driven transaction-manager = "transactionmanager"/>> <! - 顧客モジュール - > <> <> <be-colnize- id = "customeraction" scope = "prototype"> <! - 注:struts-pluginを使用したJARパッケージに基づいてアクションを管理する場合、一定のstruts.objectfactory.spring.autowire =名前が変更され、自動的に組み立てられます。設定された方法を提供するだけです。ただし、アクションは春までに管理されており、自動アセンブリは無効であるため、構成インジェクションを手動で実行する必要があります - > <プロパティ名= "customerservice" ref = "customerservice"> </property> </bean> <bean id = "customerservice" name = "hibernateTemplate" ref = "hibernateTemplate"/> - > <! - テンプレートクラスはここで注入されませんが、セッションファクターです。レイヤーはHibernatedAoSupportを継承します、構成する必要はありません - > <! - <bean id = "hibernateTemplate"> inject SessionFactory <Property name = "SessionFactory"/> </bean> - > </beans>
4)アクションクラスを変更します
ビジネス層の実装クラスが注入されるため、ビジネス層法は、この時点で豆を積み込むことなく直接呼び出すことができます
パッケージcom.clj.web.action; Import org.apache.struts2.servletactionContext; Import org.springframework.web.context.webapplicationcontext; import org.springframework.web.context.support.webapplicationcontextils; Import com.clj.clj.clj.domain.customer; com.clj.service.customerservice; Import com.opensymphony.xwork2.actionsupport; Import com.opensymphony.xwork2.modeldriven;/** * customer's Control layer * @author Administrator * */public class Customeractions extends ActionSupport Imprements Modeldiven> {customer> {/not ond ond customer> Public Customer getModel(){customerを返します。 } //サービスメンバーの属性を提供し、設定されたメソッドを提供しますプライベート顧客サービス顧客サービス。 public void setCustomerService(customerservice customerservice){this.customerservice = customerservice; } / *** customer* @return* / public string add(){system.out.println( "web layer、save the Customer"); //方法1:Web Factory(actionはstruts2によって作成されます) /*webapplicationcontext context = webapplicationcontextutils.getwebapplicationContext(servletactionContext.getServletextext()); customerservice cs =(customerservice)context.getBean( "customerservice"); //メソッドCs.Save(顧客)を呼び出す; */ customerservice.save(customer);なしなし; }}Spring Integration Hibernateメソッド2 :( hibernate.cfg.xmlなしの構成ファイル)
ここでは、Hibernateのコア構成ファイルを削除します。削除する前に、springのapplicationincontext.xmlファイルにその構成ファイルに関連するコンテンツを構成して取得する必要があります。
1. hibernate.cfg.xmlファイルの関連コンテンツを確認します
*データベース接続の基本パラメーター(4つの主要なパラメーター)
* Hibernate関連の特性
*接続プール
*ファイルをマップします
2。構成を紹介します
接続プールを紹介します
<! - c3p0の接続プールを構成しますfirst-> <bean id = "datasource"> <プロパティ名= "driverclass" value = "com.mysql.jdbc.driver"/> <プロパティ名= "jdbcurl" value = "jdbc:mysql://192.168.174.130:" 3306/> <ユーザーvalue = "root"/> <プロパティname = "password" value = "root"/> </bean>
対応するSessionFactoryを変更する:hibernate.cfg.xmlの構成ファイルがないため、構成を変更して接続プールを挿入する必要があります。
オブジェクトマッピングファイルの導入:hibernate.cfg.xmlの構成ファイルがスキャンされなくなり、構成ファイルを挿入する必要があるためです。
<! - beanを書き込み、名前は固定されており、springによって提供され、hibernate.cfg.xmlの構成ファイル - > <bean id = "sessionfactory"> <! - 接続プールファースト - > <プロパティ名= "dataSource" ref = "dataSource"/> 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"> </proppecto <! - マッピング構成ファイルの紹介 - > <プロパティ名= "MappingResources"> <list> <value> com/clj/domain/customer.hbm.xml </value> </list> </property> </bean> </bean>
ここ: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 = " 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/ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <! - c3p0の接続プールを構成しますc3p0 first-> <bean id =" datasource "> value = "com.mysql.jdbc.driver"/> <プロパティ名= "jdbcurl" value = "jdbc:mysql://192.168.174.130:3306/ssh"/>> <プロパティ名= "ユーザー" value = "root"/> <プロパティ= springによって提供されてhibernate.cfg.xmlの構成ファイルをロードするために提供 - > <bean id = "sessionfactory"> <! - connection pool first-> <property name = "datasource" ref = "dataSource"/> <! - ロード方言、ロードオプション - > <プロパティname = <props> <props> <props> <props> 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"> </proppecto <! - マッピング構成ファイルを挿入 - > <プロパティ名= "MappingResources"> <list> <value> com/clj/domain/customer.hbm.xml </value> </list> </パイプロパティ> </bean> <! - プラットフォームトランザクションマネージャーファースト> <bean id = "transaction manager"> <! - > <プロパティname = "SessionFactory" ref = "SessionFactory"/> </bean> <! - Opening Transaction-Manager = "TransactionManager"/> <! - 顧客モジュールの構成 - > <! - 強調:構成されたアシトンはマルチコラムである必要があります - > <bean id = "customer customeraction" Struts-Plugin、一定のstruts.objectfactory.spring.autowire =名前がオンになり、自動的に組み立てることができます。設定された方法を提供するだけです。ただし、アクションは春までに管理されており、自動アセンブリは無効であるため、構成噴射を手動で実行する必要があります - > <プロパティ名= "customerservice" ref = "customerservice"> </property> </bean> <bean id = "customerservice" HibernatedAoSupportおよびInject SessionFactory-> <Bean Id = "CustomerDao"> <! - <プロパティ名= "hibernateTemplate" ref = "/> - > <! - テンプレートクラスはここで注入されませんが、セッションファクターはセッションファクトリー(セッションセッション)(cessapsory"/> <"propetities" ref "" "> <" "reaptory" ref "festuctory」 </bean> <! - テンプレートクラス(Hibernateフレームワーク、カプセル化セッションによって提供)を構成し、この時点でSpring Managementに引き渡されます。 If the persistence layer inherits HibernateDaoSupport, there is no need to configure --> <!-- <bean id="hibernateTemplate"> Inject sessionFactory <property name="sessionFactory"/> </bean>--></beans>
此时可以安心的删除hibernate.cfg.xml文件了
这样SSH整合完毕
六、Hibernate模板常用方法
注意:以下代码省略了接口中的演示(偷了个懒,相信初学者不会看不懂)
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;/** * Persistence layer* Inherits HibernateDaoSupport and encapsulates HibernateTemplate internally * @author Administrator * */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public void update(Customer customer) { // TODO Auto-generated method stub this.getHibernateTemplate().update(customer); }}ビジネス層
package com.clj.service;import java.util.List;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * Customer's business layer* @author Administrator * */@Transactionalpublic 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); }}测试类
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;/** * Simple way to test Hiberante template class* @author Administrator * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo1 { @Resource(name="customerService") private CustomerService customerService; /** * Test insert*/ @Test public void run1(){ Customer customer=new Customer(); customer.setCust_id(1L); customer.setCust_name("test"); customerService.update(customer); }}2)以下为指定查询、查询所有、离线查询代码
永続的なレイヤー
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;/** * Persistence layer* Inherits HibernateDaoSupport and encapsulates HibernateTemplate internally * @author Administrator * */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { //Save data to the database (call template class (provided by hibernate, encapsulated session)) /*private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; }*/ /** * Save customer*/ public void save(Customer customer) { System.out.println("Permanent layer: save customer"); this.getHibernateTemplate().save(customer); } @Override public void update(Customer customer) { // TODO Auto-generated method stub this.getHibernateTemplate().update(customer); } /** * Query by primary key*/ public Customer getById(Long id) { return this.getHibernateTemplate().get(Customer.class, id); } /** * Query all*/ @Override public List<Customer> findAll() { String sql="from Customer"; List<Customer> list=(List<Customer>) this.getHibernateTemplate().find(sql); return list; } /** * QBC offline query*/ @Override public List<Customer> findAllByQBC() { DetachedCriteria criteria=DetachedCriteria.forClass(Customer.class); List<Customer> list=(List<Customer>) this.getHibernateTemplate().findByCriteria(criteria); return list; }}ビジネス層
package com.clj.service;import java.util.List;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * Customer's business layer* @author Administrator * */@Transactionalpublic class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } // Used to save customers public void save(Customer customer) { System.out.println("Business layer, save customer"); 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(); }}测试类
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;/** * Simple way to test Hiberante template class* @author Administrator * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo1 { @Resource(name="customerService") private CustomerService customerService; /** * Test insert*/ @Test public void run1(){ Customer customer=new Customer(); customer.setCust_id(1L); customer.setCust_name("test"); customerService.update(customer); } /** * Test query the specified customer*/ @Test public void run2(){ Customer customer=customerService.getById(2L); System.out.println(customer); } /** * Query all customers*/ @Test public void run3(){ List<Customer> list=customerService.findAll(); System.out.println(list); } /** * QBC(offline query) */ @Test public void run4(){ List<Customer> list=customerService.findAllByQBC(); System.out.println(list); }}七、关于SSH延迟加载问题
1. 使用延迟加载的时候,再WEB层查询对象的时候程序会抛出异常!
* 原因是延迟加载还没有发生SQL语句,在业务层session对象就已经销毁了,所以查询到的JavaBean对象已经变成了托管态对象!
* 注意:一定要先删除javassist-3.11.0.GA.jar包(jar包冲突了)
2。解決策
Spring框架提供了一个过滤器,让session对象在WEB层就创建,在WEB层销毁。只需要配置该过滤器即可
* 但是:要注意需要在struts2的核心过滤器之前进行,spring监听器之后配置
<!-- 解决延迟加载的问题--> <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、演示延迟加载
持久层:调用load方法,此方法时延迟加载的
/** * Lazy load*/ @Override public Customer loadById(long id) { // TODO Auto-generated method stub return this.getHibernateTemplate().load(Customer.class, id); }ビジネス層
@Override public Customer loadById(long id) { // TODO Auto-generated method stub return customerDao.loadById(id); }测试类
@Test public void run5(){ Customer customer=customerService.loadById(2L); System.out.println(customer); }上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。