http://hibernate.org/downloads
You are redirected to SourceForge download page:http://sourceforge.net/projects/hibernate/files/hibernate4/
At the time of writing this tutorial, the latest version of Hibernate is 4.1.5.SP1. Download the zip archive hibernate-release-4.1.5.SP1.zip and extract it to a desired location on your computer. The distribution has a lot of stuff but we are interested in only the required JAR files which are under lib\required directory:create database contactdb; use contactdb; CREATE TABLE `contact` ( `contact_id` INT NOT NULL , `name` VARCHAR(45) NOT NULL , `email` VARCHAR(45) NOT NULL , `address` VARCHAR(45) NOT NULL , `telephone` VARCHAR(45) NOT NULL , PRIMARY KEY (`contact_id`) ) DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;From the above script, we can see that a contact has following information:
<?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"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/contactdb</property> <property name="connection.username">root</property> <property name="connection.password">P@ssw0rd</property> </session-factory> </hibernate-configuration>We specify JDBC class driver name (for MySQL), connection URL (which also specifies host name, port number, and database name), user name and password to connect to the database.The class org.hibernate.cfg.Configuration is used to load the configuration file:
Configuration conf = new Configuration().configure();The configure() method reads configuration from hibernate.cfg.xml file under program’s classpath.There are also some overloaded versions of configure() method which allow you to load configuration file in different ways.The above configuration is only for necessary information. In addition, Hibernate provides a variety of settings such as connection pooling, transaction, debugging… however we don’t cover all of them in this simple tutorial. Just add this line to the hibernate.cfg.xml file:
<property name="show_sql">true</property>which tells Hibernate to show all SQL statements to the standard output.
package com.mycompany; public class Contact { private int id; private String name; private String email; private String address; private String telephone; public Contact() { } public Contact(int id, String name, String email, String address, String telephone) { this.id = id; this.name = name; this.email = email; this.address = address; this.telephone = telephone; } public Contact(String name, String email, String address, String telephone) { this.name = name; this.email = email; this.address = address; this.telephone = telephone; } 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } }It’s just a simple class following JavaBean naming convention.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.mycompany"> <class name="Contact" table="CONTACT"> <id name="id" column="CONTACT_ID"> <generator class="increment"/> </id> <property name="name" type="string" column="NAME"/> <property name="email"/> <property name="address"/> <property name="telephone"/> </class> </hibernate-mapping>As you can see:
<mapping resource="com/mycompany/Contact.hbm.xml"/>The hibernate.cfg.xml file should look like this till now:
<?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"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/contactdb</property> <property name="connection.username">root</property> <property name="connection.password">P@ssw0rd</property> <property name="show_sql">true</property> <mapping resource="com/mycompany/Contact.hbm.xml"/> </session-factory> </hibernate-configuration>
Configuration configuration = new Configuration().configure(); ServiceRegistryBuilder registry = new ServiceRegistryBuilder(); registry.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = registry.buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession();The Sessioninterface defines a number of methods for executing CRUD operations with mapped objects. The following table lists the most common methods provided by the session:
# | Method name | Return | Description | Issued SQL statement |
1 | beginTransaction() | Transaction | Creates a Transaction object or returns an existing one, for working under context of a transaction. | |
2 | getTransaction() | Transaction | Returns the current transaction. | |
3 | get(Class class, Serializable id) | Object | Loads a persistent instance of the given class with the given id, into the session. | SELECT |
4 | load(Class class, Serializable id) | Object | Does same thing as get() method, but throws an ObjectNotFound error if no row with the given id exists. | SELECT |
5 | persist(Object) | void | saves a mapped object as a row in database | INSERT |
6 | save(Object) | Serializable | Does same thing as persist() method, plus returning a generated identifier. | INSERT |
7 | update(Object) | void | Updates a detached instance of the given object and the underlying row in database. | UPDATE |
8 | saveOrUpdate(Object) | void | Saves the given object if it does not exist, otherwise updates it. | INSERT or UPDATE |
9 | delete(Object) | void | Removes a persistent object and the underlying row in database. | DELETE |
10 | close() | void | Ends the current session. | |
11 | flush() | void | Flushes the current session. This method should be called before committing the transaction and closing the session. | |
12 | disconnect() | void | Disconnects the session from current JDBC connection. |
session.beginTransaction(); try { session.persist(Object); session.update(Object); session.delete(Object); } catch (Exception ex) { session.getTransaction().rollback(); } session.getTransaction().commit(); session.close();When working with transaction, it requires committing the transaction to make permanent changes to the database, and finally, close the session.
To persist an object into the session (equivalent to inserting a record into the database), either persist()or save() method can be used. For example:
Contact contact1 = new Contact("Nam", "hainatuatgmail.com", "Vietnam", "0904277091"); session.persist(contact1); Contact contact2 = new Contact("Bill", "billatgmail.com", "USA", "18001900"); Serializable id = session.save(contact2); System.out.println("created id: " + id);
The save method returns id of the new record inserted in the database.
Read:To retrieve a persistent object from the database into the session (equivalent to selecting a record from the database), use the get() method. For example:
Contact contact = (Contact) session.get(Contact.class, new Integer(2)); if (contact == null) { System.out.println("There is no Contact object with id=2"); } else { System.out.println("Contact3's name: " + contact.getName()); }
The get()method returns null if there is no row with the given id exists in the database, whereas the load() method throws an ObjectNotFound error. Therefore, use the load() method only when the object is assumed exists.
Update:To update a persistent object which is already loaded in the session (attached instance), simply update the mapped object. Hibernate will update changes to the database then the session is flushed. For example:
Contact contact = (Contact) session.load(Contact.class, new Integer(5)); contact.setEmail("infoatcompany.com"); contact.setTelephone("1234567890");
You can call the update() method explicitly (but not required):
session.update(contact);
To update a detached instance, call either the update() or saveOrUpdate() method, for example:
Contact contact = new Contact("Jobs", "jobsatapplet.com", "Cupertino", "0123456789"); session.update(contact);
Both the update() or saveOrUpdate() methods throws a NonUniqueObjectException exception if there is a different object with the same identifier value was already associated with the session. For example, the update() statement in the following code throws such exception:
Contact contact = (Contact) session.load(Contact.class, new Integer(3)); Contact contactUpdate = new Contact(3, "Jobs", "jobsatapplet.com", "Cupertino", "0123456789"); session.update(contactUpdate); // will throw NonUniqueObjectException
Delete: To delete an object with a given identifier, use the delete() method, for example:
Contact contactToDelete = new Contact(); contactToDelete.setId(4); session.delete(contactToDelete);
or delete a loaded instance:
Contact contactToDelete = (Contact) session.load(Contact.class, new Integer(4)); session.delete(contactToDelete);
The delete() method throws a StaleStateException exception if there is no row with the given identifier exists in the database, and a NonUniqueObjectException exception if there is a different object with the same identifier value was already associated with the session.
package com.mycompany; import java.io.Serializable; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; /** * A sample program that demonstrates how to perform simple CRUD operations * with Hibernate framework. * @author www.codejava.net * */ public class ContactManager { public static void main(String[] args) { // loads configuration and creates a session factory Configuration configuration = new Configuration().configure(); ServiceRegistryBuilder registry = new ServiceRegistryBuilder(); registry.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = registry.buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); // opens a new session from the session factory Session session = sessionFactory.openSession(); session.beginTransaction(); // persists two new Contact objects Contact contact1 = new Contact("Nam", "hainatuatgmail.com", "Vietnam", "0904277091"); session.persist(contact1); Contact contact2 = new Contact("Bill", "billatgmail.com", "USA", "18001900"); Serializable id = session.save(contact2); System.out.println("created id: " + id); // loads a new object from database Contact contact3 = (Contact) session.get(Contact.class, new Integer(1)); if (contact3 == null) { System.out.println("There is no Contact object with id=1"); } else { System.out.println("Contact3's name: " + contact3.getName()); } // loads an object which is assumed exists Contact contact4 = (Contact) session.load(Contact.class, new Integer(4)); System.out.println("Contact4's name: " + contact4.getName()); // updates a loaded instance of a Contact object Contact contact5 = (Contact) session.load(Contact.class, new Integer(5)); contact5.setEmail("info1atcompany.com"); contact5.setTelephone("1234567890"); session.update(contact5); // updates a detached instance of a Contact object Contact contact6 = new Contact(3, "Jobs", "jobsatapplet.com", "Cupertino", "0123456789"); session.update(contact6); // deletes an object Contact contact7 = new Contact(); contact7.setId(7); session.delete(contact7); // deletes a loaded instance of an object Contact contact8 = (Contact) session.load(Contact.class, new Integer(8)); session.delete(contact8); // commits the transaction and closes the session session.getTransaction().commit(); session.close(); } }As you can see, there are no SQL statements have to be written to interact with the database, because Hibernate hides all the complex details and exposes its simple and intuitive API. Thus you are free of writing repetitive SQL queries and check their syntax. Working with Hibernate will involve mainly with defining the entities, the mapping, and the association among entities in your application.The project’s structure looks like the following screenshot: Run the program:Right click on the ContactManager.java file, select Run As > Java Application. The program produces some output in Eclipse’s Console view, as in the following screenshot:As you can see, the text in red is the debugging information of Hibernate, the text in black is the program’s output, and we can see Hibernate issues these SQL statements: select, insert, update and delete.You can download the sample application as an Eclipse project in the attachment section at the end of this tutorial.