Hibernate is an Java Object-Relational Mapping framework to map classes’ objects and database tables’s records. Hibernate provides API to save and select database’s records by Java objects. In the tutorial, JavaSampleApproach will show you way to start Hibernate by Java sample code.
I. Technologies
– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Hibernate: 5.2.10.Final
– MySql database
II. Hibernate
1. Hibernate Configuration
Hibernate requires a configuration file which has 2 parts:
– Database settings are used to establish database connections.
– Mapping files are used to map between Java persistent classes & database tables.
Format:
jdbc:mysql://localhost:3306/testdb ......
1.1 Database settings
Some important properties for database setting:
– hibernate.connection.url
: JDBC url instance
– hibernate.connection.driver_class
: JDBC driver class
– hibernate.connection.username
: database username
– hibernate.connection.password
: database password
– hibernate.dialect
: used to generate the appropriate SQL
1.2 Mapping file
Mapping files are used to map between Java persistent classes & database tables. They are defined in mapping
tag:
What is Hibernate persistent class? -> They are POJO Java classes whose objects will be stored in database tables.
Some requirement for Hibernate persistent classes:
– Must have a default constructor.
– Should have an ID to map the objects and database records.
– All persistent attributes have getXXX and setXXX methods.
Example:
– Having a class Customer.java:
public class Customer { private int id; private String firstName; ... public Customer(){}; public void setId(int id){ this.id = id; } public int getId(){ return this.id; } public void setFirstName(String firstName){ this.firstName = firstName; } public String getFirstName(){ return this.firstName; } ... }
– The mapping file Customer.hbm.xml with Customer class:
...... ...
2. Hibernate Core Classes
– Configuration Object: represents a configuration file – hibernate.cfg.xml
– SessionFactory Object: is used to inturn configures Hibernate (Configuration Object) for the application.
SessionFactory factory = new Configuration().configure().buildSessionFactory();
***Note:The SessionFactory is a thread safe & heavy object. Need one SessionFactory object per database.
– Session Object: is created via SessionFactory Object and used to get a physical database connection. It is lightweight & not thread safe. Session Object should be created when interacting with database then close it.
Session session = factory.openSession(); try{ ... Customer peter = new Customer(1, "Peter", "Smith", 20); // save to database session.save(peter); ... }finally{ session.close(); }
– Transaction Object: is a database unit work. It is created and associated with a Session Object.
Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Customer peter = new Customer(1, "Peter", "Smith", 20); session.save(peter); tx.commit(); }catch(Exception e){ if(null != tx){ tx.rollback(); } }finally{ session.close(); }
III. Practice – XML Mapping File Hibernate
Create a Simple Spring Maven Application, that uses Hibernate to store and retrieve Customer objects from MySQL database.
Step to do
– Create Spring Maven project
– Create persistent class
– Setup Hibernate configuration
– Implement Hibernate Application
– Run & Check Results
1. Create Spring Maven project
Using Spring Tool Suite, create a Simple Spring Maven project.
Modified pom.xml file with Hibernate & MySql dependencies:
4.0.0 org.springframework.samples SpringHibernateStarter 0.0.1 org.hibernate hibernate-core 5.2.10.Final mysql mysql-connector-java 6.0.6
2. Create persistent class
Create a Customer.java:
package com.javasampleapproach.hibernate.model; public class Customer { private int id; private String firstName; private String lastName; private int age; public Customer(){}; public Customer(int id, String firstName, String lastName, int age){ this.id = id; this.firstName = firstName; this.lastName = lastName; this.age = age; } public void setId(int id){ this.id = id; } public int getId(){ return this.id; } public void setFirstName(String firstName){ this.firstName = firstName; } public String getFirstName(){ return this.firstName; } public void setLastName(String lastName){ this.lastName = lastName; } public String getLastName(){ return this.lastName; } public void setAge(int age){ this.age = age; } public int getAge(){ return this.age; } public String toString(){ String info = String.format("Customer info: id = %d, firstname = %s, lastname = %s, age = %d", id, firstName, lastName, age); return info; } }
3. Setup Hibernate configuration
Under /src/main/resources:
– Create Hibernate Configuration file – hibernate.cfg.xml:
jdbc:mysql://localhost:3306/testdb com.mysql.jdbc.Driver root org.hibernate.dialect.MySQLDialect true
– Create a mapping file for Customer class – Customer.hbm.xml:
Mapping between persistent class - Customer with MySQL table - customer
4. Implement Hibernate Application
– Implement 6 functions:
setUpSessionFactory()
: setup Hibernate Session Factory
saveCustomers()
: save Customers to Database by Hibernate
showAllCustomers()
: retrieve all customers from MySQL and show all on console.
updateCustomer(int customerId, int newAge)
: update Customer’s age.
deleteCustomer(int customerId)
: delete a customer
shutdown()
: close Hiberbate Session Factory Object
package com.javasampleapproach.hibernate; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.javasampleapproach.hibernate.model.Customer; public class Application { private static SessionFactory factory = null; public static void main(String[] args) { System.out.println("============Set up Session Factory============"); setUpSessionFactory(); System.out.println("============Save Customers============"); saveCustomers(); System.out.println("============Show Customers============"); showAllCustomers(); System.out.println("============Update Customer - Peter with id = 1 & new age = 21============"); updateCustomer(1, 21); System.out.println("============Delete Customer: Lauren with id = 3============"); deleteCustomer(3); System.out.println("============Show Customers after Update & Delete============"); // show all customer again - after update & delete showAllCustomers(); shutdown(); } public static void setUpSessionFactory() { // create sessionFactory try { factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } } public static void shutdown(){ factory.close(); } public static void saveCustomers(){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); // create customers Customer peter = new Customer(1, "Peter", "Smith", 20); Customer mary = new Customer(2, "Mary", "Taylor", 25); Customer lauren = new Customer(3, "Lauren", "Taylor", 30); // save to database session.save(peter); session.save(mary); session.save(lauren); tx.commit(); }catch(Exception e){ if(null != tx){ tx.rollback(); } }finally{ session.close(); } } public static void showAllCustomers(){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Listcustomers = session.createQuery("FROM Customer").list(); customers.forEach(System.out::println); tx.commit(); }catch(Exception e){ if(null != tx){ tx.rollback(); } }finally{ session.close(); } } public static void updateCustomer(int customerId, int newAge){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); // update Peter: age = 21 Customer cust = session.get(Customer.class, customerId); cust.setAge(newAge); session.update(cust); tx.commit(); }catch(Exception e){ if(null != tx){ tx.rollback(); } }finally{ session.close(); } } public static void deleteCustomer(int customerId){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); // Employee employee = Customer cust = session.get(Customer.class, customerId); session.delete(cust); tx.commit(); }catch(Exception e){ if(null != tx){ tx.commit(); } }finally { session.close(); } } }
5. Run & Check Results
– Create a MySQL Customer table by script:
CREATE TABLE customer( id INT NOT NULL AUTO_INCREMENT, firstname VARCHAR(20) NOT NULL, lastname VARCHAR(20) NOT NULL, age INT NOT NULL, PRIMARY KEY (id) );
– Run the main class Application.java, Logs:
============Save Customers============ Hibernate: insert into customer (firstname, lastname, age) values (?, ?, ?) Hibernate: insert into customer (firstname, lastname, age) values (?, ?, ?) Hibernate: insert into customer (firstname, lastname, age) values (?, ?, ?) ============Show Customers============ Apr 24, 2017 1:02:58 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService INFO: HHH000397: Using ASTQueryTranslatorFactory Hibernate: select customer0_.id as id1_0_, customer0_.firstname as firstnam2_0_, customer0_.lastname as lastname3_0_, customer0_.age as age4_0_ from customer customer0_ Customer info: id = 1, firstname = Peter, lastname = Smith, age = 20 Customer info: id = 2, firstname = Mary, lastname = Taylor, age = 25 Customer info: id = 3, firstname = Lauren, lastname = Taylor, age = 30 ============Update Customer - Peter with id = 1 & new age = 21============ Hibernate: select customer0_.id as id1_0_0_, customer0_.firstname as firstnam2_0_0_, customer0_.lastname as lastname3_0_0_, customer0_.age as age4_0_0_ from customer customer0_ where customer0_.id=? Hibernate: update customer set firstname=?, lastname=?, age=? where id=? ============Delete Customer: Lauren with id = 3============ Hibernate: select customer0_.id as id1_0_0_, customer0_.firstname as firstnam2_0_0_, customer0_.lastname as lastname3_0_0_, customer0_.age as age4_0_0_ from customer customer0_ where customer0_.id=? Hibernate: delete from customer where id=? ============Show Customers after Update & Delete============ Hibernate: select customer0_.id as id1_0_, customer0_.firstname as firstnam2_0_, customer0_.lastname as lastname3_0_, customer0_.age as age4_0_ from customer customer0_ Customer info: id = 1, firstname = Peter, lastname = Smith, age = 21 Customer info: id = 2, firstname = Mary, lastname = Taylor, age = 25 Apr 24, 2017 1:02:58 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/testdb]
– Database records: