The support for hibernate in spring is very powerful. We can see from a simple example that we will also discuss the so-called lightweight container.
First, we need to configure the data source. Generally, we have two methods to obtain the connection. First, we need to write the data source by ourselves.CodeObtain the connection. The second is to obtain 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 database named examer to connect to MySQL. The manual configuration is as follows:
- <Bean id = "datasource"Class= "Org. Apache. commons. DBCP. basicdatasource" Destroy-method = "close">
- <Property name = "driverclassname">
- <Value> com. MySQL. JDBC. Driver </value>
- </Property>
- <Property name = "url">
- <Value> JDBC: mysql:// Localhost/examer </value>
- </Property>
- <Property name = "username">
- <Value> root </value>
- </Property>
- <Property name = "password">
- <Value> </value>
- </Property>
- </Bean>
Good reading, right? If we use the JNDI data source, the datasource declaration should be:
- <Bean id = "datasource"Class= "Org. springframework. JNDI. jndiobjectfactorybean">
- <Property name = "jndiname">
- <Value> JAVA: compenvjdbcspringexamer </value>
- </Property>
- </Bean>
You need to bind a JDBC/springexamer item in the JNDI environment to make the code meaningful. Note that the IDs of all bean declarations must be unique.
In this system, database operations are encapsulated by hibernate, so datasource does not need to be injected into a specific logic class, and it will only be injected to the sessionfactory of hibernate.
According to the general idea, we need to register the sessionfactory of hibernate in spring. It should be a class compiled by ourselves, get datasource, and return sessionfactory, other logic classes use this sessionfactory to obtain sessions for database operations.
However, we have another option. spring directly provides the encapsulation of sessionfactory. You only need to register a spring class and provide it with the required attributes. It will return an org. springframework. orm. hibernate. hibernatetemplate. This class encapsulates add, Del, and other operations. It is highly encapsulated and it is very easy to compile hibernate applications. But the problem arises. How should we choose?
On the surface, 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, classes managed by spring do not need to be bound to them. Therefore, your system will not depend on spring. However, if you use spring encapsulation to operate hibernate, you must inherit the org. springframework. Orm. hibernate. Support. hibernatedaosupport class, which leads to binding. So it is a bit painful to make such a choice. If one day the Spring framework does not exist, how can you upgrade and maintain your code? Specific problems can only be analyzed in detail. In our application, we fully use the spring-encapsulated hibernatetemplate, which is too easy to use and therefore addictive.
Suppose we have a student table with a simple structure:
- Automatic ID Growth
- Name varchar (40)
- Password varchar (32)
- GradeInt(4) grade
- SexBooleanGender (true is male, false is female)
Design a student class to map the table:
-
- /*
-
- * Creation date: 2005-3-17
-
- */
-
- PackageNet. bromon. Spring. examer. pojo;
-
- /**
-
- * @ Author bromon
-
- */
-
- Public ClassStudent
-
- {
-
- Private IntID;
-
- Private StringName;
-
- Private StringPassword;
-
- Private IntGrade;// Grade
-
- Private BooleanSex;
-
-
- GetSet method ..........
- }
Compile student. HBM. XML to let hibernate know how to associate the student table and student class. This file is in the same directory as student. Java:
- <Hibernate-mapping>
- <ClassName = "net. bromon. Spring. examer. pojo. Student" table = "student">
- <ID name = "ID" column = "ID">
- <GeneratorClass= "Identity"/>
- </ID>
- <Property name = "name" column = "name"/>
- <Property name = "password" column = "password"/>
- <Property name = "Grade" column = "Grade"/>
- <Property name = "sex" column = "sex"/>
- </Class>
- </Hibernate-mapping>
Then we can configure sessionfactory in Spring:
- class = "org. springframework. Orm. hibernate. localsessionfactorybean">
-
-
-
-
-
-
- net. SF. hibernate. dialect. mysqldialect
-
-
-
-
-
- classpath:/netbromonspringexamerpojo
-
-
-
The datasource we have previously registered is referenced. The mappingdirectorylocations attribute specifies the path of the. HBM. xml file, and all the. HBM. xml files under the folder will be loaded.
Everything is ready. Now we need to add a studentmanager class to add, delete, query, and modify operations:
-
- /*
-
- * Creation date: 2005-3-17
-
- */
-
- PackageNet. bromon. Spring. examer. student;
-
-
- ImportNet. bromon. Spring. examer. pojo. student;
-
-
- ImportOrg. springframework. Orm. hibernate. hibernatetemplate;
-
- ImportOrg. springframework. Orm. hibernate. localsessionfactorybean;
-
- ImportOrg. springframework. Orm. hibernate. Support. hibernatedaosupport;
-
-
- /**
- * @ Author bromon
-
- */
-
- Public ClassStudentmanagerExtendsHibernatedaosupport
-
- {
-
- PrivateLocalsessionfactorybean sessionfactory;
-
- PrivateHibernatetemplate HT;
-
- PublicStudentmanager ()
-
- {
-
- This. Ht =Super. Gethibernatetemplate ();
-
- }
-
- Public VoidAdd (student s)
-
- {
-
- Ht. Save (s );// Insert a piece of data only requires this line of code
-
- }
-
- }
This class only demonstrates how to add a student. hibernatetemplate also encapsulates many useful methods. Please refer to the spring document. Sessionfactory in studentmanager is injected by spring, but studentmanager does not perform any processing on sessionfactory, because all the processing is encapsulated by hibernatedaosupport. gethibernatetemplate. The entire studentmanager does not see any exception handling, and they are also encapsulated by the base class.
The last step is to register studentmanger in spring and inject sessionfactory to it:
- <Bean id = "studentmanager"Class= "Net. bromon. Spring. examer. Student. studentmanager">
- <Property name = "sessionfactory">
- <Ref bean = "sessionfactory"/>
- </Property>
- </Bean>
All configurations have been completed. Perform the unit test below:
-
- /*
-
- * Creation date: 2005-3-17
-
- */
-
- PackageNet. bromon. Spring. examer. Student. test;
-
-
- ImportJava. Io.Fileinputstream;
-
-
- ImportOrg. springframework. Beans. Factory. xml. xmlbeanfactory;
-
- ImportOrg. springframework. Context. applicationcontext;
- ImportOrg. springframework. Context. Support. classpathxmlapplicationcontext;
-
-
- ImportNet. bromon. Spring. examer. pojo. student;
-
- ImportNet. bromon. Spring. examer. Student. studentmanager;
-
- ImportJUnit. framework.Testcase;
-
-
- /**
-
- * @ Author bromon
-
- */
-
- Public ClassTeststudentmanagerExtends Testcase{
-
-
- Public VoidTestadd ()
-
- {
- Try
-
- {
-
- Applicationcontext context =NewClasspathxmlapplicationcontext ("springconfig. xml ");
-
-
- Student s =NewStudent ();
-
- S. setname ("bromon ");
-
- S. setpassword ("123 ");
-
- S. setgrade (3 );
- S. setsex (True);
-
-
- (Studentmanager) Context. getbean ("studentmanager"). Add (s );
-
- }Catch(ExceptionE)
-
- {
-
- E. printstacktrace ();
-
- }
-
- }
-
-
- }
Spring has simplified hibernate operations to a very high degree. The most important thing is that the entire development can be driven by design. If a team is familiar with spring, the designer can plan all the classes, sort out the relationships between classes, write them as configuration files, compile the hibernate ing file, and associate the data tables with pojo, members can work completely in the design scheme. Using the hibernate template encapsulated by spring, the development speed is very fast and debugging is easy. It can solve the problem of implementing the design scheme within the team.
Since this article does not explain the use of hibernate, please refer to the hibernate documentation for relevant content.