Hibernate Framework Brief

Source: Internet
Author: User

Hibernate's core components
In Java Web applications based on MVC design patterns, hibernate can be used as the model layer/data access layer. It maps a Java object or PO (persistent object, persisted object) to a database in a database through a configuration file (Hibernate.properties or Hibernate.cfg.xml) and a mapping file (***.hbm.xml) , and then through the operation of PO, the data in the table to increase, delete, change, check and other operations.
In addition to configuration files, mapping files, and persistence classes, the core components of hibernate include the following sections:
A) configuration class: Used to read Hibernate configuration files and generate Sessionfactory objects.
b) Sessionfactory interface: Generates session instance factory.
c) Session interface: used to operate PO. It has methods such as get (), load (), save (), update (), and delete () to load, save, update, and delete the PO. It is the core interface of hibernate.
d) query interface: Used for querying the PO. It can be generated from the CreateQuery () method of the session.
e) Transaction interface: Used to manage hibernate transactions, its main methods are commit () and rollback (), which can be generated from the session's Begintrancation () method.

Persistent Object
Persistent objects can be normal JavaBeans, and the only special thing is that they are associated with (just one) session. There are three states of JavaBeans in Hibernate:
1. Temporary status (transient): When an JavaBean object is orphaned in memory and does not have any association with the data in the database, the JavaBeans object is called a temporary object (transient object).
2. Persistent State (persistent): When a JavaBean object is associated with a session, it becomes persisted (persistent object)
3. Off-State (detached): When the session is closed, the object is also detached from the persistence state and becomes a de-detached object, which can be used freely by any layer of the application, such as data objects that can do business with the presentation layer ( Data Transfer Object).

Hibernate's Running Process
Hibernate is run as follows:
A: The application first calls the Configration class, which reads the information from the Hibernate configuration file and the mapping file and uses this information to generate a Sessionfactpry object.
B: Then a Session object is generated from the Sessionfactory object, and the transaction object is generated with the session object; Get (), load (), save (), update (), delete () and Saveorupdate () and other methods to load, save, update, delete, and other operations; In the case of a query, a query object can be generated from the session object and then executed with the Queries object, and if there is no exception, The transaction object submits the results of these operations to the database.

Hibernate runs as follows:

Hibernate Simple Example:
Data:

CREATE TABLE T_register
(
ID int PRIMARY KEY,
UserName varchar (30),
Userpwd varchar (30),
Sex varchar (10),
Age int
)


View Layer: Registration page register.jsp

<%@ Page language= "java" contenttype= "text/html; CHARSET=GBK "
pageencoding= "GBK"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; CHARSET=GBK ">
<title>insert title here</title>
<body>

<form action= "Servlet/registerservlet" method= "POST" >
User name: <input type= "text" name= "UserName"/><br>
Password: <input type= "text" name= "Userpwd"/><br>
Gender: <input type= "text" name= "Sex"/><br>
Age: <input type= "text" Name= "ages"/><br>
<input type= "Submit" value= "Save"/>
</form>
</body>


Design Persistence class Tregister.java

Persistence class

Design Hibernate configuration file Hibernate.cfg.xml

Hibernate.cfg.xml

Design the mapping file TRegister.hbm.xml

TRegister.hbm.xml

Design Hibernate Basic Class Hibernateutil.java

Package hibernate;
/**
* Hibernate Basic class
* @author Fengyan
* Date 2007-01-09 02:32
*/
Import org.hibernate.HibernateException;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.cfg.Configuration;

public class Hibernateutil{

private static final sessionfactory sessionfactory;

Static
{
Try
{
Configuration config = new configuration (). Configure ("/hibernate/hibernate.cfg.xml");
Sessionfactory = Config.buildsessionfactory ();
}
catch (Throwable e)
{
throw new Exceptionininitializererror (e);
}
}

public static final ThreadLocal session = new ThreadLocal ();

public static Session Currentsession () throws Hibernateexception
{
Session S = (session) Session.get ();
Open a new session,if this Thread has none yet
if (s = = NULL | |!s.isopen ())
{
s = sessionfactory.opensession ();
Session.set (s);
}
return s;
}

public static void CloseSession () throws Hibernateexception
{
Session S = (session) Session.get ();
Session.set (NULL);
if (s! = null)
S.close ();
}

}

Design Control class

Package hibernate.servlet;
/**
* @author Fengyan
* Date 2007-01-09 02:44
* Design Hibernate control class
*/
Import Hibernate. Hibernateutil;
Import Hibernate. PO. Tregister;

Import java.io.IOException;
Import Java.io.PrintWriter;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import org.hibernate.HibernateException;
Import org.hibernate.Session;
Import org.hibernate.Transaction;

public class Registerservlet extends HttpServlet{

private static final String Content_Type = "TEXT/HTML;CHARSET=GBK";
public void Init () throws Servletexception{
Put Your code here
}
public void Destroy (){
Super.destroy (); Just puts "destroy" string in log
Put Your code here
}


public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException{

Response.setcontenttype (Content_Type);
Request.setcharacterencoding ("GBK");

PrintWriter out = Response.getwriter ();

String userName = Request.getparameter ("UserName");
String userpwd = Request.getparameter ("Userpwd");
String sex = request.getparameter ("Sex");
int age = Integer.parseint (Request.getparameter ("Age"));

Tregister RG = new Tregister ();
Rg.setage (age);
Rg.setsex (Sex);
Rg.setusername (UserName);
Rg.setuserpwd (USERPWD);

Session session = Hibernateutil.currentsession ();//Generate Session instance
Transaction tx = Session.begintransaction ();

Try
{
Session.save (RG); Saving Persistent class objects
Tx.commit (); Submit to Database
Session.close ();
Response.sendredirect ("registerok.jsp");
}
catch (Hibernateexception e)
{
E.printstacktrace ();
Tx.rollback ();
}

}

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Doget (Request,response);

}



}

Hibernate Framework Brief

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.