Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use hibernate in spring

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use hibernate in spring". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use hibernate in spring.

First of all, we need to configure the data source, usually we have two ways to get the Connection, one is to write our own code to get the connection, the other is to get the DataSource from the JNDI environment, and then generate a Connection. In any case, since it is an object under spring, it should be registered in the configuration file. Suppose we need a connection to mysql. The following database is called examer. The manual configuration is:

Com.mysql.jdbc.Driver

Jdbc:mysql://localhost/examer

Root

Easy to read, isn't it? If we use JNDI data sources, then the declaration of dataSource should be:

Java:compenvjdbcspringExamer

You need to bind something called jdbc/springExamer in the JNDI environment for this code to make sense. Another reminder is that all bean claims that its id must be unique.

In this system, the database operation is encapsulated by hibernate, so dataSource does not need to be injected into the specific logic class, it will only be injected into the sessionFactory of hibernate.

According to the general idea, we need to register the sessionFactory of hibernate in spring, which should be a class written by ourselves, get dataSource, return sessionFactory, and other logical classes get session through this sessionFactory for database operation.

But we have another option, spring directly provides the encapsulation of sessionFactory, you just need to register a spring own class, provide it with the necessary properties, it will return an org.springframework.orm.hibernate.HibernateTemplate, this class encapsulates add, del and other operations, its encapsulation degree is quite high, it is very easy to write hibernate applications through it. But the question is, how should we choose?

On the face of it, using spring's own library is undoubtedly easier, but please note that spring is a lightweight framework, the so-called lightweight, an important feature is non-invasive, that is, you use this framework, will not be bound by it, classes managed by spring, should not need to use its interface and abstract classes, so that your system will not be dependent on spring. But if you use spring encapsulation to manipulate hibernate, you must inherit the org.springframework.orm.hibernate.support.HibernateDaoSupport class, which leads to binding. So it's a bit painful to make such a choice. If one day the spring framework doesn't exist, how can your code be upgraded and maintained? Specific problems can only be analyzed in detail. In our application, we completely use HibernateTemplate encapsulated by spring, which is so easy to use that it is easy to be addicted.

Suppose we have a student table with a simple structure:

Automatic growth of id

Name varchar (40)

Password varchar (32)

Grade grade int (4)

Sex Boolean gender (true is male, false is female)

Design a Student class to map this table:

/ *

* creation date 2005-3-17

, /

Package net.bromon.spring.examer.pojo

/ * *

* @ author Bromon

, /

Public class Student

{

Private int id

Private String name

Private String password

Private int grade;// grade

Private boolean sex

Getset method. .

}

Write Student.hbm.xml so that hibernate knows how to associate the student table with the Student class, which is in the same directory as Student.java:

Class >

Then we can configure sessionFactory in spring:

Net.sf.hibernate.dialect.MySQLDialect

Classpath:/netbromonspringexamerpojo

The reference to our previously registered dataSource,mappingDirectoryLocations attribute indicates where the .hbm.xml file is located, and all the .hbm.xml files under this folder will be loaded.

Everything is ready, and now we are going to add a StudentManager class to add, delete, query and modify:

/ *

* creation date 2005-3-17

, /

Package net.bromon.spring.examer.student

Import net.bromon.spring.examer.pojo.Student

Import org.springframework.orm.hibernate.HibernateTemplate

Import org.springframework.orm.hibernate.LocalSessionFactoryBean

Import org.springframework.orm.hibernate.support.HibernateDaoSupport

/ * *

* @ author Bromon

, /

Public class StudentManager extends HibernateDaoSupport

{

Private LocalSessionFactoryBean sessionFactory

Private HibernateTemplate ht

Public StudentManager ()

{

This.ht=super.getHibernateTemplate ()

}

Public void add (Student s)

{

Ht.save (s); / / insert a piece of data only with this line of code

}

}

This class only demonstrates how to add a Student,HibernateTemplate and encapsulates many useful methods, please refer to the spring documentation. SessionFactory in StudentManager is injected by spring, but StudentManager does nothing to sessionFactory because all processing is encapsulated by HibernateDaoSupport.getHibernateTemplate (). There is no exception handling in the entire StudentManager, and they are encapsulated by the base class.

The final step is to register StudentManger in spring and inject sessionFactory into it:

All the configurations have been completed, so let's do a unit test:

/ *

* creation date 2005-3-17

, /

Package net.bromon.spring.examer.student.test

Import java.io.FileInputStream

Import org.springframework.beans.factory.xml.XmlBeanFactory

Import org.springframework.context.ApplicationContext

Import org.springframework.context.support.ClassPathXmlApplicationContext

Import net.bromon.spring.examer.pojo.Student

Import net.bromon.spring.examer.student.StudentManager

Import junit.framework.TestCase

/ * *

* @ author Bromon

, /

Public class TestStudentManager extends TestCase {

Public void testAdd ()

{

Try

{

ApplicationContext context = new ClassPathXmlApplicationContext ("springConfig.xml")

Student s=new Student ()

S.setName ("bromon")

S.setPassword ("123")

S.setGrade (3)

S.setSex (true)

((StudentManager) context.getBean ("studentManager")) .add (s)

} catch (Exception e)

{

E.printStackTrace ()

}

}

}

Spring has simplified the operation of hibernate to a very high level, and the most important thing is that the whole development can be driven by design. If a team is familiar with spring, it is entirely up to the designer to plan all the classes, sort out the relationships between the classes, write them into configuration files, and then write hibernate mapping files to associate data tables with pojo, so that members can work completely within the design solution. Using the hibernate template encapsulated by spring, it is very fast to develop and easy to debug. It can solve the problem of how to implement the design within the team.

At this point, I believe you have a deeper understanding of "how to use hibernate in spring". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report