Hibernate + spring

Source: Internet
Author: User
This article is an entry-level article for spring-based Web application development. The front-end adopts the struts MVC Framework, the middle layer adopts spring, and the backend uses hibernate.

This article includes the following content:

· Configure Hibernate and transactions

· Load the spring applicationcontext. xml file

· Establish dependency between the business layer and Dao

· Apply spring to struts

  Introduction

In this example, a simple web application called myusers is created to complete user management operations, including simple database addition, deletion, and query. This is CRUD (new, access, update, and delete) operation. This is a three-tier Web application that uses action (struts) to access the business layer and the business layer to access Dao. Figure 1 briefly describes the overall structure of the application. The numbers in the figure show the Process Order-from the Web (useraction) to the middle layer (usermanager), to the data access layer (userdao), and then return the result.

The real strength of the spring layer lies in its declarative transaction processing, helping to define and support the persistent layer (such as hiberate and ibatis)

Below are the steps to complete this example:

1. Install the Eclipse plug-in

2. Create a database table

3. Configure Hibernate and spring

4. Create an implementation class for the hibernate Dao Interface

5. Run the test class to test the CRUD operation of Dao.

6. Create a processing class and declare the transaction

7. Create action and model on the web layer

8. Run the test class test CRUD operation of action

9. Create a JSP file and perform crud operations through the browser

10. Verify JSP through a browser

  Install Eclipse plug-in

1. hibernate plug-in http://www.binamics.com/hibernatesync

2. Spring plugin http://springframework.sourceforge.net/spring-ide/eclipse/updatesite/

3. myeclipse plug-in (cracked version)

4. Tomcat plug-in. tanghan

5. Other plug-ins include XML, JSP,

Create database tables

Create Table app_user (ID number not null primary, firstname vchar (32), lastname vchar (32 ));

  Create a project

Create a new web project. The new directory structure also contains the new folder page used to put JSP files, and the source folder test used to put JUnit test files. At the same time, all the packages, including struts, hibernate, and spring, will be imported to the lib directory.

Create a persistent layer o/R Mapping

1. Use the hibernate plug-in src/COM. Jandar. Model to export the. HBM. xml file of app_user from the database and change it to user. HBM. xml.

<? XML version = "1.0"?>
<! Doctype hibernate-mapping public
"-// Hibernate/hibernate mapping DTD // en"
Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd>
<Hibernate-mapping package = "com. Jandar. Model">
<Class name = "user" table = "app_user">
<ID
Column = "ID"
Name = "ID"
Type = "integer"
>

<Generator class = "assigned"/>

</ID>

<Property
Column = "lastname"
Length = "10"
Name = "lastname"
Not-null = "false"
Type = "string"
/>

<Property
Column = "firstname"
Length = "10"
Name = "firstname"
Not-null = "true"
Type = "string"
/>

</Class>
</Hibernate-mapping>

2. Use hibernate synchronizer-> synchronizer file to generate the user. Java file. The user object corresponds to the app_user table in the database.

Note: The automatically generated object files in eclipse are not exactly the same. The same is that each object file must implement the serializable interface and must use the tostring and hashcode methods;

Import java. Io. serializable;
Import org. Apache. commons. Lang. Builder. equalsbuilder;
Import org. Apache. commons. Lang. Builder. hashcodebuilder;
Import org. Apache. commons. Lang. Builder. tostringbuilder;
Import org. Apache. commons. Lang. Builder. tostringstyle;

Public class baseobject implements serializable {
Public String tostring (){
Return tostringbuilder. reflectiontostring (this,
Tostringstyle. multi_line_style );
}

Public Boolean equals (Object O ){
Return equalsbuilder. reflectionequals (this, O );
}

Public int hashcode (){
Return hashcodebuilder. reflectionhashcode (this );
}
}

Public class user extends baseobject {
Private long ID;
Private string firstname;
Private string lastname;

/**
* @ Return returns the ID.
*/

Public long GETID (){
Return ID;
}

/**
* @ Param ID the ID to set.
*/

Public void setid (long ID ){
This. ID = ID;
}

/**
* @ Return returns the firstname.
*/

Public String getfirstname (){
Return firstname;
}

/**
* @ Param firstname the firstname to set.
*/

Public void setfirstname (string firstname ){
This. firstname = firstname;
}

/**
* @ Return returns the lastname.
*/

Public String getlastname (){
Return lastname;
}

/**
* @ Param lastname the lastname to set.
*/

Public void setlastname (string lastname ){
This. lastname = lastname;
}
}

Create a DaO Access Object

1. Create the idao. Java interface in src/COM. Jandar. Service. Dao. All Dao files inherit this interface.


Package com. Jandar. Services. Dao;

Public interface idao {

}

2. Create the iuserdao. Java interface under src/COM. Jandar. Service. Dao.

Public interface iuserdao extends Dao {
List getusers ();
User getuser (integer userid );
Void saveuser (User user );
Void removeuser (integer ID );
}

This interface provides methods to access objects,

3. Create userdaohiberante. Java in src/COM. Jandar. Service. Dao. hibernate

Import java. util. List;
Import org. Apache. commons. Logging. log;
Import org. Apache. commons. Logging. logfactory;
Import org. springframework. Orm. hibernate. Support. hibernatedaosupport;
Import com. Jandar. model. user;
Import com. Jandar. Service. Dao. iuserdao;

Public class userdaohibernate extends hibernatedaosupport implements iuserdao {

Private log = logfactory. getlog (userdaohibernate. Class );
/* (Non-javadoc)
* @ See COM. Jandar. Dao. iuserdao # getusers ()
*/

Public list getusers (){
Return gethibernatetemplate (). Find ("from user ");
}

/* (Non-javadoc)
* @ See COM. Jandar. Dao. iuserdao # getuser (Java. Lang. Long)
*/

Public user getuser (integer ID ){
// Todo automatically generates method stubs
Return (User) gethibernatetemplate (). Get (user. Class, ID );
}

/* (Non-javadoc)
* @ See COM. Jandar. Dao. iuserdao # saveuser (COM. Jandar. model. User)
*/

Public void saveuser (User user ){
Log. debug ("xxxxxxx ");
System. Out. println ("YYYY ");
Gethibernatetemplate (). saveorupdate (User );
If (log. isdebugenabled ())
{
Log. debug ("userid set to" + User. GETID ());
}
}

/* (Non-javadoc)
* @ See COM. Jandar. Dao. iuserdao # removeuser (Java. Lang. Long)
*/

Public void removeuser (integer ID ){
Object User = gethibernatetemplate (). Load (user. Class, ID );
Gethibernatetemplate (). Delete (User );
If (log. isdebugenabled ()){
Log. debug ("del user" + id );
}
}
}

This class implements the iuserdao interface method and inherits the hibernatedaosupport class. This class is used to access and operate objects through hibernate to perform database operations.

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.