The Hibernate Annotations Example in Eclipse tutorial shows you how to create hibernate 4 application with standard JPA annotations. This application will performs CRUD operations on database.
The Java Persistence API (JPA) is a Java application programming interface specification that describes the management of relational data in applications. And Hibernate implements this JPA specification. Hibernate also supports it’s own non-standard annotations to work with. I recommend you to work with Standards and use standard annotations.
Other interesting posts you may like
Create database Table
The stuff that we need to do before creating the Hibernate Annotations 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 Annotations Example 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>HibernateWithAnnotation</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>HibernateWithAnnotation</name> <properties> <hibernate.version>4.3.6.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. This POJO class uses standard JPA annotations.
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 |
package com.javabycode.hibernate.model; import java.io.Serializable; import java.util.Date; 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 @Table(name = "STUDENT") public class Student implements Serializable { private static final long serialVersionUID = 6832006422622219737L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "NAME", nullable = false) private String name; @Column(name = "ENTERING_DATE", nullable = false) private Date enteringDate; @Column(name = "NATIONALITY", nullable = false) private String nationality; @Column(name = "code", 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(Date enteringDate) { this.enteringDate = enteringDate; } public void setNationality(String nationality) { this.nationality = nationality; } public String getCode() { return code; } public Date 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 + "]"; } } |
Let’s dig deeper:
@Entity indicates that this class is Entity Bean.
@Table indicates that database table will be mapped with this class. You can specify catalog and schema attributes with this annotation. @Table annotation is optional and unqualified class name is used as table name in this case.
@Id indicates that the field or group of fields is primary key of entity.
@GeneratedValue may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation. GenerationType depends on the underlying database. For example, on MySQL, IDENTITY is supported (strategy = GenerationType.IDENTITY) and on Oracle SEQUENCE is supported (strategy = GenerationType.SEQUENCE).
@Column idicates that the class field will map with the column name in database table. This annotation is optional too and field name will be used as column name in this case. It also supports other attributes like unique, nullable, name & length.
Finally, don’t forget to It is a good practice and is required to work with collections or detached instances.
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 |
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 Annotations 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 |
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 HibernateExample { @SuppressWarnings("unused") public static void main(String[] args) { HibernateExample application = new HibernateExample(); /* * 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 all on the Hibernate Annotations Example in Eclipse tutorial.
Download complete source code, following the below link
HibernateExampleWithAnnotation.zip (298 downloads)