Spring (10)----SSH Framework Integration

Source: Internet
Author: User
Tags aop ssh

Review:

1. How to Annotate AOP
Writing slice classes (including notifications and pointcuts)
Turn on automatic proxy
2. JDBC Template Technology
Spring provides template technology, database operation
After you write the DAO layer, you can inherit the Jdbcdaosupport class (JDBC template)
Spring Framework consolidates open source connection pools
3. Spring Transaction Management
Spring Framework transaction management requires interfaces and an overview
Platformtransactionmanager Interface (Platform transaction manager Interface), this class must be configured regardless of the way the transaction is managed:
Manual Coding (Learn)
Declarative transaction management (focus), by default using AOP technology to enhance
The way of XML
How to Annotate


SSH Integrated Data

Configuration files required by SSH three-frame

1. STRUTS2 Framework

* Configure the core filter in Web. xml

<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>
* Create a struts.xml in the SRC directory to configure the action
2. Hibernate Framework

* Create hibernate.cfg.xml configuration file in src directory
* Configuration file mapped under the package where the JavaBean is located

3. Spring Framework

* Create Applicationcontext.xml in src directory

* Under the SRC directory log4j.proerties

* Configure the integrated Web listener on the XML.

<listener>
	<listener-class>org.springframework.web.context.contextloaderlistener</ listener-class>
</listener>
<context-param>
	<param-name>contextconfiglocation </param-name>
	<param-value>classpath:applicationContext.xml</param-value>
</ Context-param>
I. Spring Framework integrated STRUTS2 Framework

1. Import the CRM Project's UI page, find the page to add the customer, modify the form form, access the action



Writing the Action class

public class Customeraction extends Actionsupport {

	private static final long Serialversionuid = 7334305113638651338 L;

	Public String Add () {
		System.out.println ("Web tier: Save Customer ...");
		return NONE;
	}
}
Configure Struts.xml
<struts>
	<package name= "CRM" namespace= "/" extends= "Struts-default" >

		<!--Configure customer action--
		<action name= "customer_*" class= "com.ken.web.CustomerAction"
			method= "{1}" ></action>
	</package>

</struts>



The action receives a request from the front end, and the next step is to invoke the service layer.

Create service interfaces and classes.

Then, configure the service bean in Applicationcontext.xml

<!--configuring customer modules--
<bean id= "customerservice" class= "Com.ken.service.CustomerServiceImpl" >

< /bean>
Action invokes the service through the Web factory


Process: The server starts, the Contextloaderlistener in Web. XML executes, and the Applicationcontext.xml is loaded. All bean configurations in the applicationcontext.xml will be parsed. The bean is then created, and the default is singleton. Then, take it from the container through the Web factory. Once you get it, the next time you use it, you don't have to load the config file again, just take it directly from the factory.

Get to service in action (development will not be used because of trouble)
Can be passed Webapplicationcontextutils.getwebapplicationcontext (Servletactioncontext.getservletcontext ()); To get it, but it's too cumbersome to write code in this way.

The first way spring consolidates the STRUTS2 framework (action is created by the STRUTS2 framework)

In action, add:

Private CustomerService CustomerService;

public void Setcustomerservice (CustomerService customerservice) {
	this.customerservice = customerservice;
}
You can use it directly. Because, Struts2-spring-plugin-2.3.24.jar helped us to inject it automatically.




As soon as the action provides a set method for a variable, the Struts framework helps us to fetch the bean by name from the Spring factory.

The action's class is configured in Struts.xml, so the action object is created by the STRUTS2 framework and is multi-instance, and one request creates an action object.

Spring's second approach to consolidating the STRUTS2 framework (action created by the spring framework)

(Recommended for everyone to use)

In the above method, the action object is created by the STRUTS2 framework. The core IOC of our spring is responsible for the creation of objects and the management of dependencies. Then the action can also be created by spring. Then, we can inject the service directly. The advantage is that Action,service,dao, all objects are managed by spring.

The practice is:

First, configure the action in the Applicationcontext.xml.


So here's the problem, we've also configured this action in Struts.xml, and we're going to create the object for this action.


How to do it.


Note that the action is in multiple cases and is to be configured in Applicationcontext.xml.


When the action is given to spring to manage, the automatic injection fails. We want to inject the service manually.


ii. Spring Framework Integration Hibernate Framework

1. Write the Customerdaoimpl code, add the configuration and complete the injection in the Customerserviceimpl



The next step is to consider how the DAO layer operates the database.

We use hibernatetemplate and it needs a session. The final operational database is the use of Session.get (), Session.save () and other methods.

We can use the new Hibernatetemplate object in the method of the DAO layer. The following figure:


However, we use spring to do the integration. So, we're going to give the template object to spring to manage.



If we want to use a template class, we have to inject something into it.


Our DAO implementation class can inherit Hibernatedaosupport, which helps us to provide hibernatetemplate member variables and set methods.






2.1 configuration file with Hibernate.cfg.xml

2. Write the mapped configuration file and introduce the mapped profile in the Hibernate.cfg.xml configuration file

3. In Applicationcontext.xml configuration file, configure the configuration to load the Hibernate.cfg.xml

<!--write bean, name is fixed, load hibernate.cfg.xml configuration file--
<bean id= "sessionfactory" class= " Org.springframework.orm.hibernate5.LocalSessionFactoryBean ">
	<property name=" configlocation "value=" Classpath:hibernate.cfg.xml "/>
</bean>
Localsessionfactorybean is used to load hibernate's core configuration files and, by the way, helps us build sessionfactory objects. So, we generally set its ID value to sessionfactory.
Process: When we start the server, the object just configured will be created. As soon as it is created, Hibernate's core configuration file is loaded. Then, according to the configuration file information, to generate a Sessionfactory object. The Sessionfactory object can create a session. Sessionfactory are heavyweight, not easily created and destroyed. Well, our configuration is just right, we start the server, create the Sessionfactory object, this object is in memory. As long as the server is not shut, it has been alive.

We inject the Sessionfactory object into the DAO's implementation class. In DAO's implementation class, you only need to use hibernatetemplate. Because the hibernatetemplate the session is encapsulated. The bottom, or the session is doing.

4. In Customerdaoimpl, to complete the addition of data, the spring Framework provides a Hibernatedaosupport tool class that can later be inherited by Dao

5. Turn on the configuration of the transaction


Configure the transaction manager first, note that the Hibernate framework is now in use, so you need to use the Hibernate framework's transaction manager. A transaction is managed by another session. Sessionfactory can produce session. So, we inject sessionfactory into the transaction manager.

<!--first configure the platform transaction manager--
<bean id= ""
	class= " Org.springframework.orm.hibernate5.HibernateTransactionManager ">
	<property name=" sessionfactory "ref=" Sessionfactory "/>
</bean>
Opening annotation Transactions
<tx:annotation-driven transaction-manager= "TransactionManager"/>
Adding transaction annotations in the service class
@Transactional
SSH integration with hibernate config file code 2.2 configuration file without Hibernate.cfg.xml

Without the Hibernate.cfg.xml configuration file, the contents of this configuration file will be transferred to the Applicationcontext.xml file.

Hibernate core configuration file contains: Database of 4 large parameters, C3P0 connection pool. Our spring can integrate the C3P0 connection pool. So, these two parameters are done. Also, database dialect, optional configuration (Show_sql, Format_sql, Hbm2ddl.auto), mapping files.

1. Configure connection pool-related information first

<!--first configure C3P0 Connection pool--
<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" >
	<property name= "Driverclass" value= "Com.mysql.jdbc.Driver"/>
	<property name= "Jdbcurl" value= "JDBC: Mysql:///ssh_inte1 "/>
	<property name=" user "value=" root "/>
	<property name=" password "value=" 123456 "/>
</bean>
The purpose of our Hibernate core profile is to create sessionfactory. We can also create sessionfactory in spring, through Localsessionfactorybean.

2. Modify the Localsessionfactorybean property configuration because there is no hibernate.cfg.xml configuration file, so you need to modify the configuration to inject the connection pool

3. In Localsessionfactorybean configuration, use the Hibernateproperties property to continue to configure other properties, note that the value is the Properties property file


<!--write the bean, the name is fixed, load the Hibernate.cfg.xml configuration file--
<!--before the load Hibernate.cfg.xml. Now, we cancel the hibernate core configuration file, as configured below--
<bean id= "sessionfactory"
	class= " Org.springframework.orm.hibernate5.LocalSessionFactoryBean ">
	<!--First load connection pool-
	<property name=" DataSource "ref=" DataSource "/>
	<!--loading dialect, loading 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 a mapped profile--
	<property name= "mappingresources" >
		<list>
			<value >com/ken/domain/Customer.hbm.xml</value>
		</list>
	</property>
</bean>
SSH integration, without hibernate.cfg.xml
The current code is not bound to the current thread's code. If there is, then the error. Because, we are now using Localsessionfactorybean, which is provided by spring. It helps us to produce the session, will be responsible for the management session, and generated a session of a proxy object. So, now the session is not maintained by hibernate. The session is now created by spring. Therefore, you cannot configure an operation that is bound to the current thread.
Iii. Common methods of Hibernate templates

1. The operation of adding or deleting changes
Add: Save (Object obj); Modified: Update (Object obj); Delete: Delete (Object obj); 2. Operation of the query
Query a record:
Object Get (Class c,serializable ID); Object load (Class c,serializable ID); 3. Querying multiple records: List find (String hql,object ... args);


4.QBC mode query All

Findbycriteria (Detachedcriteria criteria, ...)

Offline conditional query. We can prepare the conditions ahead of time and then pass them in as parameters.

See above, the parameter list has int firstrresult, int maxResults, it is suitable for paging query.

/**
 * QBC, query all
 *
/@Override public
list<customer> FINDALLBYQBC () {
	Detachedcriteria Criteria = Detachedcriteria.forclass (customer.class);
	Set the condition query
	list<customer> List = (list<customer>) this.gethibernatetemplate (). Findbycriteria ( criteria);
	return list;
}
Offline conditions, why is called offline. Because this object is not created by the session, it is our own new one, so it can be placed on any level. Iv. delayed loading issues


Create the Loadbyid method in action and create it separately on the service and DAO layers, with the DAO layer code as follows:


Access this interface:



This is a package conflict:


After the package has been deleted, again accessed, there is another exception:


The Load method is lazy loading. Lazy loading, when you use the properties of it will not send SQL statements.


The reason is that SQL statements are only issued when System.out.println (c). However, this time the session has been destroyed, the session is destroyed, you can not send SQL.


The web layer invokes the service layer. Once the service layer is requested, the service will help us create a session and manage the transaction. The service then calls the DAO layer. In the DAO layer, the Load method, deferred loading, does not go to the database surface to look up data, and the object returned to the service layer (proxy object) has only one ID. The service returns the object to the Web layer and closes the session. After the web layer gets the object (the proxy object), the print operation is performed, and the client's attributes are used to send SQL, but the session is closed. I will report this mistake:

Org.hibernate.LazyInitializationException:could not initialize Proxy-no Session
Solutions 1: Do not use lazy loading, then the first query when all the attributes are detected.


Adding lazy= "false" will not delay loading. We delay loading to improve the performance of the program. So how do we do it better.

Solution 2: The spring Framework provides a filter that allows session objects to be created at the Web layer and destroyed at the Web layer. You only need to configure the filter. However, be aware of the need to configure before struts2 core filters

<!--solve problems with lazy loading-
<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>
Look at the name: Open session in view, the session opens in the view layer. That is, the session is opened on the web layer.

Ssh_inte2 Template Common Methods & deferred loading issues


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.