Spring makes Hibernate users

xiaoxiao2021-03-06  14

Spring also provides support for Hibernate and JDO, which supports HibernateTemplate classes and JDEMPLATE classes similar to the JDBCTemplate class, and HibernateInterceptor classes, JDointerceptor classes, and Hibernate, JDO transaction management classes. The most important purpose is to distinguish the level of the application, and deliver data access and transaction processing with application objects. All business objects no longer rely on data access or transaction policies. No more hard-coded resource lookup code, no longer have a single case object, no longer need a custom service registration. All individual data access features do not require Spring, which can be used separately without letting Spring know, and can also be assembled through Spring application configuration (providing an XML-based configuration and cross-references to ordinary JavaBean instances). In a typical Spring application, most important objects are ordinary JavaBean: Data Access Templates, Data Access Objects (Objects to Template Objects with Data), Transaction Management Objects and Business Objects (Use Data Access Objects and Transaction Objects), the web represents an exploded object, the web control object (objects of the business object), and more. 2. Resource definition in Application Confinition To avoid application objects hard coding, Spring allows a bean to be defined as a JDBC DataSource or Hibernate SessionFactory in the application configuration. Applications If you need access to resources, you only need to receive a reference to the previously defined instance by a bean reference (DAO definition in the next section). The following content references from an application configuration definition, showing how to create a JDBC Datasource and a Hibernate's sessionFactory:

jdbc / myds Product.hbm.xml net.sf.hibernate.diaalect.mysqldiaalect ... Note The selection is to locate the data source in JNDI or get a data source from a local definition like Jakarta Commons DBCP BasicDataSource. Just a change of changing configuration:

org.hsqldb.jdbcdriver jdbc: hsqldb: hsql: // localhost: 9001 You can also use a JNDI to find sessionFactory, but usually do not need for applications other than EJB environments ( Refer to the discussion of the "Container Resources VS Local Resources"). 3. Inversion control: The basic programming mode of the template and the callback template is like you will see below, as for the method, as the method of any custom data access object or the object of the service. In addition to providing it to provide a Hibernate's sessionFactory, there is no limit to the trust of the object around the object. Although it is best to use a bean reference from a Spring application configuration to obtain it, but then you can get it from anywhere. Subsequent reference fragments include a configuration in the Spring application configuration to the DAO definition, which references examples in which the SESSIONFACTORY, and a DAO method are implemented.

...

Public Class ProductDaoImpl Implements Productda {

Private sessionFactory sessionFactory;

Public void setsessionFactory (sessionFactory sessionFactory) {

THIS.SESSIONFACTORY = sessionFactory;

}

Public List loadProductSBycategory (FINAL STRING CATEGORY) {

HibernateTemplate HibernateTemplate =

New HibernateTemplate (this.SessionFactory);

Return (List) HibernateTemplate.execute (

New hibernateCallback () {

Public Object DoinHibernate (session session) throws hibernateException {list result = session.find (

"From test.product product where produter =?",

Category, Hibernate.String;

// do some further stuff with the result list

Return Result;

}

}

);

}

} A callback implementation can be effectively used in any Hibernate data access. In any case, it is managed by HibernateTemplate to manage the session and automatic multi-party transactions. Template instances are thread security and reusable, so they can do variables for other classes. For simple single steps, like Find, Load, SaveorUpdate, or delete, HibernateTemplate provides a more convenient choice to replace the callback of a row. In addition, Spring provides a convenient basic class, which is the HibernatedAosupport class that provides a SetSessionFactory method to accept a sessionFactory while providing the GetSessionFactory and gethibernateTemplate methods for its inheritance class. Combine these, allowing a very simple DAO implementation for typical needs:

Public Class ProductDaoImpl Extends Hibernatedaosupport IMPLEments Productda {

Public List loadProductSBycategory (String category) {

Return gethibernateTemplate (). Find

"from test.product product where product.category =?", category,

Hibernate.string;

}

4. Apply an AOP interceptor instead of a template in addition to another option other than HibernateTemplate is use Spring's AOP HibernateInterceptor. Use the Hibernate code directly in a delegated TRY / CATCH block, and cooperate with the corresponding interceptor configuration in the application configuration instead of the callback. The following segment shows the respective definitions of DAO, Interceptor, and Proxy in a Spring application configuration, and give an example of a DAO method implementation:

...

Class = "org.springframework.orm.hibernate.hibernateInterceptor">

Product.ProductDao

MyHibernateInterceptor

MyProductDaotarget

...

Public Class ProductDaoImpl Extends Hibernatedaosupport IMPLEments Productda {

Public List LoadProductSbycategory (FINAL STRING CATEGORY) THROWS MyException {

Session session = sessionFactoryUtils.getations (GetSessionFactory (), False;

Try {

List result = session.find (

"From test.product product where produter =?",

Category, Hibernate.String;

IF (result == null) {

Throw New MyException ("Invalid Search Result");

}

Return Result;

}

Catch (HibernateException EX) {

Throw sessionFactoryUtils.ConvertHibernateAccessException (ex);

}

}

}

This method will only work normally when there is a HibernateInterceptor that it works, and HibernateInterceptor is the turn off after the opening and method call of the SESSION in the process before the method calls. The "false" flag in the GetSession method is to confirm that the session must already exist. If no one session is found, SessionFactoryUtils will create one for it. If there is already a session handle binding on this thread, such as binding by a HibernateTransactionManager transaction, in any case, SessionFactoryUTils will automatically access this session. HibernateTemplate also uses SessionFactoryUtils on the ground, which is basically the same as the above way. The main benefit of HibernateInterceptor is that it allows the Checked Application Exception in the data access code, and HibernateTemplate can only throw unchecked Exceptions due to the restricted callback. Note that this we can postpone their own inspections while throwing the application exception after the callback. The main disadvantage of intercepting methods is that it needs special configurations in the configuration. HibernateTemplate is a simple and easy way in most cases. 5. The program transaction is divided on this underlying data access service, and transaction can be divided on a higher application layer to form some operations. There is no restriction in addition to a Spring's PlatformTransactionManager object, there is no restrictions. Similarly, you can get them anywhere, but it is more suitable via the setTransactionManage method via the stepTransactionManage method, like ProductDao to get the same via a setProductDao method. The following reference fragment shows the definition of transaction management objects and business objects in a Spring application configuration, and also provides an example of a business method implementation:

...

Class = "org.springframework.orm.hibernate.hibernateTransactionManager">

Public Class ProductServiceImpl Implements PRODSERVICE {

Private PlatformTransactionManager TransactionManager;

Private Productdao Productdao; Public Void SetTransactionManager (PlatformTransactionManager TransactionManager) {

THIS.TRANSACTIONMANAGER = TransactionManager;

}

Public void setProductdao (ProductDao Productdao) {

THIS.PRODUCTDAO = PRODUCTDAO;

}

Public Void IncreasePRiceOfallProductSIncategory (FINAL STRING CATEGORY) {

TransactionTemplate TransactionTemplate =

New TransactionTemplate (this.TransactionManager);

TransactionTemplate.SetPropagationBehavior (TransactionsDefinition.propagation_required);

TransactionTemplate.execute (

New TransactionCallbackwithOutResult () {

Public void dointransactionwithoutResult (TransactionsTatus Status) {

List productstochange = productdao.loadproductsbycategory (category);

...

}

}

);

}

} 6. Declarative transaction division We can also choose AOP TransactionInterceptor using Spring by defining interceptor configurations in application configuration instead of transaction division code. This allows us to keep business objects independently of repeated transaction classification code in each business object. In addition, changes in transaction behavior and isolation hierarchy can be changed through a profile without affecting the implementation of business objects.

...

Class = "org.springframework.orm.hibernate.hibernateTransactionManager">

Class = "Org.springframework.transaction.interceptor.transactionintercePtor">

Product.ProductService.Increaseprice * = PropAgation_required

Product.ProductService.SOMEOTHERBUSINESSMETHOD = Propagation_Mandatory

Product.ProductService

MyTransactionInterceptor

MyProductServentArget

Public Class ProductServiceImpl Implements PRODSERVICE {

Private productdao productda;

Public void setProductdao (ProductDao Productdao) {

THIS.PRODUCTDAO = PRODUCTDAO;

}

Public Void IncreasePRiceOfallProductSIncategory (FINAL STRING CATEGORY) {

List productStochange = this.productdao.loadProductSbycategory (category);

...

}

} As with HibernateInterceptor as, TransactionInterceptor in allowing any checked application exception is thrown from the callback code, while TransactionTemplate restricted in its interior by a callback throw unchecked exceptions, in the event of an exception is the case when the unchecked application, or TransactionTemplate this will lead to a rollback The transaction is labeled rollback by the application (through the transaction). TransactionInterceptor is also the same behavior by default, but allowing rollback policies to each method. A convenient way to establish a declarative transaction is to use TransactionProxyFactoryBean, especially if there is no other AOP interceptor, TransactionProxyFactoryBean will jointly define the transaction configured for the agent's own and a special target bean. This will reduce the configuration of a proxy bean corresponding to a target bean. In addition, you don't have to specify which interface or which class must define a transaction method.

...

Class = "org.springframework.orm.hibernate.hibernateTransactionManager">

Class = "org.springframework.transaction.interceptor.TransactionProxyFactoryBean">

PropAgation_required

Propagation_mandatory

7. Hibernate transaction management strategies for applications, whether or TransactionTemplate TransactionInterceptor are commissioned to verify the actual transaction PlatformTransactionManager instance, may be a HibernateTransactionManager (of a single Hibernate SessionFactory using a ThreadLocal Session) or may be a JTATRRANSACTIONMANAGER (JTA subsystem of the proxy container). Even you can use a custom PlatformTransactionManager implementation. If you choose to transfer transaction management from a local Hibernate transaction to be managed by JTA, for example, when your application is deployed, it is just a matter of changing the configuration. Just simply change Hibernate's transaction management to JTA transaction implementation. All transactional division and data access can continue to work without any changes, because they are all ordinary transaction management APIs. For distributed transactions spanning multiple Hibernate's Session Factories, just United JTATRRRANSACTIONMANAGERs are just as transaction policies as a transaction policy. Every DAO will get a special sessionFactory reference through their respective bean properties. If all this is in the following JDBC data source is a transactional container, a business object can divide a transaction across a lot of Dao and a lot of Session Factories without having to do special processing, is the same for using JTATRRRRRANSACTIONMANAGER as a transaction strategy.

JDBC / MYDS1

JDBC / MYDS2

Class = "org.springframework.orm.hibernate.localsessionFactoryBean">

product.hbm.xml

net.sf.hibernate.dialect.mysqldiaforct

Class = "org.springframework.orm.hibernate.localsessionFactoryBean">

inventory.hbm.xml

net.sf.hibernate.dialect.OracledgeALect

Class = "org.springframework.transaction.jta.jtatransactionmanager" />

Class = "org.springframework.transaction.interceptor.TransactionProxyFactoryBean>

PropAgation_required

Propagation_mandatory

Whether HibernateTransactionManager or JTATRRANSACTIONMANAGER allows appropriate to Hibernate's JVM hierarchical cache processing - no container - provide special transaction lookup or JCA connector (not using EJB initiating transactions). In addition, HibernateTransactionManager outputs a JDBC connection for usual JDBC access code. This allows the transaction partitioning at a high level to mix Hibernate and JDBC without JTA, as long as it is just accessing a database! 8. A Spring application configuration definition that uses the Spring management app can be loaded by multiple configurations, from FileSystemxmlapplicationContext and ClassPathXMLApplicationContext to XMLWebApplicationContext. This allows you to re-use Spring management data access and business objects in a variety of environments. By default, a web app will have its own definition root configuration in "Web-INF / ApplicationContext.xml". In any Spring application, an application configuration defines all related beans for applications in an XML format to assemble, from Hibernate's session factory to custom data access and business objects (like all Beans above Like that). Most of them don't need a Spring container to know them, even if they work together with other beans, because they are just a collaboration between JavaBean. The following bean definition may be part of a Spring Web's MVC configuration to access the configuration of the business object.

Spring WEB Controller The BEAN is referenced to all of the services and data access objects they need, so they do not need to do any manual bean lookup in the application configuration. But when using Spring Manage Beans is used for Struts or in an EJB implementation, or when an applet is used to manually find a bean. Therefore, Spring's beans can be used anywhere. Perhaps just need to be a reference to an application configuration, or create it from a servlet configuration property of a web container, or from a file or class path resource. ApplicationContext context = WebApplicationContextUtils.GetWebApplicationContext (servletContext);

ProductService ProductService =

(ProductService) Context.getBean ("MyProductService");

ApplicationContext context =

New filesystemxmlapplicationContext ("c: /mycontext.xml);

ProductService ProductService =

(ProductService) Context.getBean ("MyProductService");

ApplicationContext context =

New classpathxmlapplicationContext ("MyContext.xml");

ProductService ProductService =

("MyProductService"); 9. Container Resource VS Local Resource Spring resource management allows you to choose between JNDI SessionFactory and a local sessionFactory, etc. Allow in a JNDI DataSource and local DataSource No need to change the application's code. Saving resource definitions in the container is still preserved locally, mainly a transaction policy. Compare a local sessionFactory with a Spring and a manually registered JNDI SessionFactory without any benefits. If you register through the JCA connector through Hibernate, there will be a significant benefit to join the JTA transaction, especially for EJB. The advantage of an important Spring transaction is that it is not bound to any container. Definitions include a policy, which can work independently or working in a test environment. Especially for a typical database transaction, this is a very lightweight and powerful choice for JTA. When using local EJB SLSB transactions, you will rely on EJB containers and JTA- even if you just access a database, even if you just use SLSBs to declare transactions via CMT. Choosing a JTA programming also requires a J2EE environment. JTA is not just including container dependence on JTA itself and JNDI data sources. For Hibernate transactions that do not use Spring, you must use the HibernateJCA connector or transaction code to write Hibernate in the appropriate JVM buffer layer to configure JTA transaction. In the case of only one database, Spring-driven transactions can cooperate with a local defined Hibernate, just as in combination with a local JDBC data source. Therefore, when faced with distributed transaction needs, you only need to convert JTA transaction policies to Spring. It is important to note that a JCA connector requires a special container deployment step, and it is clear that JCA is first supported. This is more controversial than deploying a simple web application than using local resource definitions and Spring driver transactions. And you often need the company's version of the container support, and JCA is not available like WebLogic Express. A Spring app that uses local resources and transactions with a database can be worked in any J2EE's Web container, and the web container does not have to support JTA, JCA, and EJBs, such as: Tomcat, Resin, and even smallest Jetty. In addition, such an intermediate layer can be easily applied to the desktop application or in the test kit. All considered things include: If you don't use EJB, insist on using the local sessionFactory, use SpringHibernateTransactionManager or JTATRRANSACTIONMANAGER, you will get all the benefits of cache and distribution of JVM layers appropriately, without causing any arguments for container deployment . The JNDI registration of the sessionFactory of a Hibernate via the JCA connector is just a significant value in the case of using EJB. 10. Skeletons and examples Configuring a J2EE for a J2EE using Spring and Hibernate Best to see the "Typical web application" Skeletons in Spring Framework, it gives the JDBC and Hibernate applications. A variety of data sources and transaction management configuration items, take a closer look at the configuration of the transaction interceptor, and it also shows you how to configure the AOP interceptor. In the 1.0 M2 version of Spring, the example PETClinic provides the selection of DAO implementations and application configurations for JDBC and Hibernate.

转载请注明原文地址:https://www.9cbs.com/read-49911.html

New Post(0)