Spring application example

Source: Internet
Author: User
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:

    1. <Bean id = "datasource"Class= "Org. Apache. commons. DBCP. basicdatasource" Destroy-method = "close">
    2. <Property name = "driverclassname">
    3. <Value> com. MySQL. JDBC. Driver </value>
    4. </Property>
    5. <Property name = "url">
    6. <Value> JDBC: mysql:// Localhost/examer </value>
    7. </Property>
    8. <Property name = "username">
    9. <Value> root </value>
    10. </Property>
    11. <Property name = "password">
    12. <Value> </value>
    13. </Property>
    14. </Bean>

Good reading, right? If we use the JNDI data source, the datasource declaration should be:

    1. <Bean id = "datasource"Class= "Org. springframework. JNDI. jndiobjectfactorybean">
    2. <Property name = "jndiname">
    3. <Value> JAVA: compenvjdbcspringexamer </value>
    4. </Property>
    5. </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:

    1. Automatic ID Growth
    2. Name varchar (40)
    3. Password varchar (32)
    4. GradeInt(4) grade
    5. SexBooleanGender (true is male, false is female)

Design a student class to map the table:

  1. /*
  2. * Creation date: 2005-3-17
  3. */
  4. PackageNet. bromon. Spring. examer. pojo;
  5. /**
  6. * @ Author bromon
  7. */
  8. Public ClassStudent
  9. {
  10. Private IntID;
  11. Private StringName;
  12. Private StringPassword;
  13. Private IntGrade;// Grade
  14. Private BooleanSex;
  15. GetSet method ..........
  16. }

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:

    1. <Hibernate-mapping>
    2. <ClassName = "net. bromon. Spring. examer. pojo. Student" table = "student">
    3. <ID name = "ID" column = "ID">
    4. <GeneratorClass= "Identity"/>
    5. </ID>
    6. <Property name = "name" column = "name"/>
    7. <Property name = "password" column = "password"/>
    8. <Property name = "Grade" column = "Grade"/>
    9. <Property name = "sex" column = "sex"/>
    10. </Class>
    11. </Hibernate-mapping>

Then we can configure sessionfactory in Spring:

    1. class = "org. springframework. Orm. hibernate. localsessionfactorybean">
    2. net. SF. hibernate. dialect. mysqldialect
    3. 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:

  1. /*
  2. * Creation date: 2005-3-17
  3. */
  4. PackageNet. bromon. Spring. examer. student;
  5. ImportNet. bromon. Spring. examer. pojo. student;
  6. ImportOrg. springframework. Orm. hibernate. hibernatetemplate;
  7. ImportOrg. springframework. Orm. hibernate. localsessionfactorybean;
  8. ImportOrg. springframework. Orm. hibernate. Support. hibernatedaosupport;
  9. /**
  10. * @ Author bromon
  11. */
  12. Public ClassStudentmanagerExtendsHibernatedaosupport
  13. {
  14. PrivateLocalsessionfactorybean sessionfactory;
  15. PrivateHibernatetemplate HT;
  16. PublicStudentmanager ()
  17. {
  18. This. Ht =Super. Gethibernatetemplate ();
  19. }
  20. Public VoidAdd (student s)
  21. {
  22. Ht. Save (s );// Insert a piece of data only requires this line of code
  23. }
  24. }

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:

    1. <Bean id = "studentmanager"Class= "Net. bromon. Spring. examer. Student. studentmanager">
    2. <Property name = "sessionfactory">
    3. <Ref bean = "sessionfactory"/>
    4. </Property>
    5. </Bean>

All configurations have been completed. Perform the unit test below:

  1. /*
  2. * Creation date: 2005-3-17
  3. */
  4. PackageNet. bromon. Spring. examer. Student. test;
  5. ImportJava. Io.Fileinputstream;
  6. ImportOrg. springframework. Beans. Factory. xml. xmlbeanfactory;
  7. ImportOrg. springframework. Context. applicationcontext;
  8. ImportOrg. springframework. Context. Support. classpathxmlapplicationcontext;
  9. ImportNet. bromon. Spring. examer. pojo. student;
  10. ImportNet. bromon. Spring. examer. Student. studentmanager;
  11. ImportJUnit. framework.Testcase;
  12. /**
  13. * @ Author bromon
  14. */
  15. Public ClassTeststudentmanagerExtends Testcase{
  16. Public VoidTestadd ()
  17. {
  18. Try
  19. {
  20. Applicationcontext context =NewClasspathxmlapplicationcontext ("springconfig. xml ");
  21. Student s =NewStudent ();
  22. S. setname ("bromon ");
  23. S. setpassword ("123 ");
  24. S. setgrade (3 );
  25. S. setsex (True);
  26. (Studentmanager) Context. getbean ("studentmanager"). Add (s );
  27. }Catch(ExceptionE)
  28. {
  29. E. printstacktrace ();
  30. }
  31. }
  32. }

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.
 

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.