Integration of spring and Hibernate

Source: Internet
Author: User

The core idea is to use spring to manage Hibernate and configure hibernate in spring configuration.

Applicationcontext. xml

<? 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: P = "http://www.springframework.org/schema/p" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <! -- Configure the data source JNDI: org. springframework. JNDI. jndiobjectfactorybean JDBC: org. springframework. JDBC. datasource. drivermanagerdatasourcedbcp connection pool: org. Apache. commons. DBCP. basicdatasource --> <! -- <Bean id = "cecejndi" class = "org. springframework. JNDI. jndiobjectfactorybean "> <property name =" jndiname "value =" Java: COMP/ENV/jdbc/Magus "/> </bean> --> <bean id =" cecejdbc "class =" org. springframework. JDBC. datasource. drivermanagerdatasource "> <property name =" driverclassname "value =" com. mySQL. JDBC. driver "/> <property name =" url "value =" JDBC: mysql: // localhost: 3306/ssh "> </property> <property name = "Username" value = "root"> </property> <property name = "password" value = "root"> </property> </bean> <bean id = "datasourcedbcp "Class =" org. apache. commons. DBCP. basicdatasource "> <property name =" driverclassname "value =" com. mySQL. JDBC. driver "/> <property name =" url "value =" JDBC: mysql: // localhost: 3306/ssh "> </property> <property name =" username "value =" root "> </property> <property name =" password "value =" root "> </proper Ty> <! -- Initial value when the connection pool starts --> <property name = "initialsize" value = "1"/> <! -- Maximum value of the connection pool --> <property name = "maxactive" value = "500"/> <! -- Maximum idle value after a period of peak time, the connection pool can slowly release a portion of the connections that are no longer in use, until maxidle --> <property name = "maxidle" value = "10"/> <! -- Minimum idle value when the number of idle connections is less than the threshold value, the connection pool will pre-apply for some connections, in case of peak traffic, it is too late to apply --> <property name = "minidle" value = "5"/> </bean> <! -- Define a sessionfactory of hibernate --> <bean id = "sessionfactory" class = "org. springframework. Orm. hibernate3.localsessionfactorybean"> <! -- Inject datasource --> <property name = "datasource" ref = "performancejdbc"/> <! -- Configure relevant hibernate properties --> <property name = "hibernateproperties"> <props> <prop key = "hibernate. dialect"> <! -- Com. Magus. sqlserver2008.sqlserver2008dialect --> <! -- Org. hibernate. dialect. oracle9dialect --> <! -- Org. hibernate. dialect. oracledialect --> <! -- Org. hibernate. dialect. mysqldialect --> Org. hibernate. dialect. mysqldialect </prop> </props> </property> <property name = "configlocation" value = "classpath: hibernate. cfg. XML "> </property> </bean> <! -- Define the Transaction Manager and use the Transaction Manager for hibernte --> <bean id = "transactionmanager" class = "org. springframework. Orm. hibernate3.hibernatetransactionmanager"> <! -- Hibernatetransactionmanager needs to inject reference to a sessionfactory Bean --> <property name = "sessionfactory" ref = "sessionfactory"/> </bean> <! -- Define Dao bean as the target of the transaction proxy --> <bean id = "personservicebean" class = "com. Ch. Dao. impl. personservicebean"> <! -- Inject sessionfactory reference to Dao Bean --> <property name = "sessionfactory" ref = "sessionfactory"/> </bean> <! -- Configure the transaction for the service of the specific operation database. Define the transaction proxy of Dao Bean (XML declarative) --> <! -- Gethibernatetemplate (). getsessionfactory (). getcurrentsession () is the session bound to the current thread, and the session bound to the current thread is generated through the current transaction. If you have not configured a transaction, there will be no session in the current thread threadlocal, so there will be no hibernate session bound to thread, and configuration does notallow creation of Non-transactional one here error. --> <Bean id = "personservice1" class = "org. springframework. transaction. Interceptor. transactionproxyfactorybean"> <! -- Inject Transaction Manager into transaction proxy Bean --> <property name = "transactionmanager" ref = "transactionmanager"> </property> <! -- SET transaction properties --> <property name = "transactionattributes"> <props> <! -- All Methods Starting with find adopt the required transaction policy and read-only --> <prop key = "find *"> propagation_required, readonly </prop> <prop key = "get *"> propagation_required, readonly </prop> <prop key = "is *"> propagation_required, readonly </prop> <prop key = "Save *"> propagation_required </prop> <prop key = "Update *"> propagation_required </prop> <prop key = "delete * "> propagation_required </prop> <prop key =" batchdelete * "> propagation_required </prop> <prop key =" n EW * "> propagation_required </prop> </props> </property> <! -- Set the target bean of the transaction proxy --> <property name = "target"> <ref local = "personservicebean"/> <! -- Use nested beans to configure the target Bean (to prevent the target bean from being mistakenly referenced) --> <! -- <Bean class = "com. ch. dao. impl. personservicebean "> <propertyname =" sessionfactory "ref =" sessionfactory "/> </bean> --> </property> </bean> <! -- In most cases, the transaction attributes of each transaction proxy are similar. The implementation classes of the transaction proxy are transactionproxyfactorybean, and the transaction proxy Bean must be injected into the Transaction Manager. Therefore, Spring provides inheritance between beans and beans. Most of the general configurations are configured as transaction templates, while the actual transaction proxy bean inherits the transaction template. This configuration method can reduce part of the configuration code. The following is an inherited configuration file: --> <bean id = "tranproxytemplate" class = "org. springframework. transaction. interceptor. transactionproxyfactorybean "lazy-init =" true "abstract =" true "> <! -- Inject Transaction Manager into transaction proxy Bean --> <property name = "transactionmanager" ref = "transactionmanager"> </property> <! -- SET transaction properties --> <property name = "transactionattributes"> <props> <! -- All Methods Starting with find adopt the required transaction policy and read-only --> <prop key = "find *"> propagation_required, readonly </prop> <prop key = "get *"> propagation_required, readonly </prop> <prop key = "is *"> propagation_required, readonly </prop> <prop key = "Save *"> propagation_required </prop> <prop key = "Update *"> propagation_required </prop> <prop key = "delete * "> propagation_required </prop> <prop key =" batchdelete * "> propagation_required </prop> <prop key =" n EW * "> propagation_required </prop> </props> </property> </bean> <bean id =" personservice "parent =" tranproxytemplate "> <! -- Set the target bean of the transaction proxy --> <property name = "target"> <ref local = "personservicebean"/> <! -- Use nested beans to configure the target Bean (to prevent the target bean from being mistakenly referenced) --> <! -- <Bean class = "com. ch. dao. impl. personservicebean "> <propertyname =" sessionfactory "ref =" sessionfactory "/> </bean> --> </property> </bean> </beans>

Service layer interface

package com.ch.dao;import com.ch.entity.Person;public interface IPersonService {public void save(Person person) ;public void update(Person person);public Person find(Integer personId);public void delete(Person person);}

Service layer implementation

package com.ch.dao.impl;import java.util.List;import org.hibernate.SessionFactory;import com.ch.dao.IPersonService;import com.ch.entity.Person;public class PersonServiceBean implements IPersonService {private SessionFactory sessionFactory;public void delete(Person person) {sessionFactory.getCurrentSession().delete(person);}public Person find(Integer personId) {Person person = (Person) sessionFactory.getCurrentSession().get(Person.class, personId);return person;}public void save(Person person) {sessionFactory.getCurrentSession().save(person);}public void update(Person person) {sessionFactory.getCurrentSession().merge(person);}public List<?> findAllPersons() {return sessionFactory.getCurrentSession().createQuery("from Person").list();}public void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}}

Hibernate configuration file

<? XML version = '1. 0' encoding = 'utf-8'?> <! Doctype hibernate-configuration public "-// hibernate/hibernate configuration DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <! -- Generated by myeclipse hibernate tools. --> 

Test class

Package COM. ch. test; import Org. springframework. context. applicationcontext; import Org. springframework. context. support. classpathxmlapplicationcontext; import COM. ch. dao. ipersonservice; import COM. ch. entity. person; public class persontest {private ipersonservice personservice; Public persontest () {applicationcontext AC = new classpathxmlapplicationcontext ("spring/applicationcontext. XML "); personservice = (Ipersonservice) AC. getbean ("personservice");} public void testsave () {person P = new person ("John"); personservice. save (p); system. out. println ("saved ..... ");} Public void testupdate () {person P = personservice. find (2); p. setpersonname ("Xiao Zhang"); personservice. update (p); system. out. println ("Update successful ..... ");} Public String testfind () {person P = personservice. Find (1); system. Out. println (" search successful ..... "); Return p. getpersonname ();} public void testdelete () {person P = personservice. find (2); personservice. delete (p); system. out. println ("deleted successfully ..... ");} Public static void main (string [] ARGs) {persontest test = new persontest (); test. testsave (); // test. testupdate (); // test. testfind (); // test. testdelete ();}}

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.