Recently in the study of SSH, now see hibernate this piece, hands-on implementation of a simple demo, hibernate function, the use of a preliminary understanding.
1. First copy the Hibernate jar package to the Lib directory of the Web project. Some rely on the jar package, to import additional, such as Cglib-nodep.jar, or will be error.
2. Configure the entity class. Here I am using a simple account class, note that the following annotations are used javax.persistense.*, not org.hibernate.*.
Package Com.jobhelp.domain;import Javax.persistence.column;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.generationtype;import Javax.persistence.Id;import javax.persistence.Table; @Entity//@Entity indicates that the class can be persisted by hibernate @table (name= "user")//data table name for the specified Entity public class Account {@Id//Specifies that the column primary key @generatedvalue (Strategy=generationtype.auto)//auto is the self-growing private Integer Id; @Column (name= "name ") private string Username; @Column (name=" password ") private string Password;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}
3. Create a new hibernate configuration file Hibernate.cfg.xml in the SRC directory. (The MyEclipse Wizard is automatically generated, and I'm using eclipse to create it myself.) )
The contents of Hibernate.cfg.xml are as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hibern Ate.org/dtd/hibernate-configuration-3.0.dtd ">
4. Create a new Hibernate tool class to get the session. Each session in Hibernate represents a complete database operation.Hibernate officially provided by Hibernateutil.java
Package Com.jobhelp.util;import Org.hibernate.sessionfactory;import org.hibernate.cfg.AnnotationConfiguration; public class Hibernateutil {private static final sessionfactory sessionfactory;//sessionfactory//static code block for singleton mode, Initialize hibernate on class load, singleton only initializes once static{try{//entity class loaded from Hibernate.cfg.xml with config//load @ annotation configuration with annotationconfiguration ()// The entity class that loads the XML configuration uses the configuration () Sessionfactory = new Annotationconfiguration (). Configure ("Hibernate.cfg.xml"). Buildsessionfactory ();} catch (Throwable ex) {System.err.println ("Initial sessionfactory Error"); throw new Exceptionininitializererror (ex);}} public static Sessionfactory Getsessionfactory () {return sessionfactory;}}
5, initialize the MySQL database, build a simple user table, I use the table data as follows.Mysql> SELECT * from user;+----+-------+----------+| ID | Name | password |+----+-------+----------+| 1 | admin | 123456 | | 2 | Bowen | 123456 | | 3 | Tom | 123456 | | 4 | Jack | 123456 |+----+-------+----------+
6. Execute Hibernate program. Hibernate is an ORM framework that deals with databases.Hibernate session sessions are similar to the JDBC operations database process.
In contrast to the use of JdbcTemplate in spring, Hibernate does not have to write SQL statements, does not encapsulate the results, is logically clear, and the code is much simpler, which obviously helps to improve development efficiency.
The following is the code that executes the Hibernate program in a test class.
Package Com.jobhelp.util;import Java.util.list;import Org.hibernate.session;import org.hibernate.Transaction; Import Com.jobhelp.domain.account;public class Test {public static void main (string[] agrs) {/*account account =new Accoun T (); Account.setusername ("Jack"); Account.setpassword ("123456"); *///start a hibernate sessionsession session = Hibernateutil.getsessionfactory (). Opensession ();//start a transactiontransaction transaction = Session.begintransaction ();//insert into Database//session.persist, @SuppressWarnings ("All")//hql Querylist<account> list =session.createquery ("from Account"). List (),//print query Resultfor (account Account2: List) {System.out.println (Account2.getid () + ":" +account2.getusername ());} Transaction.commit (); Session.close ();}}
Execution Result:[2014-11-24 21:26:19,083] [DEBUG] [org.hibernate.jdbc.abstractbatcher:366]-About to open preparedstatement (open preparedstatements:0, globally:0) [ 2014-11-24 21:26:19,083][debug][org.hibernate.sql:401]-select Account0_.id as id0_, Account0_.password as password0_, Account0_.name as name0_ from user Account0_hibernate:select account0_.id as id0_, Account0_.password as password0_, Acco Unt0_.name as name0_ from user account0_ ... [2014-11-24 21:26:19,108] [DEBUG] [org.hibernate.engine.statefulpersistencecontext:787]-initializing Non-lazy collections1:admin2:bowen3:tom4:jack [2014-11-24 21:26:19,109] [DEBUG] [org.hibernate.transaction.jdbctransaction:103]-commit ...
Note: Hibernate only generates a table structure, but does not create a database. Hibernate throws an exception if the specified database does not exist.
Simple hibernate access to the database demo