Hibernate Hello World Example in Eclipse tutorial will show you how to create simple hibernate CRUD application using MySQL database. The tutorial also demonstrate detailed CRUD operations like saving few records, list all of the persisted records from database, update a record in database and delete a record in database.
Other interesting posts you may like
Create database Table
The stuff that we need to do before creating the Hibernate Hello World Example in Eclipse is MySQL installation on local computer and create database and table. You can aslo use MySQL Workbench or PhpMyAdmin to work with Mysql.
In this example, we create table by executing the script:
1 2 3 4 5 6 7 8 |
CREATE TABLE STUDENT( id INT NOT NULL auto_increment, name TEXT NOT NULL, entering_date DATE NOT NULL, natinality TEXT NOT NULL, code VARCHAR(30) NOT NULL UNIQUE, PRIMARY KEY (id) ); |
Project directory structure
Our Hibernate Hello World Example in Eclipse will have project directory structure like this:
Maven dependency
We will use hibernate and mysql dependency in project and here is our pom.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.hibernate</groupId> <artifactId>HibernateHelloWorldExample</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>HibernateHelloWorldExample</name> <properties> <hibernate.version>4.3.11.Final</hibernate.version> <mysql.version>5.1.31</mysql.version> </properties> <dependencies> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> </project> |
Create Model
We create a simple POJO class named Student which be mapped to STUDENT table in database. This table is created in the above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
package com.javabycode.springmvc.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.annotations.Type; import org.hibernate.validator.constraints.NotEmpty; import org.joda.time.LocalDate; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Size(min=3, max=50) @Column(name = "NAME", nullable = false) private String name; @NotNull @DateTimeFormat(pattern="dd/MM/yyyy") @Column(name = "ENTERING_DATE", nullable = false) @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate") private LocalDate enteringDate; @NotNull @Column(name = "nationality", nullable = false) private String nationality; @NotEmpty @Column(name = "CODE", unique=true, nullable = false) private String code; 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 void setCode(String code) { this.code = code; } public void setEnteringDate(LocalDate enteringDate) { this.enteringDate = enteringDate; } public void setNationality(String nationality) { this.nationality = nationality; } public String getCode() { return code; } public LocalDate getEnteringDate() { return enteringDate; } public String getNationality() { return nationality; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Student)) return false; Student other = (Student) obj; if (id != other.id) return false; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; return true; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", enteringDate=" + enteringDate + ", nationality=" + nationality + ", code=" + code + "]"; } } |
Don’t forget to override hashcode and equals method. It is a good practice and is required to work with collections or detached instances.
Create Hibernate Mapping File
Hibernate need to know the declaration that our java class and fields is mapped to Table and Columns in database. This declaration will be defined in file Student.hbm.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.javabycode.hibernate.model.Student" table="STUDENT"> <id name="id" type="int" column="id"> <generator class="native" /> </id> <property name="name" column="NAME" type="string" /> <property name="enteringDate" column="ENTERING_DATE" type="date" /> <property name="nationality" column="NATIONALITY" type="string" /> <property name="code" column="CODE" type="string" /> </class> </hibernate-mapping> |
This file is placed in the directory src/main/resources folder as shown in project structure above.
Base the above file, Hibernate know that class Student is mapped to table STUDENT. Properties name, enteringDate, nationality, code of class Student will be mapped to columns NAME, ENTERING_DATE, NATIONALITY, CODE of table STUDENT. Id property of Student class is mapped to primary key of table Student and using native generator to tell hibernate can choose any of sequence, identity or hilo algorithm for generating the primary key.
Create Hibernate configuration File
We need to provide for hiberate all stuffs like database dialect, driver class, url and account information to connect database. These stuffs is declared in file hibernate.cfg.xml like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">javabycode</property> <property name="hibernate.connection.password">mypassword</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javabycode</property> <property name="show_sql">false</property> <property name="format_sql">false</property> <mapping resource="com/javabycode/hibernate/model/Student.hbm.xml"></mapping> </session-factory> </hibernate-configuration> |
This file is placed in src/main/resources folder.
Create Hibernate Utility class
For configuring hibernate on startup and managing session factory we create the HibernateUtil class like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.javabycode.hibernate; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateUtil { private static final SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; static { try { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); sessionFactory = new Configuration().configure() .buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Session Factory could not be created." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } |
Create a program to perform CRUD operations on Database
Hibernate works with database by mechanism or steps like this
1. Open session
2. Begin transaction
3. Do something with entities (save/update/delete)
4. Commit transaction
We will also demonstrate these steps in our program. The program will perform CRUD operations like saving few records, list all of the persisted records from database, update a record in database and delete a record in database.
Now we create Hibernate Hello World Example in Eclipse like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
package com.javabycode.hibernate; import java.util.Date; import java.util.List; import org.hibernate.Session; import com.javabycode.hibernate.model.Student; /** * The program performs CRUD operation on database with Hibernate API's * */ public class HelloworldExample { @SuppressWarnings("unused") public static void main(String[] args) { HelloworldExample application = new HelloworldExample(); /* * Dump data by saving few objects with hibernate */ int id1 = application.saveStudent("Bill Gate", new Date(), "USA", "1111111"); int id2 = application.saveStudent("Larry Page", new Date(), "France", "1111112"); int id3 = application.saveStudent("Steve Job", new Date(), "England", "1111113"); int id4 = application.saveStudent("David Pham", new Date(), "Canada", "1111114"); /* * Get all saved objects */ List<Student> students = application.getAllStudents(); System.out.println("\n*******List of all persisted students*******"); for (Student student : students) { System.out.println(student); } /* * Update an object */ application.updateStudent(id3, "Tim Cook"); /* * Deletes an object */ application.deleteStudent(id2); /* * Retrieve all saved objects */ List<Student> remaingStudents = application.getAllStudents(); System.out .println("\n*******List of all remained persisted students*******"); for (Student student : remaingStudents) { System.out.println(student); } } /** * Save a Student object in database */ public int saveStudent(String name, Date enteringDate, String nationality, String code) { Student student = new Student(); student.setName(name); student.setEnteringDate(enteringDate); student.setNationality(nationality); student.setCode(code); Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); int id = (Integer) session.save(student); session.getTransaction().commit(); return id; } /** * List of all persisted Student objects from database */ public List<Student> getAllStudents() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); @SuppressWarnings("unchecked") List<Student> employees = (List<Student>) session.createQuery( "FROM Student s ORDER BY s.id ASC").list(); session.getTransaction().commit(); return employees; } /** * Update a specific Student object */ public void updateStudent(int id, String nationality) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Student student = (Student) session.get(Student.class, id); student.setNationality(nationality); session.update(student); session.getTransaction().commit(); } /** * Delete a specific Student object */ public void deleteStudent(int id) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Student student = (Student) session.get(Student.class, id); session.delete(student); session.getTransaction().commit(); } } |
Run the program and the output should be generated like this:
That’s it on the Hibernate Hello World Example in Eclipse tutorial.
Download complete source code by hitting the below link
HibernateHelloWorldExample.zip (295 downloads)