Spring integration hibernate consists of three parts: Hibernate configuration, Hibernate core objects to spring management, transactions by AOP control benefits:
- Configuration by Java code, get rid of hard-coded, connect database and other information more flexible
- The sessions and other life cycles are better controlled, and the session and transaction dependencies are injected into the DAO, which is more cool
- Transactions are more clearly managed by AOP, and automate the management of transactions
Hibernate configuration
Spring provides a sessionfactory implementation, Localsessionfactorybean by setting the value in Localsessionfactorybean to achieve the effect of the configuration , There are several localsessionfactorybean:
- Org.springframework.orm.hibernate5. Localsessionfactorybean
- Org.springframework.orm.hibernate4. Localsessionfactorybean
- Org.springframework.orm.hibernate3. Localsessionfactorybean
Their difference is that in different versions of the hibernate package, according to their own version of Hibernate to choose
@Configuration @propertysource ("Classpath:/application.properties") public class Hibernateconf {// The Enviroment object can take the file data that is @propertysource tagged//get rid of hard-coded @Autowired public environment env by getting the properties in the property file; The DataSource object is the information used to configure the connection database///At a later configuration Localsessionfactorybean will use DataSource to connect to the database @Bean public DataSource DataSource () Throws classnotfoundexception{DataSource ds=new DataSource (); Get configuration Information Ds.setusername (Env.getproperty ("Datasource.username", "root") in the Environment object and properties file; Ds.setpassword (Env.getproperty ("Datasource.password", "null")); Ds.setaddress (Env.getproperty ("datasource.address")); Ds.setdriver (Env.getproperty ("Datasource.driver")); return DS; }//localsessionfactorybean with Sessionbean//used to configure Hibernate @Bean @Autowired public Localsessionfactorybean Sessionfactory (DataSource DataSource) {Localsessionfactorybean sessionfactory=new localsessionfactorybean (); Sessionfactory.setdatasource (DataSource); Set scan ORM Object Lock Cub Pack Sessionfactory.setpackagestoscan ("Weibo.po"); PropertieS prop=new Properties (); Prop.setproperty ("Hibernate.dialect", Env.getproperty ("Hibernate.dialect"));//Set Hibernate dialect Prop.setproperty (" Hibernate.show_sql ", Env.getproperty (" Hibernate.show_sql "));//settings Display SQL Prop.setproperty (" Hibernate.format_sql ", Env.getproperty ("Hibernate.format_sql"));//Format SQL Prop.setproperty ("Hibernate.hbm2ddl.auto", Env.getproperty (" Hibernate.hbm2ddl.auto "));//auto-build Table sessionfactory.sethibernateproperties (prop); return sessionfactory; }
The essence is to get rid of hard-coded, connected database information (username,password,driver,address .... ) through the enviroment object provided by spring to read the external data file (application.properties) to get the connection information , This way the database configuration is configured directly in the application.properties. It is important to note that Localsessionfactorybean and sessionfactory are not polymorphic relationships, but Localsessionfactorybean There is a Sessionfactory object, and spring automatically instantiates the Sessionfactory object in the Localsessionfactorybean at run time. So we took the Localsessionfactorybean object from the spring container and actually got the sessionfactory in the Localsessionfactorybean.
The session is handed to the spring container
Give Sessionfactory, Session, transcation objects to spring container management
- Manage life cycle better and avoid wasting resources
- Use dependency injection to no longer manually open the connection
- Manage transactions with AOP and no longer manually manage transactions
Sessionfactory has been identified as a bean when it was configured for Hibernate, no more configuration
Session @Bean//request Scope + implements proxy @Scope by class (scopename=webapplicationcontext.scope_request,proxymode= Scopedproxymode.target_class)//automatically assemble the assembled Sessionfactory @Autowired public session session (Sessionfactory Sessionfactory) { return sessionfactory.opensession ();} Transaction @Bean @Scope (Scopename=webapplicationcontext.scope_request,proxymode=scopedproxymode.target_class) Automatically assemble the assembled session @Autowired public Transaction Transction (session session) { return session.begintransaction () ; }
Here are a few places to watch out for
- Set scope, scope is usually request or session, avoid long-term connection to the database
- Set up the proxy, because to inject the session and transcation into DAO, DAO is generally singleton, and session and transaction are short scopes. So you want to inject the proxy object into the DAO first, and then call the real object when you use it.
- Open the session with the Sessionfactory already assembled
- Open the transaction via the assembled session (to reach session and Transcation object one by one)
Transactions are controlled through AOP
When we don't use AOP, we write code like this.
public void Crud () throws sqlexception{ try{ //Operation Database code transaction.submit ();//Submit }catch ( SQLException e) { transaction.rollback ();//Roll back throw e; } finally{ session.close ();//Close Connection }}
General CRUD requires these steps: Commit a transaction, roll back a transaction On error, close the connection
This repetitive, non-business-logic code is not done with AOP.
When you manage transactions through AOP, you only need to
- Set Curd as Tangency point
- Write a surround notification at the tangent point and several steps to implement a transaction in a surround notification
DECLARE slice @aspectpublic class Daoaspect {//Auto assemble session and Transcation @Autowired private session session; @Autowired Private Tr Ansaction transaction; Declares a tangent @Pointcut ("Execution (* *.dao.*.crud (*))")//such that all the CRUD methods under the DAO package are marked as tangency public void Crud () {} //In crud Place surround notification @ Around ("crud ()") public void Aroundcrud (Proceedingjoinpoint p) throws throwable{ try{ p.proceed ();//Perform crud actions transaction.commit ();//COMMIT TRANSACTION } catch (Throwable e) { transaction.rollback ();//error rollback throw e; } finally{ session.close ();//Close Connection}}}
Such a look is not more convenient, from this transaction management only write once there are a few places to note
- P.proceed () must write, do not write will not invoke the tangent point (crud) method, just as the tangent point (crud) is blocked by filtering the same
- Throw e must be written, because AOP is actually a proxy object, otherwise the operation database error will not throw an error (error is handled by the proxy object capture catch)
- Do not commit the transaction, close the connection in the Crud primitive method, or the AOP level will report an error (the connection is closed, the transaction has been committed)
- Because the session and transcation minimum scopes are request levels, it is not necessary to worry about the automatic assembly of the object is not the original
View Original: http://zswlib.com/2016/07/14/spring%e6%95%b4%e5%90%88hibernate/
Spring Integration Hibernate