SSH 프레임 워크 통합
서문 : 어떤 사람들은 주류 프레임 워크가 여전히 인기가 있으며 SSH는 SSH는 물론 오랫동안 나왔다고 말합니다. 나는 그렇게 생각하지 않습니다. 오늘날 많은 회사들이 여전히 SSH를 사용하고 있으며 주류 프레임 워크로 변경되면 비용이 많이 듭니다. 예를 들어, 금융 IT 필드에서는 인터넷이 아닌 한 빠르게 개발할 수 있기 때문에 데이터베이스 계층에서 최대 절전 모드를 사용하는 것이 좋습니다. 동시성이 높기 때문에 데이터베이스 계층은 데이터 상호 작용 효율이 빠른 mybatis를 사용합니다. 따라서 SSH는 무시할 수 없습니다.
1. SSH는 무엇입니까?
SSH는 Struts+Spring+Hibernate의 통합 프레임 워크이며 현재 웹 애플리케이션에 인기있는 오픈 소스 프레임 워크입니다.
SSH 프레임 워크를 통합하는 시스템은 프레젠테이션 계층, 비즈니스 논리 계층, 데이터 지속성 계층 및 도메인 모듈 계층의 책임 측면에서 4 개의 계층으로 나뉩니다. 그중에서도 Struts는 MVC 분리를 담당하는 시스템의 전체 인프라로 사용되며 Struts 프레임 워크의 모델 부분에서 비즈니스 점프를 제어하고 최대 절차제를 사용하여 끈기 계층, 스프링 관리, 관리 및 최대 입동맥을 지원합니다. 구체적인 접근법은 다음과 같습니다. 객체 지향 분석 방법을 사용하여 요구에 따라 일부 모델을 제안하고 이러한 모델을 기본 Java 객체로 구현 한 다음 기본 DAO (데이터 액세스 객체) 인터페이스를 작성하고 DAO를 Hibernate의 구현을 제공합니다. 최대 절전 모드 아키텍처에서 구현 한 DAO 클래스는 Java 클래스와 데이터베이스 간의 변환 및 액세스를 실현하는 데 사용됩니다. 마지막으로, Spring은 Struts와 최대 절전 모드를 관리하고 관리합니다.
--------- Baidu 백과 사전
2. SSH와 관련된 부분
3. 환경의 빠른 배치
여기서는 작은 데모를 사용하여 고객을 절약하여 SSH의 통합을 보여줍니다.
1. 필요한 JAR 패키지를 가져옵니다
1). struts2 프레임 워크
* struts-2.3.24/apps/struts2-blank/web-inf/lib/*. jar- struts2에 필요한 모든 항아리 패키지
* 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은 최대 절전 모드 코어 패키지를 통합합니다
* Spring은 Struts2 코어 패키지를 통합합니다
2. web.xml에서 스프링 및 스트럿 관련 코드를 구성하십시오
1) struts2 코어 필터를 구성하십시오
이것은 모든 차단으로 정의됩니다
<!-코어 필터 구성-> <filter> <filter-name> struts2 </filter-name> <filter-class.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter </filter class> </filter> <filter-name> struts2 </filter-name> <url-pattern>/*</url-pattern> </필터 매핑>
2) 스프링 리스너를 구성하십시오
서비스가 시작되면 스프링 구성 파일이 먼저로드됩니다.
<!-스프링 프레임 워크 통합 웹-> <liseer> <layer-class> org.springframework.web.context.contextloaderListener </laiseer class> </liareer>를 구성합니다.
3) 기본 로딩 경로를 구성하십시오
<!-리스너는 기본적으로 웹 -INF 파일을로드합니다. 지정된 파일을로드하려면 매개 변수를 구성해야합니다-> <countxt-param> <param-name> contextConfigLocation </param-name> <param-value> classpath : applicationcontext.xml </param- value> </context-param>
요약 : Web.xml의 모든 코드는입니다
<!-스프링 프레임 워크에서 웹을 통합하는 리스너를 구성합니다 .-> <liseer> <layer-class> org.springframework.web.context.contextloderListener </liareterloderlistener </liarcher> <!-리스너는 기본적으로 웹 -INF 파일을로드하고 지정된 파일을로드하도록 구성해야합니다. <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-mapping> <filter-name> struts2 </filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2. SRC에서 관련 구성 파일을 쓰십시오
1) 스프링 : ApplicationContext.xml
관련 제약 조건을 가져옵니다
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.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.spramwork.org/schema/schema/schema/schema. 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/sprring.xsd 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 configuration dtd 3.0 // en" "http://www.hibernate.org/dtd/dtd/hibernatefiguration-3.0.dtd". <session-factory> <!-꼭 구성해야합니다-> <속성 이름 = "hibernate.connection.driver_class"> com.mysql.jdbc.driver </property> <property name = "hibernate.connection.url"> jdbc : mysql : //192.168.174.130 : 3306/sh </sh </property> <property 이름 = "hibernate.connection.username"> root </property </property </property name = "hibernate.connection.password"> root </property> <property name = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </property> <!-옵션 ion </propert </properation <hibernate. 이름 = "hibernate.format_sql"> true </property> <property name = "hibernate.hbm2ddl.auto"> 업데이트 </property> <!-c3p0의 연결 풀 구성-> <property name = "connection.provider_class"> org.hibernate.connection.c3p0connection.c3p0connection.c3p0connection. -> <!-구성 파일 매핑-> <매핑 자원 = "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.appender.stdout.layout.conversonversonpattern = %d { 비 ### log4j.appender.file = org.apache.log4j.fileAppenderLog4j.appender.file.file = c/: mylog.loglog4j.appender.file.layout = org.apache.log4j.patternlayoutlog4j.appender.file.layout.conversonpattern = %d {retute 비4) struts2 : struts.xml
관련 제약 조건을 가져옵니다
<? xml 버전 = "1.0"alcoding = "utf-8"?> <! doctype struts public "-// apache 소프트웨어 재단 // dtd struts configuration 2.1 // en" "http://struts.apache.org/dtds/struts-2.3.dtd "> <struts> </struts>
요약 : SRC가 요구하는 구성 파일은 그림에 표시됩니다.
3. DAO 레이어를 구성하십시오
인터페이스 및 구현 클래스를 정의하십시오
Public Interface CustomerDao {Public Void Save (고객 고객);} Public Class CustomerDaoimpl은 CustomerDao {public void save (customer customer) {}}을 구현합니다.4. 비즈니스 계층 인터페이스 및 구현 클래스를 정의합니다
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;/** * Customer's business layer* @author Administrator * */public class CustomerServiceImpl implements CustomerService{//Used to save customers public void save(Customer customer) { }}5. Pojo 클래스를 정의하십시오
최대 절전 모드는 객체 관계 매핑을 달성하기 위해 Pojo 클래스를 작동하여 데이터베이스 테이블을 작동합니다.
Com.clj.domain 패키지; 공개 클래스 고객 {private long cust_id; 개인 문자열 cust_name; Private Long Cust_user_id; Private Long Cust_create_id; 개인 문자열 cust_source; 개인 문자열 cust_industry; 개인 문자열 cust_level; 개인 문자열 cust_linkman; 개인 문자열 cust_phone; 개인 문자열 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 (문자열 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 (문자열 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 = " + cushce =", cust_source + " cust_level = " + cust_level +", cust_linkman = " + cust_linkman +", cust_phone = " + cust_phone +", cust_mobile = " + cust_mobile +"]; }}6. 고객 정의 .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/hibernate-3.0.dtd"> <Hibernate-mapping> < 이름 = "com.clj.domain.customer"table = "cst_customer"> <id name = "cust_id"column = "cust_id"> <generator/> </id> <property name = "cust_name"열 = "cust_name"/<property name = "cust_user_id"column = "custeer_id" " 열 = "cust_create_id"/> <property name = "cust_source"column = "cust_source"/<property name = "cust_industry"column = "cust_industry"/> <property name = "cust_level"열 = "cust_level"/> <property name = "cust_linkman"collect = "cust_linkman"/>. name = "cust_phone"column = "cust_phone"/> <속성 이름 = "cust_mobile"열 = "cust_mobile"/> </class> </hibernate-mapping>
프로젝트 구성 다이어그램
4. 고객 보존을위한 데모의 예비 데모
여기서 우리는 먼저 heibernate to heibernate, struts2 to struts2, 생성 인스턴스를 스프링으로 정의합니다.
1. 고객을 저장하고 양식 양식을 사용하여 데이터 제출을위한 인터페이스 정의
도메인 이름에 따르면, 우리는 Struts2의 와일드 카드 방법이 액세스에 사용됨을 알 수 있습니다.
<form id = form1 name = form1 action = "$ {pagecontext.request.contextpath} /customer_add.action"method = post> <!-테이블 부분 생략-> </form>2. struts.xml에서 수락 요청을 구성하고, 동작 이름과 방법에 따라 지정된 조치로 점프하고 지정된 방법을 실행하십시오.
Spring Integrates Struts2 Method : Action은 Struts2 프레임 워크에 의해 관리됩니다.
* 가져온 struts2-spring-plugin-2.3.24.jar 패키지에는 구성 파일 Struts-plugin.xml이 함께 제공되므로 다음 코드는 구성 파일에 포함됩니다.
* <constant name = "structs.objectFactory"value = "spring" /> 상수를 켜십시오. 상수를 켜면 다음 상수를 사용할 수 있습니다.
* struts.objectfactory.spring.autowire = 이름,이 상수는 조치가 Bean 객체를 자동으로 조립할 수있는 클래스입니다!
<? xml version = "1.0"alcoding = "utf-8"?> <! doctype struts public "-// apache 소프트웨어 재단 // dtd struts configuration 2.1 // en" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <crm "" "crm" " extends = "struts-default"네임 스페이스 = "/"> <!-고객 조치 구성-> <!-메소드 1 : Aciton은 struts2 프레임 워크-> <action name = "customer_*"method = "{1}"/> </struts>에 의해 관리됩니다.3. Spring Application Context.xml에서 해당 콩 및 트랜잭션 구성
여기에서 Spring의 IOC (Control Version) 기능을 사용하여 인스턴스 생성 작업은 Spring Framework Management에 전달됩니다.
<bean id = "customerservice"> <property name = "customerdao"ref = "customerdao"> </property> </bean> <bean id = "CustomerDao"> <property name = "hibernateTemplate"ref = "HiberNateTemplate"/</bean> <bean = "hibernateTemplate"> <property name "/<"sessionfactory ""> </bean> </beans>
4. 지속성 계층 구현 클래스 관련 코드를 쓰십시오
여기서 Hibernate가 제공하는 템플릿 클래스는 세션의 메소드를 호출 할 수 있도록 세션을 내부적으로 동봉하는 데 사용됩니다.
/** * 지속성 계층 * * @author 관리자 * */public class customer daoimpl은 customerDao {// 데이터 저장 데이터베이스 (템플릿 클래스 (hibernate, 내부 캡슐화 된 세션에 의해 제공 됨)) 개인 HibernateTemplate Hibernatemplate; public void sethibernateTemplate (HibernateTemplate HibernateTemplate) {this.hibernateTemplate = HibernateTemplate; } / *** 저장 고객* / public void save (customer customer) {system.out.println ( "영구 계층 : 고객 저장"); HibernateTemplate (). 저장 (고객); }}5. 비즈니스 계층 구현 클래스 관련 코드를 작성하십시오
패키지 com.clj.service; import org.springframework.transaction.annotation.transactional; import com.clj.dao.customerdao; import com.clj.domain.customer;/** * 고객의 비즈니스 계층 * @author 관리자 * */ @transactionalpublic customervicempl emplestments emprivation evermpy empriver empriver and custompition and custompition empriblings empribling redince remustion emprivations customervice empress; Public Void SetCustomerDao (CustomerDao CustomerDao) {this.CustomerDao = CustomerDao; } // 고객을 저장하는 데 사용되는 공개 void Save (고객 고객) {System.out.println ( "비즈니스 계층, 고객 저장"); CustomerDao.Save (고객); }}6. 조치 관련 코드를 작성하십시오
다음은 struts2의 템플릿 클래스입니다
패키지 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.clj.customer; com.clj.service.customerService; import com.opensymphony.xwork2.actionSupport; import com.opensymphony.xwork2.modeldriven;/** * 고객의 제어 계층 * @author 관리자 */public class customeraction은 Actionsupport Implements Modeldriven <customer> {// 새로운 개인 고객 (새로운 고객)을 잊지 마십시오. 공개 고객 getModel () {반환 고객; } // 서비스 멤버 속성을 제공하고 설정 방법을 제공합니다. 개인 고객 서비스 고객 서비스를 제공합니다. public void setCustomerService (CustomersOrvice 고객 서비스) {this.customerService = customerService; } / *** 고객 저장* @return* / public string add () {System.out.println ( "웹 계층, 고객 저장"); // 메소드 1 : 웹 공장 생성 (action은 struts2에 의해 생성 됨) WebApplicationContext context = webApplicationContextUtils.getWebApplicationContext (servletActionContext.getServletContext ()); CustomersIrvice CS = (CustomersOrvice) Context.GetBean ( "CustomersOrvice"); // 호출 메소드 cs.save (고객); 리턴 없음; }}5. 프로젝트 최적화의 통합
1. Spring Integration Struts2 Method 2 : Spring Framework에 의해 관리됩니다.
특정 조치 클래스 구성 파일 ApplicatonContext.xml을 구성 파일에 넣지 만 참고 : struts.xml을 수정해야합니다.
<struts> <!-패키지 구조 구성-> <패키지 이름 = "crm"extends = "struts-default"namespace = "/"> <!-고객의 조치 구성-> <!-메소드 1 : aciton은 struts2 framwork <action name = "customer_*"method = "{1}"/> ---------- 메소드가 관리됩니다. 클래스 태그에 srping configuration bean이 필요합니다-> <action name = "customer_*"method = "{1}"> </action> </package> </struts>2. ApplicationContext.xml에서 액션 클래스를 구성하십시오
참고 : 1) 스프링 프레임 워크는 기본적으로 고객 행동을 생성하고 struts2 프레임 워크는 다중입니다. 따라서 SCOPE = "프로토 타입"을 구성해야합니다.
2) 현재 Struts2의 자동 조립은 없다. 실제로, CustomersOrvice 속성을 수동으로 구성하고 액션 클래스에서 설정 메소드를 생성해야합니다.
<!-고객 모듈 구성-> <!-강조 : 구성된 Aciton은 멀티 컬럼이어야합니다 .-> <bean id = "customerAction"scope = "프로토 타입"> <!-참고 : Struts-Plugin JAR 패키지를 기반으로 액션을 관리 할 때, Struts.object.spring.spring.spring. 정해진 방법 만 제공하면됩니다. 그러나 동작은 Spring에 의해 관리되며 자동 어셈블리는 유효하지 않으므로 구성 주입-> <속성 이름 = "CustomersIrvice"ref = "CustomersOrvice"> </property> </bean>을 수동으로 수행해야합니다.
3. 트랜잭션 구성
Spring은 최대 절전 모의 방법 1 : (구성 파일과 Hibernate.cfg.xml을 포함합니다. 강조 : 현재 스레드를 바인딩하는 구성을 추가 할 수 없습니다)
과거에는 Hibernate를 재생할 때 Hibernate.cfg.xml은 Hibernate 프레임 워크에 의해 관리되었습니다. 구성 파일은 SessionFactory를 생성 할 수 있습니다. Persistence Layer는이 구성 파일을로드하여 SessionFactory를 얻으므로 공장 생성 세션을 생성하고 데이터를 추가, 삭제 및 변경합니다. 현재 구성 파일은 Spring Management에 양도되어 Spring의 IOC 특성을 최대한 활용해야합니다.
Spring Framework는 HibernatedaoSupport 도구 클래스를 제공하며, DAO가 미래에 상속받을 수 있습니다! ! 최대 절전 모드 코어 구성 파일을 소개하기 전에 DAO 계층은 상위 클래스 Hibernatedaosupport를 상속해야하며, 이는 트랜잭션 템플릿을 내부적으로 캡슐화합니다.
소스 코드를 참조하십시오 :
1) 해당 지속성 계층 구현 클래스를 수정하고 HibernatedaoSupport를 상속 받도록하십시오.
패키지 com.clj.dao; import org.springframework.orm.hibernate5.hibernateTemplate; import org.springframework.orm.hibernate5.support.support.support.support.hibernatedaosupport; import com.clj.domain.customer;/*** persistence hibernater* hibernate support* hibernate support* @Author Administrator * /Public Class Customer CustientDaoimpl은 HibernatedaoSupport를 확장합니다. CustomerDao {// 데이터를 데이터베이스에 저장합니다 (템플릿 클래스 (Hibernate, Accapsed Session에서 제공)) / *개인 HibernateTemplate Hibernatemplate; public void sethibernateTemplate (HibernateTemplate HibernateTemplate) {this.hibernateTemplate = HibernateTemplate; }*// ***고객 저장*/ public void save (customer customer) {system.out.println ( "영구 계층 : 고객 저장"); this.gethibernateTemplate (). 저장 (고객); }}2) 비즈니스 계층을 수정하고 거래 주석을 활성화하십시오
패키지 com.clj.service; import org.springframework.transaction.annotation.transactional; import com.clj.dao.customerdao; import com.clj.domain.customer;/** * 고객의 비즈니스 계층 * @author 관리자 * */ @transactionalpublic customervicempl emplestments emprivation evermpy empriver empriver and custompition and custompition empriblings empribling redince remustion emprivations customervice empress; Public Void SetCustomerDao (CustomerDao CustomerDao) {this.CustomerDao = CustomerDao; } // 고객을 저장하는 데 사용되는 공개 void Save (고객 고객) {System.out.println ( "비즈니스 계층, 고객 저장"); CustomerDao.Save (고객); }}3) ApplicationContext.xml 파일을 수정하십시오
최대 절전 모드 구성 파일을 먼저 소개하십시오
<!-쓰기 콩, 이름은 스프링에 의해 제공된 고정되어 있으며, Hibernate.cfg.xml의 구성 파일을로드하는 데 사용됩니다 .cfg.xml-> <bean id = "sessionfactory"> <!-구성 경로 : 서버가 시작되면 객체가 생성되므로 hibernate.cfg.xml 파일을로드하여 세션 이름을로드합니다. value = "classpath : hibernate.cfg.xml"/> </bean>
플랫폼 트랜잭션 관리 구성 : 트랜잭션을 관리하는 데 사용됩니다. 최대 절전 모드 프레임 워크가 사용되므로 최대 절전 모드 프레임 워크의 트랜잭션 관리자가 필요합니다.
<!-플랫폼 트랜잭션 관리자를 먼저 구성합니다-> <bean id = "transactionManager"> <!-트랜잭션 주입, 세션은 트랜잭션을 관리 할 수 있으며 공장은 세션을 생성 할 수 있습니다.
열린 거래 주석
<!-트랜잭션을 활성화하기위한 주석-> <tx : 주석 중심 트랜잭션-매너 = "TransactionManager"/>
템플릿 클래스 구성 제거 및 지속성 계층에 대한 SessionFactory 구성
<!-미래에, DAO는 HibernateDaoSupport를 상속하고 SessionFactory를 주입해야합니다-> <bean id = "customerdao"> <!-<property name = "hibernateTemplate"ref = "HiberNateTemplate"/> <!-템플릿 클래스는 여기에 주입되지 않지만 템플릿이 필요하기 때문에 session name이 필요합니다. ref = "sessionFactory"/> </bean>
모든 코드는 다음과 같습니다
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.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.spramwork.org/schema/schema/schema/schema. 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/sprring.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-쓰기 Beans를 작성하십시오. 이름은 Spring에 의해 고정되어 있으며 Hibernate.cfg.x.x의 구성 파일을로드합니다. 구성 경로 : 서버가 시작되면 객체가 생성되어 Hibernate.cfg.xml 파일을로드하여 SessionFactory 객체를 생성하여-> <property name = "configlocation"value = "classpath : hibernate.cfg.xml"/> </bean> <!-<bean id = <! <!-<bean id = "transactionmanage"> <! 거래 및 공장은 세션을 만들 수 있습니다-> <속성 이름 = "sessionFactory"ref = "sessionFactory"/> </bean> <!-트랜잭션을 활성화하기위한 주석-> <TX : 주석 중심 거래 관리-관리자 = "TransactionManager"/> <!-고객 모듈-> <!-Consigize-< ""eD = " SCOPE = "프로토 타입"> <!-참고 : Struts가 Struts-Plugin이있는 JAR 패키지를 기반으로 동작을 관리하는 경우, Constant Struts.ObjectFactory.spring.spring.spring.spring.spring.aUtowire = 자동 조립 될 수 있습니다. 정해진 방법 만 제공하면됩니다. 그러나 동작은 Spring에 의해 관리되고 자동 어셈블리가 유효하지 않으므로 구성 주입-> <속성 이름 = "CustomersErvice"ref = "CustomerErvice"> </property> </bean> <bean id = "customerservice"> <property name = "customerdao"ref = "customerdao"> </bean> <joid = "id =" "> <! 이름 = "HiberNateTemplate"ref = "HiberNateTemplate"/>-> <!-템플릿 클래스는 여기에 주입되지 않지만 세션은 세션이 필요하기 때문에 (캡슐화 된 세션)-> <property name = "sessionfactory"ref = "sessionFactory"/> </bean> <!-템플릿 클래스 (session factory) (템플릿 클래스에 제공됨”/>이 시간에 제공됩니다. Hibernatedaosupport, 구성 할 필요가 없습니다-> <!-<bean id = "HibernateTemplate"> SessionFactory <Property name = "sessionFactory"/> </bean>-> </beans>
4) 액션 클래스를 수정하십시오
비즈니스 계층 구현 클래스가 주입되기 때문에 비즈니스 계층 방법은 Bean을로드하지 않고 직접 호출 할 수 있습니다.
패키지 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.clj.customer; com.clj.service.customerService; import com.opensymphony.xwork2.actionSupport; import com.opensymphony.xwork2.modeldriven;/** * 고객의 제어 계층 * @author 관리자 */public class customeraction은 Actionsupport Implements Modeldriven <customer> {// 새로운 개인 고객 (새로운 고객)을 잊지 마십시오. 공개 고객 getModel () {반환 고객; } // 서비스 멤버 속성을 제공하고 설정 방법을 제공합니다. 개인 고객 서비스 고객 서비스를 제공합니다. public void setCustomerService (CustomersOrvice 고객 서비스) {this.customerService = customerService; } / *** 고객 저장* @return* / public string add () {System.out.println ( "웹 계층, 고객 저장"); // 메소드 1 : 웹 공장 생성 (action은 struts2에 의해 생성됩니다) /*WebApplicationContext context = webApplicationContextUtils.getWebApplicationContext (servletActionContext.getServletContext ()); CustomersIrvice CS = (CustomersOrvice) Context.GetBean ( "CustomersOrvice"); // 호출 메소드 cs.save (고객); */ customerservice.save (고객); 리턴 없음; }}Spring Integration Hibernate Method Two : (Hibernate.cfg.xml없는 구성 파일)
여기서 우리는 Hibernate의 핵심 구성 파일을 삭제합니다. 삭제하기 전에 구성 파일의 관련 내용을 Spring의 ApplicationIntext.xml 파일로 구성하여 가져와야합니다.
1. Hibernate.cfg.xml 파일에서 관련 내용을 확인하십시오
* 데이터베이스 연결의 기본 매개 변수 (4 가지 주요 매개 변수)
* 최대 절전 모드 관련 특성
* 연결 풀
*지도 파일
2. 구성을 소개합니다
연결 풀을 소개합니다
<!-C3P0의 연결 풀을 구성합니다. first-> <bean id = "dataSource"> <property name = "driver class"value = "com.mysql.jdbc.driver"/> <property name = "jdbcurl"value = "jdbc : mysql : //192.168.174.130 : 3306/shs" "" "" "" "" "" "" "" "" "" "" "" " 값 = "루트"/> <속성 이름 = "비밀번호"value = "root"/> </bean>
해당 SessionFactory 수정 : Hibernate.cfg.xml에 대한 구성 파일이 없으므로 구성을 수정하고 연결 풀을 주입해야합니다.
객체 매핑 파일을 소개합니다. Hibernate.cfg.xml의 구성 파일이 더 이상 스캔되지 않고 구성 파일을 주입해야하기 때문입니다.
<!-쓰기, 이름은 고정되어 있으며 Spring이 Hibernate.cfg.xml의 구성 파일을로드하기 위해 Spring에 의해 제공됩니다.> <bean id = "sessionfactory"> <!-연결 풀을 최초로로드합니다.> <속성 이름 = "dataSource"ref = "DataSource"/> <-로드 변증법,로드 옵션 = "<propletipe"> <propls ". 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.aut"> props> </props> <!-매핑 구성 파일을 소개합니다-> <속성 이름 = "MappingResources"> <list> <value> com/clj/domain/customer.hbm.xml </value> </list> </property> </bean>
이제 : ApplicationContext.xml 코드는 다음과 같습니다
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.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.spramwork.org/schema/schema/schema/schema. 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/sprring.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-C3P0 First-> <Bean ID ="DataSource "> <특성 이름을 구성하십시오."Driver Class " 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"root "/bean> </bean> </bean" hibernate.cfg.xml의 구성 파일을로드하려면 <bean id = "sessionfactory"> <!-연결 풀을로드합니다. 첫 번째-> <속성 이름 = "dataSource"ref = "DataSource"/> <!-로드 방언,로드 옵션-> <속성 이름 = "HibernateProperties"> <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.aut"> props> </props> <!-매핑 구성 파일을 주입-> <속성 이름 = "mappingResources"> <list> <value> com/clj/domain/domain/customer.hbm.xml </value> </list> </bean> <!-플랫폼 트랜잭션 관리자 First-> <bean id = "TransactionManager">-세션을 관리 할 수 있습니다. 이름 = "sessionFactory"ref = "sessionFactory"/> </bean> <!-트랜잭션-매너를 열기위한 주석은 "TransactionManager"/> <!-고객 모듈 구성-> <!-강조 : 구성된 Aciton은 멀티 컬럼이어야합니다-> <Bean id = "customerAction"scope = "proctopte"> <! <! constant struts.objectfactory.spring.autowire = 이름이 켜져 자동 조립 될 수 있습니다. 설정 방법 만 제공하면됩니다. However, the action is managed by spring and the automatic assembly is invalid, so you need to manually perform configuration injection--> <property name="customerService" ref="customerService"></property> </bean> <bean id="customerService"> <property name="customerDao" ref="customerDao"></property> </bean> <!-- In the future, Dao needs to inherit HibernateDaoSupport and inject sessionFactory --> <bean id="customerDao"> <!--<property name="hibernateTemplate" ref="hibernateTemplate"/> -> <!-- The template class is not injected here, but sessionFactory, because the template needs session (encapsulated session)--> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- Configure the template class (provided by the hibernate framework, encapsulated session) and is handed over to spring management at this time. 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을 더 지원하기를 바랍니다.