Hibernate learning Notes (3)

Source: Internet
Author: User

Two years ago, I studied hibernate and recorded the learning process of hibernate through a blog, with the following address:

Hibernate learning Notes (1)

Hibernate learning Notes (2)

Recently in review hibernate, in the process of re-learning, there are some new experience and harvest, and now will be a blog for future use as reference material.


First, import the corresponding jar package

Currently hibernate is updated to the 4.x version, after downloading in the official website, find the required folder in the Lib file Plus, additional import of log4j and database driver package is required.


Second, create hibernate configuration file

Create the appropriate hibernate.cfg.xml in the SRC directory to include the appropriate database configuration information in this file, and the Hibernate.cfg.xml file can find the template in the Hibernate download folder.

<! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd ">
Iii. Creating an entity class

public class User {private int id;private string Username;private string password;private string Nickname;<span style= " White-space:pre "></span>//omitting setter and getter method

The entity class is created and the corresponding HBM file needs to be created:

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public        "-//hibernate/hibernate mapping DTD 3.0//en"        "http// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">

and register the User.bhm.xml file in Hibernate's configuration file:

<mapping resource= "Com/hib/model/user.hbm.xml"/>

Iv. creation of Hibernateutil.java class

Create Sessionfactory, which is thread-safe, so the entire sessionfactory should be created based on a singleton pattern.

public class Hibernateutil {private final static sessionfactory FACTORY = Buildsessionfactory ();p rivate static SESSIONFAC Tory buildsessionfactory () {Configuration cfg = new Configuration (). Configure (); Serviceregistry serviceregistry = new Serviceregistrybuilder (). Applysettings (Cfg.getproperties ()). Buildserviceregistry (); Sessionfactory factory = Cfg.buildsessionfactory (serviceregistry); return factory;} public static Sessionfactory Getsessionfactory () {return FACTORY;} public static Session Opensession () {return factory.opensession ();} public static void Close (Session session) {if (session! = NULL) {Session.close ();}}}

v. CRUD Operations

5.1 Test Insert Data

        @Testpublic void Testadd () {session session = NULL; Transaction Transaction = null;try {session = Hibernateutil.opensession (); Transaction = Session.begintransaction (); User U = New User (1, "net", "123456", "Sand Monk", New Date ()), Session.save (U); Transaction.commit ();} catch (Exception e) {e.printstacktrace (); if (session! = NULL) {Transaction.rollback ();}} Finally{hibernateutil.close (session);}}

5.2 Testing the Load method

        @Testpublic void TestLoad () {Session session = Null;try {session = Hibernateutil.opensession (); User U = (user) session.load (user.class, 1); <span style= "font-family:arial, Helvetica, Sans-serif;" >//The SQL statement is issued only when the user is used, otherwise the SQL statement </span>user user = (user) Session.get (user.class, 2); The SQL statement is issued regardless of whether the user is being used} catch (Exception e) {e.printstacktrace ();} Finally{hibernateutil.close (session);}}
Lazy loading: When the load operation is completed, the SQL statement is not issued immediately and SQL is emitted only when the object is used. When the load is completed, it actually returns a proxy object with only one ID in it, so the SQL statement is not emitted if it is just the print ID.
Hibernate's Get method, regardless of whether or not the user is used, emits a SQL statement to query, without the problem of lazy loading.


5.3 Testing the Update method

        @Testpublic void Testupdate () {session session = NULL; Transaction Transaction = null;try {session = Hibernateutil.opensession (); Transaction = Session.begintransaction (); User U = (user) session.load (user.class, 1); U.setnickname ("small Four"); Session.update (U); Transaction.commit ();} catch (Exception e) {e.printstacktrace (); if (session! = NULL) {Transaction.rollback ();}} Finally{hibernateutil.close (session);}}

5.4 Testing the Delete method

        @Testpublic void Testdelete () {session session = NULL; Transaction Transaction = null;try {session = Hibernateutil.opensession (); Transaction = Session.begintransaction (); User U = new user (); U.setid (1); Session.delete (U); Transaction.commit ();} catch (Exception e) {e.printstacktrace (); if (session! = NULL) {Transaction.rollback ();}} Finally{hibernateutil.close (session);}}

5.5 Testing the list method

        @Testpublic void Testlist () {Session session = Null;try {session = Hibernateutil.opensession (); list<user> users = Session.createquery ("from User"). List (); System.out.println (users);} catch (Exception e) {e.printstacktrace ();} Finally{hibernateutil.close (session);}}

5.6 Test Paging

        @Testpublic void Testpager () {Session session = Null;try {session = Hibernateutil.opensession (); list<user> users = Session.createquery ("from User"). Setfirstresult (0). Setmaxresults (2). List (); System.out.println (users);} catch (Exception e) {e.printstacktrace ();} Finally{hibernateutil.close (session);}}

Vi. three states of Hibernate

Temporary state (Transient): Object created with new, it is not persisted, is not in session, the object in this state is called a temporary object;

Persistent State (persistent): persisted and added to the session cache. objects, such as those saved through hibernate statements. The object in this state is called a persistent object;

Free State (Detached): The persisted object is detached from the session object. Objects such as the session cache are emptied. Feature: persistent, but not in session cache. The object in this state is called a free object;

There have been a detailed description of Hibernate's three states, please refer to: http://www.cnblogs.com/xiaoluo501395377/p/3380270.html



Seven, Manytoone one-way

The so-called manytoone relationships, such as student and classroom, have multiple student corresponding to a classroom. A foreign key is generally added on the many side:

public class Classroom {private int id;private String name;private int grade;

public class Student {private int id;private string name;private string no;private classroom classroom;

When adding data, you should add one before adding many:

First add oneclassroom classroom = new Classroom (1, "Computer network"); Session.save (classroom);//Add manystudent STU1 = new Student (1, "Monkey King", "001", classroom); Session.save (STU1); Student STU2 = new Student (1, "Pig", "002", classroom); Session.save (STU2);


<!--Many-to-one is used to map many-to-one, name represents the property name in the object, and column represents the property name--><!--when Cascade is set, the associated object is automatically created, and an associated object is automatically built--><! --if there is no special case, do not use cascade, may use cascade place, is generally one side of the use of the deletion, special requirements will use Cascade, the normal Add method is done by the programmer to add-->< Many-to-one name= "Classroom" column= "CID" cascade= "All" ></many-to-one>


Hibernate learning Notes (3)

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.