Java Framework---Spring hibernate integration

Source: Internet
Author: User

The integration of the two frameworks after using Hibernate and the spring framework becomes quite easy,

Why integrate hibernate?
1. Managing Sessionfactory objects with the IOC feature of spring
2. Manage session objects with spring
3. Implement declarative transaction management using Spring's features

First step: Build Hibernate environment (including the jar that introduced hibernate, package configuration data source, build class and Table mapping), why do you do this. I think hibernate is the most important thing. Because no spring does not affect me to add records to the data. Spring is just a container. That's not much to say.

Step Two: Configure the spring environment (introduce the jar and write a bean. configuration information FOR XML)

Omitted hibernate.cfg.xml files are all hosted in spring configuration file

In pure hibernate access, applications need to create Sessionfactory instances manually, which is not an excellent strategy to imagine. In real-world development, you want to manage sessionfactory instances in a declarative way, managing Sessionfactory instances directly with configuration files, and when demonstrating the plugin extension points of struts,

Spring's IOC container provides a better way to manage not only the Session-factory instances in a declarative manner, but also the role of the IOC container to inject data source references for Sessionfactory.

Here is the sample code for configuring Hibernate sessionfactory in the spring configuration file:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://"Xmlns:xsi= "Http://"Xmlns:context= "Http://"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation= "Http:// XSD Http:// -context-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Schema/aop/spring-aop-3.1.xsd "Default-autowire= "ByName">    <Context:annotation-config/>    <Context:component-scanBase-package= "COM.BJSXT" />    <!--
You can also use this method <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "cl OSE "> <property name=" driverclassname "value=" Com.mysql.jdbc.Driver "/> <propert Y name= "url" value= "Jdbc:mysql://localhost:3306/myuse"/> <property name= "username" value= "root"/> <property name= "Password" value= "root"/> </bean> - <Beanclass= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> < Propertyname= "Locations"> <value></value> </ Property> </Bean> <BeanID= "DataSource"Destroy-method= "Close"class= "Org.apache.commons.dbcp.BasicDataSource"> < Propertyname= "Driverclassname"value= "${jdbc.driverclassname}" /> < Propertyname= "url"value= "${jdbc.url}" /> < Propertyname= "username"value= "${jdbc.username}" /> < Propertyname= "Password"value= "${jdbc.password}" /> </Bean> <BeanID= "Sessionfactory"class= "Org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> < Propertyname= "DataSource"ref= "DataSource" /> < Propertyname= "Annotatedclasses"> <List> <value>Com.bjsxt.model.User</value> </List> </ Property> < Propertyname= "Hibernateproperties"> <Props> <propKey= "Hibernate.dialect">Org.hibernate.dialect.MySQLDialect</prop> <propKey= "Hibernate.show_sql">True</prop> </Props> </ Property> </Bean></Beans>

Jdbc.driverclassname=com.mysql.jdbc.driverjdbc.url=jdbc\:mysql\://localhost\:3306/myusejdbc.username= Rootjdbc.password=root

Step three: Register Hibernate in spring.

<BeanID= "Txmanager"class= "Org.springframework.orm.hibernate3.HibernateTransactionManager">        < Propertyname= "Sessionfactory"ref= "Sessionfactory" />    </Bean>    <Tx:annotation-drivenTransaction-manager= "Txmanager"/>

In DAO components, all persisted operations are done through the Hibernatetemplate instance, and the Hibernatetemplate operations database is very concise, and most crud operations can solve the problem through a single line of code. The following describes how to make persistent layer access through hibernatetemplate.

Hibernatetemplate provides a number of common ways to perform basic operations, such as the usual additions, deletions, modifications, and queries, and Spring 2.0 adds support for named SQL queries, as well as paging support. In most cases, the CRUD operations of most DAO objects can be done using Hibernate's general usage. Here is an introduction to Hibernatetemplate's common methods:

void Delete (Object entity) to delete the specified persisted instance.

DeleteAll (Collection entities), deletes all persisted class instances within the collection.

Find (String queryString), which returns an instance collection based on the HQL query string.

Findbynamedquery (String queryname), which returns an instance collection based on a named query.

Get (class Entityclass, Serializable ID) that loads instances of a particular persisted class based on the primary key.

Save (Object entity), saving the new instance.

Saveorupdate (Object entity), select Save or update, depending on the instance state.

Update (Object entity), which updates the state of the instance and requires the entity to be persistent.

Setmaxresults (int maxResults), sets the size of the paging.

The following is the source code for a complete DAO class:


 PackageCom.bjsxt.service;Importorg.junit.Test;ImportOrg.springframework.context.ApplicationContext;;ImportCom.bjsxt.model.User;//Dependency Injection//Inverse of Control Public classuserservicetest {@Test Public voidTestadd ()throwsException {classpathxmlapplicationcontext ctx=NewClasspathxmlapplicationcontext ("Beans.xml"); UserService Service= (UserService) ctx.getbean ("UserService");        System.out.println (Service.getclass ()); (NewUser ());            Ctx.destroy (); }}

Java Framework---Spring hibernate integration

Related Article

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: 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.