SSH framework integration
Preface: Some people say that the mainstream framework is still popular now, and SSM has been out for a long time, let alone SSH. I don't think so. Nowadays, many companies still use ssh, and if they change to mainstream frameworks, it will cost. For example, in the financial IT field, it is recommended to use hibernate in the database layer because it can be developed quickly, unless it is the Internet. Because it involves high concurrency, the database layer uses mybatis, which has faster data interaction efficiency. Therefore, SSH cannot be ignored.
1. What is SSH
SSH is an integrated framework of struts+spring+hibernate, and is currently a popular open source framework for web applications.
The system integrating the SSH framework is divided into four layers in terms of responsibilities: presentation layer, business logic layer, data persistence layer and domain module layer to help developers build web applications with clear structure, good reusability and convenient maintenance in the short term. Among them, Struts is used as the overall infrastructure of the system, responsible for the separation of MVC, and in the model part of the Struts framework, controlling business jumps, using the Hibernate framework to provide support for the persistence layer, Spring manages, manages struts and hibernate. The specific approach is: use object-oriented analysis methods to propose some models according to needs, implement these models as basic Java objects, then write the basic DAO (Data Access Objects) interface, and give the DAO implementation of Hibernate. The DAO class implemented by the Hibernate architecture is used to realize the conversion and access between Java classes and databases. Finally, Spring manages and manages struts and hibernate.
---------- Baidu Encyclopedia
2. The parts involved in SSH
3. Rapid deployment of the environment
Here we use a small demo to save customers to demonstrate the integration of SSH
1. Import the required jar package
1). Struts2 framework
* struts-2.3.24/apps/struts2-blank/WEB-INF/lib/*.jar -- All jar packages required by Struts2
* struts2-spring-plugin-2.3.24.jar ---Struts2 integrates Spring's plug-in package
2). Hibernate framework
* hibernate-release-5.0.7.Final/lib/required/*.jar -- jar package required by Hibernate framework
* slf4j-api-1.6.1.jar -- Log interface
* slf4j-log4j12-1.7.2.jar -- Log implementation
* mysql-connector-java-5.1.7-bin.jar -- MySQL driver package
3). Spring Framework
* IOC Core Package
* AOP core package
* JDBC templates and transaction core packages
* Spring integrates JUnit test package
* Spring integrates Hibernate core package
* Spring integrates Struts2 core package
2. Configure spring and struts related code in web.xml
1) Configure struts2 core filter
This is defined as intercepting all
<!-- Configure core filter --> <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) Configure the spring listener
When the service starts, the spring configuration file will be loaded first
<!-- Configure the listener for the Spring framework integrating WEB--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
3) Configure the default loading path
<!-- The listener loads the Web-INF file by default. You need to configure parameters to load the specified file --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value></context-param>
Summary: All codes for web.xml are
<!-- Configure the listener that integrates WEB in the Spring framework --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- The listener loads the Web-INF file by default, and requires configuration parameters to load the specified file --> <context-param> <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. Write relevant configuration files under src
1) spring:applicationContext.xml
Import related constraints
<?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
Import relevant constraints and configure the database
<?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> <!-- Must configure--> <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> <!-- Optional configuration--> <property name="hibernate.show_sql">true</property> <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 thread --> <!-- Mapping configuration file --> <mapping resource="com/clj/domain/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>
3) Configure log4j.properties
### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.errlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file mylog.log ###log4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=c/:mylog.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.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, stdout4) struts2: struts.xml
Import related constraints
<?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>
Summary: The configuration file required by src is shown in the figure
3. Configure the dao layer
Define an interface and its implementation class
public interface CustomerDao { public void save(Customer customer);} public class CustomerDaoImpl implements CustomerDao { public void save(Customer customer) { }}4. Define the business layer interface and implementation class
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. Define the pojo class
Hibernate operates database tables by operating pojo classes to achieve object-relational mapping
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. Define Customer.hbm.xml
This configuration file is related to the Customer pojo class. This file needs to be placed under the same package as the Customer pojo class
<?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/> </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_linkman"/> <property name="cust_phone" column="cust_phone"/> <property name="cust_mobile" column="cust_mobile"/> </class> </hibernate-mapping>
Project construction diagram
4. Preliminary demonstration of demo for preservation of customers
Here we first define the persistence layer to heibernate, the business layer to struts2, and the creation instance to spring
1. Define an interface to save customers and use form forms to submit data
According to the domain name, we can see that the wildcard method of struts2 is used for access.
<FORM id=form1 name=form1 action="${pageContext.request.contextPath }/customer_add.action" method=post> <!--table part omitted--></FORM>2. Configure accept requests in struts.xml, jump to the specified action according to the action name and method, and execute the specified method
Spring integrates struts2 method one: action is managed by struts2 framework
* Because the imported struts2-spring-plugin-2.3.24.jar package comes with a configuration file struts-plugin.xml, the following code is included in the configuration file
* <constant name="structs.objectFactory" value="spring" /> Turn on a constant. If the constant is turned on, the following constant can be used
* struts.objectFactory.spring.autoWire = name, this constant is a class that allows Action to automatically assemble Bean objects!
<?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> <!-- Configure package structure--> <package name="crm" extends="struts-default" namespace="/"> <!-- Configure customer action --> <!-- Method 1: aciton is managed by struts2 framework--> <action name="customer_*" method="{1}"/> </package> </struts>3. Configure the corresponding beans and transactions in spring applicationContext.xml
Here, using the IOC (control inversion) feature in spring, the task of creating an instance is handed over to the spring framework management
<bean id="customerService"> <property name="customerDao" ref="customerDao"></property> </bean> <bean id="customerDao"> <property name="hibernateTemplate" ref="hibernateTemplate"/> </bean> <bean id="hibernateTemplate"> <!-- Inject sessionFactory --> <property name="sessionFactory"/> </bean></beans>
4. Write persistence layer implementation class related code
Here, the template class provided by hibernate is used to enclose the session internally, so that the method in the session can be called.
/** * Persistence layer* * @author Administrator * */public class CustomerDaoImpl implements CustomerDao { //Save data to the database (call template class (provided by hibernate, encapsulated session internally)) 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"); hibernateTemplate().save(customer); }}5. Write business layer implementation class related code
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 * */@Transactionalpublic class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } //Used to save the customer public void save(Customer customer) { System.out.println("Business layer, save the customer"); customerDao.save(customer); }}6. Write action-related code
Here is the template class of struts2
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;/** * Customer's control layer* @author Administrator * */public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{ //Don't forget to manually new private Customer customer=new Customer(); public Customer getModel() { return customer; } //Provide service member attributes and provide set method private CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } /** * Save the customer* @return */ public String add(){ System.out.println("WEB layer, save the customer"); //Method 1: Create the web factory (action is created by struts2) WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext()); CustomerService cs=(CustomerService) context.getBean("customerService"); //Calling method cs.save(customer); return NONE; } }5. Integration of project optimization
1. Spring integration struts2 method 2: action is managed by spring framework
Put the specific Action class configuration file applicatonContext.xml in the configuration file, but note: struts.xml needs to be modified
<struts> <!-- Configure package structure--> <package name="crm" extends="struts-default" namespace="/"> <!-- Configure customer's Action --> <!-- Method 1: Aciton is managed by struts2 framework<action name="customer_*" method="{1}"/>---> <!-- Method 2: Action is managed by spring, and only the ID value of the srping configuration bean is required on the class tag--> <action name="customer_*" method="{1}"></action> </package></struts>2. Configure the Action class in applicationContext.xml
Note: 1) The Spring framework generates CustomerAction by default, while the Struts2 framework is multiple. So you need to configure scope="prototype"
2) There is no automatic assembly of struts2 at this time. In action, you need to manually configure the customerService property and generate the set method in action class.
<!-- Configure customer module --> <!-- Emphasize: The configured Aciton must be multi-column --> <bean id="customerAction" scope="prototype"> <!-- Note: When struts manage actions, based on a struts-plugin jar package, which changes a constant struts.objectFactory.spring.autoWire = name to turn it on, and it can be automatically assembled. You only need to provide a set method. 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>
3. Configure transactions
Spring integrates hibernate method one: (Configuration file with hibernate.cfg.xml. Emphasize: The configuration that binds the current thread cannot be added)
In the past, when playing hibernate, hibernate.cfg.xml was managed by the hibernate framework. Its configuration file can generate sessionFactory. The persistence layer loads this configuration file to obtain sessionFactory, thereby creating a factory generated session, adding, deleting and changing data into. At this time, its configuration file should be handed over to spring management, making full use of spring's IOC characteristics.
The Spring framework provides a HibernateDaoSupport tool class, which can be inherited in the future by DAO! ! Before introducing the hibernate core configuration file, the dao layer must inherit a parent class HibernateDaoSupport, which encapsulates the transaction template internally.
See the source code:
1) Modify the corresponding persistence layer implementation class and let it inherit HibernateDaoSupport
package com.clj.dao;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 the data to the database (call the template class (provided by hibernate, encapsulated session)) /*private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; }*/ /** * Save the customer*/ public void save(Customer customer) { System.out.println("Permanent layer: save the customer"); this.getHibernateTemplate().save(customer); }}2) Modify the business layer and enable transaction annotations
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 * */@Transactionalpublic class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } //Used to save the customer public void save(Customer customer) { System.out.println("Business layer, save the customer"); customerDao.save(customer); }}3) Modify the applicationContext.xml file
Introduce the hibernate configuration file first
<!-- Write beans, the names are fixed, provided by spring, used to load the configuration file of hibernate.cfg.xml --> <bean id="sessionFactory"> <!-- Configuration path: When the server is started, the object will be created, thus loading the hibernate.cfg.xml file, thereby generating the sessionFactory object --> <property name="configLocation" value="classpath:hibernate.cfg.xml"/></bean>
Configure platform transaction management: used to manage transactions. Note that the Hibernate framework is now used, so the transaction manager of the Hibernate framework is needed.
<!-- Configure the platform transaction manager first --> <bean id="transactionManager"> <!-- Inject transactions, the session can manage transactions, and the factory can create session --> <property name="sessionFactory" ref="sessionFactory"/> </bean>
Open transaction annotation
<!-- Annotation to enable transaction--> <tx:annotation-driven transaction-manager="transactionManager"/>
Remove template class configuration and configure sessionFactory for persistence layer
<!-- 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>
All codes are as follows
<?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"> <!-- Write beans, the names are fixed, and are provided by spring to load the configuration file of hibernate.cfg.xml --> <bean id="sessionFactory"> <!-- Configuration path: When the server is started, the object will be created, thus loading the hibernate.cfg.xml file, thereby generating the sessionFactory object --> <property name="configLocation" value="classpath:hibernate.cfg.xml"/> </bean> <!-- Configure the platform transaction manager first-> <bean id="transactionManager"> <!-- Inject transactions, the session can manage transactions, and the factory can create session --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- Annotation to enable transactions --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- Configure customer modules --> <!-- Emphasize: The configured Aciton must be multi-column --> <bean id="customerAction" scope="prototype"> <!--Note: When struts manages actions, based on a jar package with struts-plugin, a constant struts.objectFactory.spring.autoWire = name is changed to turn it on, and it can be automatically assembled. You only need to provide a set method. 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> <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> <!-- The template class (property name="sessionFactory"/> is provided 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>
4) Modify the action class
Because the business layer implementation class is injected, the business layer method can be called directly at this time without loading the bean
package com.clj.web.action;import org.apache.struts2.ServletActionContext;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;import com.clj.domain.Customer;import com.clj.service.CustomerService;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;/** * Customer's control layer* @author Administrator * */public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{ //Don't forget to manually new private Customer customer=new Customer(); public Customer getModel() { return customer; } //Provide service member attributes and provide set method private CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } /** * Save the customer* @return */ public String add(){ System.out.println("WEB layer, save the customer"); //Method 1: Create the web factory (action is created by struts2) /*WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext()); CustomerService cs=(CustomerService) context.getBean("customerService"); //Calling method cs.save(customer); */ customerService.save(customer); return NONE; }}Spring integration hibernate method two: (configuration file without hibernate.cfg.xml)
Here we are going to delete the core configuration file of hibernate. Before deleting, you need to configure the relevant content in its configuration file to spring's applicationinContext.xml file to get it.
1. Check the relevant content in the hibernate.cfg.xml file
* Basic parameters of database connection (4 major parameters)
* Hibernate-related properties
* Connection pool
* Map files
2. Introduce configuration
Introduce connection pool
<!-- Configure the connection pool for C3p0 first-> <bean id="dataSource"> <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>
Modify the corresponding sessionFactory: Because there is no configuration file for hibernate.cfg.xml, you need to modify the configuration and inject the connection pool.
Introduce object mapping file: Because the configuration file of hibernate.cfg.xml is no longer scanned, and the configuration file needs to be injected.
<!-- Write beans, the names are fixed, and are provided by spring to load the configuration file of hibernate.cfg.xml --> <bean id="sessionFactory"> <!--Load the connection pool first-> <property name="dataSource" ref="dataSource"/> <!--Load dialect, load options--> <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> <!-- Introduce mapping configuration files--> <property name="mappingResources"> <list> <value>com/clj/domain/Customer.hbm.xml</value> </list> </property> </bean>
Now: the applicationContext.xml code is as follows
<?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"> <!-- Configure the connection pool for C3p0 first-> <bean id="dataSource"> <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> <!-- Write beans, the names are fixed, and are provided by spring to load the configuration file of hibernate.cfg.xml--> <bean id="sessionFactory"> <!-- Load the connection pool first-> <property name="dataSource" ref="dataSource"/> <!-- Load dialect, load options--> <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> <!-- Inject the mapping configuration file --> <property name="mappingResources"> <list> <value>com/clj/domain/Customer.hbm.xml</value> </list> </property> </bean> <!-- Configure the platform transaction manager first-> <bean id="transactionManager"> <!-- Inject transactions, the session can manage transactions, and the factory can create sessions --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- Annotation for opening transaction-manager="transactionManager"/> <!-- Configure customer module--> <!-- Emphasize: The configured Aciton must be multi-column --> <bean id="customerAction" scope="prototype"> <!-- Note: When struts manage actions, based on a jar package with a struts-plugin, a constant struts.objectFactory.spring.autoWire = The name has turned on it and can be automatically assembled. You only need to provide the set method. 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>
At this time, you can safely delete the hibernate.cfg.xml file
This way the SSH integration is complete
6. Common methods for Hibernate templates
Note: The following code omits the demonstration in the interface (I'm lazy, I believe beginners won't understand it)
1) Insert:
Persistent layer
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); }}Business layer
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); }}Test class
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) The following are the specified query, query all, offline query codes
Persistent layer
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; }}Business layer
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(); }}Test class
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层查询对象的时候程序会抛出异常!
* 原因是延迟加载还没有发生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方法,此方法时延迟加载的
/** * 延迟加载*/ @Override public Customer loadById(long id) { // TODO Auto-generated method stub return this.getHibernateTemplate().load(Customer.class, id); }Business layer
@Override public Customer loadById(long id) { // TODO Auto-generated method stub return customerDao.loadById(id); }Test class
@Test public void run5(){ Customer customer=customerService.loadById(2L); System.out.println(customer); }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.