Hibernate is an open-source ORM framework that, as its name implies, is the core idea of ORM (Object relational Mapping, objects relational mapping) that can manipulate the information in the database through objects, and it is said that developers are not familiar with database SQL statements at first. This also creates the power of hibernate, which does not force developers to be familiar with SQL statements or manipulate databases, and hibernate can automatically generate SQL statements for automatic execution.
Hibernate allows developers to fully use the surface thinking object to manipulate the database, so the next demonstration will not have a SQL statement, if there is, please do not say this sentence!
In this paper, hibernate is used to realize the basic additions and deletions to a person data table.
Preparatory work
Environment: Win7+eclipse
Toolkit: Hibernate package, can go to http://hibernate.org/orm/downloads/download, this example is used in version 4;
Database Connection Driver package, this example uses the MySQL
Program Structure diagram
Pojo layer Entity Class
Package Demo.pojo;
public class Person {
Private Integer ID;
private String name;
Private String gender;
Private Integer age;
Public Integer getId () {
return ID;
}
public void SetId (Integer id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String Getgender () {
return gender;
}
public void Setgender (String gender) {
This.gender = gender;
}
Public Integer Getage () {
return age;
}
public void Setage (Integer age) {
This.age = age;
}
@Override
Public String toString () {
return "person [id=" + ID + ", name=" + name + ", gender=" + Gender + ", age=" + Age + "]";
}
}
Core configuration file Hibernate.cfg.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE hibernate-configuration Public
"-//hibernate/hibernate Configuration DTD 3.0//en"
"Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<session-factory>
<!--The following four lines are: Database driver class, DriverManager get connection parameter URL, user name, password--
<property name= "Connection.driver_class" >com.mysql.jdbc.Driver</property>
<property name= "Connection.url" >jdbc:mysql://127.0.0.1/web?characterEcoding=utf-8</property>
<property name= "Connection.username" >root</property>
<property name= "Connection.password" >123456</property>
<!--set the dialect, Hibernate generates SQL statements corresponding to the database type--
<property name= "dialect" >org.hibernate.dialect.MySQLDialect</property>
<!--console Displays the generated SQL statement, which defaults to false--
<property name= "Show_sql" >true</property>
<!--map configuration source file Location--
<mapping resource= "Demo/pojo/person.hbm.xml"/>
</session-factory>
mapping Files Person.hbm.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE hibernate-mapping Public
"-//hibernate/hibernate Mapping DTD 3.0//en"
"Http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<!--name is the full name of the entity class, table is the data table name--
<class name= "Demo.pojo.Person" table= "Person" >
<id name= "id" column= "id" >
<!--primary key generation, native is let hibernate automatically recognize-
<generator class= "native" ></generator>
</id>
<!--
Note the point:
The 0.name value is the attribute name in the entity class, and column is the field name in the data table;
1. When the attribute name in the entity class is the same as the corresponding data table field name, the following column can be omitted, and hibernate will automatically match, for example, age below;
2. Conversely, when the attribute name in the entity class is different from the corresponding data table field, both items must be written, such as the following gender and sex
-
<property name= "name" column= "name" ></property>
<property name= "gender" column= "sex" ></property>
<property name= "Age" ></property>
</class>
Session Factory class
Package demo.util;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.cfg.Configuration;
Import Org.hibernate.service.ServiceRegistry;
Import Org.hibernate.service.ServiceRegistryBuilder;
public class Hibernatesessionfactory {
private static Sessionfactory factory;
private static threadlocal<session> thread = new threadlocal<session> ();
private static String Path = "Hibernate.cfg.xml";
private static Configuration Config = new configuration ();
static {
Config.configure (path);
Serviceregistry service = new Serviceregistrybuilder ()//define a services keygen
. Applysettings (Config.getproperties ()). Buildserviceregistry ();
Factory = config.buildsessionfactory (service);//create Session factory class
}
/**
* Create a session from Hibernate's Session factory class
* @return
* */
public static Session getsession () {
Session session = Thread.get ();
if (session = = NULL | |!session.isopen ()) {
Session = Factory.opensession ();
Thread.set (session);
}
return session;
}
public static void CloseSession () {
Session session = Thread.get ();
if (session! = NULL && session.isopen ()) {
Session.close ();
Thread.set (NULL);
}
}
}
Methods of the DAO layer encapsulating Data operations
Package Demo.dao;
Import java.io.Serializable;
Import org.hibernate.Session;
Import org.hibernate.Transaction;
Import Demo.pojo.Person;
Import Demo.util.HibernateSessionFactory;
public class Persondaoimpl {
Add or delete change, here to increase as an example
Public boolean Add (person p) {
Session session = Hibernatesessionfactory.getsession ();//Create Session
Transaction trans = Session.begintransaction ();//Open transaction
try {
Serializable id = session.save (p);//add record and get primary key value
System.out.println (id+ "is the primary key value obtained");//console View primary key value
Trans.commit ();//Commit a transaction
return true;
} catch (Exception e) {
Trans.rollback ();//Get exception, transaction rollback
} finally {
Hibernatesessionfactory.closesession ();//Close session
}
return false;
}
}
Test class Testperson
Package demo.test;
Import Org.junit.Test;
Import Demo.dao.PersonDaoImpl;
Import Demo.pojo.Person;
public class Testperson {
@Test
public void Testadd () {
Create a Human object
Person p = new person ();
P.setname ("Zhang San");
P.setgender ("male");
P.setage (18);
To create a DAO layer class object and invoke the Add method
Persondaoimpl dao = new Persondaoimpl ();
Dao.add (P);
}
}
A simple hibernate chestnut