I. Preface
A long time ago has been understanding of hibernate, in the project has been a simple application, basic understanding of Hibernate simple application, no in-depth understanding, to shine Company nearly three months, the company's ORM framework is used Hiberante, It simply encapsulates the hibernate framework application and improves the efficiency of the development. Today I looked at some hiberbate based on the original ecological SQL query, harvested a lot, so decided to set up a hibernate small application example, to carry out in-depth study.
Two. Illustrative examples
This small example is based on the product category, the product two sheets to build, is a common Java project, project structure such as:
Three. Preparation before development
This small example is based on jdk1.7, which uses po-based annotations to reduce Hibernate's configuration file, and why it is annotated, because the configuration file for an ORM-mapped data was previously configured in the Hibernate configuration file that the project has been using, but is generally developed in a commented manner in enterprise development , reduce configuration files, use code to structure clearly, facilitate team development.
1. Create a common Java project, under the root directory, create two folders, Docs, Lib,docs one to store in the document, containing the development notes, database creation Basic. The Lib is a jar package.
2. To create the completion project, we should think of download hiberbate development needs of the jar package,Hibernate-3.2.6.ga.jar is hibernate must be the jar,
This small example is developed in the form of annotations, with the need to annotate the jar packages required,Ejb3-persistence.jar, Hibernate-annotations.jar, Hibernate-commons-annotations-3.3.0.ga.jar, Hibernate-entitymanager.jar;
Its Ojdbc7.jar is the drive jar package for Oracle;
The other ones are the jars needed to print the console logs.
Create the corresponding package structure to store in different class and configuration files, this project is relatively simple, do not introduce the specific package of the corresponding class or configuration file.
Four. Hibernate configuration file Description
Create an XML file named: Hibernate.cfg.xml in config and configure the Hinernate
<?xml version= ' 1.0 ' encoding= ' UTF-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibern Ate.sourceforge.net/hibernate-configuration-3.0.dtd "><!--Generated by MyEclipse hibernate Tools. --> Five. Create PO simple Java object class
Package Com.shine.goodsmgr.po;import Java.io.serializable;import Javax.persistence.column;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.id;import Javax.persistence.table;import org.hibernate.annotations.parameter;/** * Method Description: Commodity category PO. */@Entity @org.hibernate.annotations.genericgenerator (name = "seq_category_id", strategy = "sequence", parameters = {@ Parameter (name = "Sequence", value = "seq_category_id")}) @Table (name = "category") public class Categorypo implements Seri alizable {/** * serialized version. */private static final Long serialversionuid = 1l;/** * Category ID. */private Long id;/** * category name. */priva Te String name;public Categorypo () {super ();} Public Categorypo (Long ID, String name) {super (); this.id = Id;this.name = name;} /** * Gets the ID. */@Id @generatedvalue (generator = "seq_category_id") @Column (name = "Id", precision = 16,scale = 0) public Long getId () {Retu RN ID;} /** * Set ID. */public void SetId (Long id) {this.id = ID;} /** * Gets the name. */@Column(name = "name") public String GetName () {return name;} /** * Set name. */public void SetName (String name) {this.name = name;} @Overridepublic String toString () {return "Product Category ID:" +this.id+ ", Product Category name:" +this.name;}}
Special Note: For PO, and note configuration do not understand, you can refer to the previous blog post, to learn, in the Java classification.
Six. Database creation
Generally before the start of the project, the design of the database, in the Java code to write, in order to write the PO class, Java is Object-oriented programming, so Java object is the core of Java.
--Product Category Table CREATE TABLE category ( ID int primary KEY, name VARCHAR2 (254) not NULL);--product category sequence create sequence Seq_categ ory_id;--Commodity Table CREATE TABLE goods ( ID int primary KEY, name VARCHAR2 (254) Not NULL, price number (6,2) not null,< C9/>category int NOT null, constraint fk_goods_category FOREIGN KEY (category) references category (ID));--Commodity sequence Create sequence seq_goods_id;
Seven. Log4j.properties instructions
Log4j.properties is the SQL that is executed in the console print hibernate to log, and so on other information. It is interesting to have a look at the specific configuration information of log4j.properties.
Eight. Create Hibernateutil
The main function is: to get the session, close the session method, get out in the tool class, easy to call.
/** * Class Description: Hibernate tool class. */public class Hibernateutil {private static Sessionfactory factory = Null;static{configuration Configuration = new Annota Tionconfiguration (); Create a configurator configuration.configure ("Com/shine/goodsmgr/config/hibernate.cfg.xml"); factory = Configuration.buildsessionfactory (); Build Session Factory}/** * Method Description: Get session. */public static Session opensession () {return factory.opensession ();} /** * Method Description: Close session. */public static void CloseSession (Session session) {Session.close ();}}
Nine. Create a test class, test based on JUNIT4
Package Com.shine.goodsmgr.test;import static Org.junit.assert.assertnotnull;import Java.util.hashmap;import Java.util.list;import Java.util.map;import Org.apache.commons.lang3.stringutils;import Org.hibernate.hibernateexception;import Org.hibernate.sqlquery;import Org.hibernate.session;import Org.hibernate.transaction;import Org.hibernate.transform.transformers;import Org.junit.Before;import Org.junit.test;import Com.shine.goodsmgr.po.categorypo;import Com.shine.goodsmgr.utils.hibernateutil;public Class Categorytest {Private session session = NULL; @Beforepublic void SetUp () throws Exception {Session = hibernateutil.opensess Ion ();} @Testpublic void Testaddcategory () throws Exception{categorypo Categorypo = new Categorypo (); Categorypo.setname ("Maternity Products" ); Transaction Transaction = null;try{assertnotnull ("Product category cannot be empty!", Categorypo); Transaction = Session.begintransaction (); Open transaction Long categoryId = (long) session.save (CATEGORYPO); SYSTEM.OUT.PRINTLN ("The ID of the product category is:" +categoryid); TraNsaction.commit (); Commit TRANSACTION}catch (Hibernateexception e) {transaction.rollback (); Rollback TRANSACTION e.printstacktrace ();} Finally{hibernateutil.closesession (session);}} @Testpublic void Testloadcategorts () throws exception{transaction Transaction = Null;try{transaction = Session.begintransaction ();//Method one. Categorypo Categorypo = (categorypo) session.get (Categorypo.class, 1L); System.out.println (CATEGORYPO);} catch (Hibernateexception e) {transaction.rollback (); E.printstacktrace ();} Finally{hibernateutil.closesession (session);}} @SuppressWarnings ("unchecked") @Testpublic void Testgetcategort () throws exception{transaction Transaction = null; Long id = 1L; String name = "Electron"; try{transaction = Session.begintransaction (); StringBuilder sqlsb = new StringBuilder () sqlsb.setlength (0); Sqlsb.append ("select * \ n"); Sqlsb.append ("from CATEGORY \ n "); Sqlsb.append (" WHERE id =: id \ n "); Sqlsb.append (" and NAME like:name \ n "); map<string,object> map = new hashmap<string,object> (); if (null! =ID) {map.put ("id", id); } if (Stringutils.isnotblank (name)) {map.put ("name", '% ' +name+ '% '); } sqlquery query = Session.createsqlquery (sqlsb.tostring ()); Hibernate is the default return object type, requiring other types to be manually converted to query.addentity (Categorypo.class); Query.setproperties (map); list<categorypo> Categorypos = Query.list (); for (Categorypo Categorypo:categorypos) {System.out.println (categorypo.tostring ());}} catch (Hibernateexception e) {transaction.rollback (); E.printstacktrace ();} Finally{hibernateutil.closesession (session);}}}
Written in a hurry, some details are not described in detail, in the following Hibernate blog post, will be in the detailed description.
Create a first hiberntae project