Hibernate learning Notes (ii)--Creating a simple Hibernate project

Source: Internet
Author: User
Tags connection pooling generator rollback sessions stub

Reprint please specify the Source: http://blog.csdn.net/fxdaniel/article/details/42420779


Next article: Hibernate study notes (i)--build Hibernate development environment

First look at the hibernate development of a simple process:

(1) Prepare the development environment and create hibernate projects.

(2) Create the data table in the database.

(3) Create a persistent class.

(4) Design the mapping file to map the Pojo object to the database using the Hibernate mapping file.

(5) Create the Hibernate configuration file Hibernate.cfg.xml.

(6) Write the helper class Hibernateutil class, which can be used to initialize the hibernate and provide a method to obtain the session, this step may choose according to the situation.

(7) Writing DAO layer classes.

(8) Writing service layer class.

(9) Writing test class.


Let's do it step-by-step. 1. Create Eclipse Project

Create a dynamic WEB Project project in Eclipse named Hibernatedemo.
Right-click on the Hibernatedemo item name, select New->other option from the shortcut menu, locate the Hibernate node in the pop-up dialog box, select Hibernate Configuration File (cfg.xml) option, As shown in the following illustration:


Click on the Next button, in the pop-up dialog box to select the directory to save the configuration file, the general default in the SRC directory, and the need to enter the name of the configuration file, the general default for Hibernate.cfg.xml can be. Continue next, fill in the database dialect (DB dialect), database driver (Driver Class), database URL, username, password, etc. in the pop-up dialog box. The MySQL database is configured as follows:


When you click Finish, the configuration file is created successfully, and you can continue to edit the file after you need it. 2. Create data table User

Create a database named MySQLdb in MySQL and create a table named user in the database. The statement to create the user table is as follows:

CREATE TABLE User (
user_id int (one),
name varchar (), password varchar (),
type varchar (6),
Primary KEY (USER_ID));
The Created user table is displayed in MySQL as follows:

mysql> describe user;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| user_id  | int (one)     | NO   | PRI | 0       | | |
| name     | varchar (20) | YES  |     | NULL    | | |       password |
varchar (12) | YES  |     | NULL    | | |     varchar (6)  | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+

3. Write Pojo mapping class User.java

Package org.hibernate.entity;

public class User {

	private int id;//The identity attribute of the persisted class, mapped to the primary key column in the datasheet
	private String name;
	private String password;
	Private String type;
	Public User () {
		//TODO auto-generated constructor stub
	} public
	int getId () {return
		ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	Public String GetPassword () {return
		password;
	}
	public void SetPassword (String password) {
		this.password = password;
	}
	Public String GetType () {return
		type;
	}
	public void SetType (String type) {
		this.type = type;
	}
	
}

4. Write Mapping file User.hbm.xml

<?xml version= "1.0"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "> <!--generated 2014-12-28 22:18:36 by hibernate Tools 3.4.0.CR1--> <  Hibernate-mapping> <!--The class name of the name-persistence class, the table name for a table datasheet, MySQL case-insensitive--> <class name= "Org.hibernate.entity.User"
            table= "User" > <!--map the id attribute in the user class to the primary key column in datasheet user user_id--> <id name= "id" type= "int" > <column name= "user_id"/> <generator class= "native"/> </id> <!--map US The ER class's Name property--> <property name= "name" type= "java.lang.String" > <column name= "name" Length= " /> </property> <!--map the password properties of the user class--> <property name= "Password" ja Va.lang.String "> <column name=" PASSWORD "length=" "/> </property> <!--map U The type attribute of the Ser class--> <property name= "type" type= "java.lang.String" > <column name= "type" length= "6"/>
 </property> </class>  

5. Write Hibernate.cfg.xml configuration file

We have created a new Hibernate.cfg.xml profile with the Hibernate Tools Wizard tool, but we can also name the Hibernate.cfg.xml by creating an XML file directly under the SRC directory. Now we need to edit this file, add some configuration, the modified file is as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <!
                                         DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >  

6. Writing auxiliary tools class Hibernateutil.java

Package org.hibernate.entity;
Import org.hibernate.HibernateException;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;

Import org.hibernate.cfg.Configuration;
	public class Hibernateutil {private static sessionfactory sessionfactory; Creates a thread local variable ThreadLocal, which is used to save Hibernate session private static final threadlocal<session> threadlocal=new
	Threadlocal<session> ();
			Use static code block to initialize hibernate static {try {//Read configuration file Configuration cfg=new Configuration (). Configure ();
		Create Sessionfactory sessionfactory=cfg.buildsessionfactory ();
		}catch (Throwable ex) {throw new Exceptionininitializererror (ex);
	}///Get Sessionfactory instance public static Sessionfactory Getssessionfactory () {return sessionfactory; }//Get Threadlocal Object managed session public static sessions Getssession () throws Hibernateexception {session session= (Sessi
		ON) Threadlocal.get (); if (session==null| |! Session.isopen ()) {if (sessionfactory==null) {RebuildsessioNfactory ();
			///Create Session object by Sessionfactory object session= (sessionfactory!=null)? Sessionfactory.opensession (): null;
		Saves the session object to the thread local variable threadLocal threadlocal.set (session);
	return to session; }//Close session instance public static void CloseSession () {//) Gets the session instance session session= (Sessio, previously deposited from the thread local variable threadlocal).
		n) threadlocal.get ();
		Threadlocal.set (NULL);
		if (session!=null) {session.close (); }//Rebuild sessionfactory public static void Rebuildsessionfactory () {Configuration configuration=new Configuration ()
		;
		Configuration.configure ("/hibernate.cfg.xml");
	Sessionfactory=configuration.buildsessionfactory ();
	//Turn off caching and connection pooling public static void shutdown () {getssessionfactory (). Close ();
 }
}

7. Write DAO layer Interface Userdao.java

Package Org.hibernate.dao;

Import Org.hibernate.entity.User;

Public interface Userdao {

	void Save (user user);
	User FindByID (int id);
	void Delete (user user);
	void update (user user);
}

8. Write DAO layer implementation class Userdaoimpl.java

Package Org.hibernate.dao;
Import org.hibernate.Session;
Import org.hibernate.Transaction;
Import Org.hibernate.entity.HibernateUtil;

Import Org.hibernate.entity.User;  public class Userdaoimpl implements Userdao {//Add user @Override public void Save (user user) {//TODO auto-generated
		Method Stub//Create session Instance Session session = Hibernateutil.getssession ();
		Create Transaction instance Transaction tx = Session.begintransaction ();
			try {///Use the session's Save method to save the persisted object to the database Session.save (user);
		Submit transaction Tx.commit ();
			catch (Exception e) {e.printstacktrace ();
		Unexpected exception, rollback transaction tx.rollback ();
		Finally {//close session connection Hibernateutil.closesession ();
		Find user @Override Public user findbyid (int id) {//TODO auto-generated method Stub user = null by ID;
		Session session = Hibernateutil.getssession ();
		Transaction tx = Session.begintransaction ();
			try {///Use the session's Get method to obtain the user = (user) Session.get (user.class, id) of the specified ID;
	Tx.commit ();	catch (Exception e) {e.printstacktrace ();
		Tx.rollback ();
		finally {hibernateutil.closesession ();
	return to user; }//Remove user @Override public void Delete (user user) {//TODO auto-generated a stub session = Hibernate
		Util.getssession ();
		Transaction tx = Session.begintransaction ();
			try {//Use the session's Delete method to delete the persisted object Session.delete (user);
		Tx.commit ();
			catch (Exception e) {e.printstacktrace ();
		Tx.rollback ();
		finally {hibernateutil.closesession (); }///modify user Information @Override public void update (user user) {//TODO auto-generated a stub session = Hibe
		Rnateutil.getssession ();
		Transaction tx = Session.begintransaction ();
			try {//Update Persistent object Session.update (user) with the session's Update method;
		Tx.commit ();
			catch (Exception e) {tx.rollback ();
		E.printstacktrace ();
		finally {hibernateutil.closesession ();
 }
	}

}

With the above steps, a hibernate project is completed, let's test it.

9. Writing test class Usertest.java

Right-click on the Hibernatedemo item name, select Properties, select the Java Build path option on the left side of the pop-up window, and then select the libraries tag in the right-hand side and click the Add Library button. Select JUnit in the pop-up window, as shown in the following illustration:



Then click Next, select JUnit 4 in the Version column, and click Finish. So the JUnit package is introduced into the project.

Next, create a new org.hibernate.test package in your project, right-click on the package name, select the New->junit test Case menu, fill in the pop-up window with the name of the test class and the name of the class you want to test (this requires complete package name), as shown in the following illustration:



Click on the Next button to select the method you want to test and select it as needed.



Click Finish, the system will automatically generate the framework of the Usertest class, which contains some empty methods, we will need to test the methods to rewrite it.

Here, take the Save method as an example, overriding the Testsave method.

Package org.hibernate.test;

Import Org.hibernate.dao.UserDAO;
Import Org.hibernate.dao.UserDAOImpl;
Import Org.hibernate.entity.User;
Import Org.junit.AfterClass;
Import Org.junit.Before;
Import Org.junit.Test;

public class Usertest {

	@AfterClass public
	static void Teardownafterclass () throws Exception {
	}

	@ Before public
	void SetUp () throws Exception {
	}

	//@Test annotation table name is a test method
	@Test public
	Void Testsave () {
		Userdao userdao=new userdaoimpl ();
		try{
			User u=new User ();
			Sets the individual properties of the user Object
			U.setid.
			U.setname ("Zhangsan");
			U.setpassword ("123456");
			U.settype ("admin");
			Use the Userdaoimpl Save method to deposit the user object into the database
			userdao.save (u);
		} catch (Exception e) {
			e.printstacktrace ();}}}

Next, right-click on the name of the Usertest.java file, select the Run as->junit Test menu, and we can see the test results in Eclipse's Junit view, if the progress bar is correct, the result is correct, and if the progress bar is red, it indicates an error , we can see what's wrong.


Then we went to the database to see if the data was correctly saved to the database.

Mysql> select * from user;
+---------+----------+----------+-------+
| user_id | NAME     | PASSWORD | TYPE  |
+---------+----------+----------+-------+
|       1 | Zhangsan | 123456   | admin |
+---------+----------+----------+-------+
One might wonder why the Usertest class has an ID of 20, and the result is 1 in the database.

Because we set the ID as the primary key in the User.hbm.xml file, as follows:

    	<!--map the id attribute in the user class to the primary key column in datasheet user user_id-->
        <id name= "id" type= "int" >
            <column name= "User_" ID "/>
            <generator class=" native "/>
        </id>
Where the generator element refers to the primary key generation policy, Hibernate assigns a value to the ID according to the primary key generation policy and does not store the ID value in the program to the database.


Finally, with the above project, let's look at how Hibernate works:

(1) Hibernate initialization, creating configuration objects.

(a) Read the configuration information from the Hibernate configuration file hibernate.properties or Hibernate.cfg.xml, and store it in the configuration object.

(b) Load the mapping files of all entity classes into the configuration object according to the mapping element in the configuration file.

Description : Hibernate can take two forms of configuration file, one is Hibernate.properties file, the other is Hibernate.cfg.xml file. The two files are essentially the same, and they can all be configured for Hibernate, and in actual development, more XML-formatted configuration files are used. If both configuration files are present and have the same configuration information, the configuration in Hibernate.cfg.xml overrides the configuration in Hibernate.properties, which is explained by the code. Look at the following code:

Configuration cfg=new Configuration (). Configure ();
This is the code that creates the configuration instance and reads the configuration file.

When the new Configuration () method is executed, hibernate looks for hibernate.properties files in the classpath root directory. If the file is found, all hibernate.* properties are loaded into the configuration object. When the Configure () method is invoked, Hibernate looks for hibernate.cfg.xml in the classpath root directory. Throw a hibernateexception if it is not found. If some of the properties and hibernate.properties in the hibernate.cfg.xml are duplicated, they are overwritten.

(2) Create a sessionfactory instance.

The configuration object stores the configuration information in Sessionfactory's properties, creates the Sessionfactory instance, and the configuration object's mission ends. The association between Sessionfactory and configuration is also disconnected. Sessionfactory acts as a proxy for the data source and is responsible for creating the Session object.

Sessionfactory instance is globally unique, it corresponds to the data source in the application, a data source requires only one sessionfactory instance, and only one sessionfactory instance is established for each data source when there are multiple data sources in the application. The Sessionfactory instance is heavyweight, creating and destroying consumes more resources and is therefore created only once. Multiple session instances can be obtained through sessionfactory. Sessionfactory are thread-safe and can be shared by multiple threads. Sessions are not thread-safe, and multiple concurrent threads can operate on one session instance at the same time, often using the threadlocal mode to manage the session.

(3) Create a session instance and establish a database connection.

Sessionfactory can create a session in two ways.

A) Opensession () method. This method creates a new session instance directly, and you need to call the Close method to turn it off manually when you are finished using it.

b) getcurrentsession () method. The session instance created by this method is bound to the current thread and is automatically closed after a transaction commit (commit) or rollback (rollback). Use this method to add the following configuration to the Hibernate.cfg.xml configuration file:

  <!--If you are using a local transaction-->
  <propertyname= "Hibernate.current_session_context_class" >thread</property >
  <!--If you are using global transaction-->
  <propertyname= "Hibernate.current_session_context_class" >jta</ Property>

(4) Create a transaction instance and start a transaction.

The hibernate transaction is the encapsulation of the underlying transaction of the database, and it is necessary to create a transaction object in the process of adding, deleting and modifying Hibernate, a transaction is an atomic operation.

(5) Using the method of session to persist the operation. Persisting entity objects into the database.

(6) Commit the transaction.

(7) Close the session and disconnect from the database.

Project source code point this download: Hibernatedemo

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.