Hibernate 5

Share on:

Here in this post we will be looking into the basic setup of “Hibernate 5” with maven.
In this tutorial we will be using -

  1. Maven
  2. JDK 1.8****
  3. Hibernate 5
  4. MySQL

You can also download/clone the complete workspace from GitHub : - https://github.com/rahulwagh/hibernate5.git

If you are not able to clone the repository than download the complete workspace and import in eclipse using following instruction.

Here in this post we will try to insert an employee entry into the “employee” table which we have created.

SQL Script for “employee” table : -

1CREATE TABLE employee(
2id INT NOT NULL AUTO_INCREMENT,
3employee_name VARCHAR(100) NOT NULL,
4employee_address VARCHAR(40) NOT NULL,
5PRIMARY KEY ( id));

Next step is to create an “Employee” @Entity

 1package com.hibernate.tutorial.entity;
 2
 3import javax.persistence.Column;
 4import javax.persistence.Entity;
 5import javax.persistence.Id;
 6import javax.persistence.Table;
 7
 8@Entity
 9@Table(name = "employee")
10public class Employee {
11
12 @Id
13 @Column(name = "id")
14 Long id;
15
16 @Column(name="employee_name")
17 String employeeName;
18
19 @Column(name="employee_address")
20 String employeeAddress;
21
22 public Employee(Long id, String employeeName, String employeeAddress) {
23  this.id = id;
24  this.employeeName = employeeName;
25  this.employeeAddress = employeeAddress;
26 }
27
28 public Employee() {
29
30 }
31
32 public Long getId() {
33  return id;
34 }
35
36 public void setId(Long id) {
37  this.id = id;
38 }
39
40 public String getEmployeeName() {
41  return employeeName;
42 }
43
44 public void setEmployeeName(String employeeName) {
45  this.employeeName = employeeName;
46 }
47
48 public String getEmployeeAddress() {
49  return employeeAddress;
50 }
51
52 public void setEmployeeAddress(String employeeAddress) {
53  this.employeeAddress = employeeAddress;
54 }
55
56}

Next we need to write a code to insert a record into the table. Refer to following code where we have created following instances

  1. SessionFactory
  2. Session
  3. Transaction
 1package com.hibernate.tutorial.mainclass;
 2
 3import org.hibernate.Session;
 4import org.hibernate.SessionFactory;
 5import org.hibernate.Transaction;
 6import org.hibernate.cfg.Configuration;
 7
 8import com.hibernate.tutorial.entity.Employee;
 9
10public class Hibernate5InsertTest {
11
12 public static void main(String[] args) {
13  SessionFactory sessionFactory;
14  sessionFactory = new Configuration().configure().buildSessionFactory();
15
16  Session session = sessionFactory.openSession();
17
18  Transaction tx = session.beginTransaction();
19
20  Employee emp = new Employee();
21  emp.setId(new Long(1));
22  emp.setEmployeeName("Rahul Wagh");
23  emp.setEmployeeAddress("Indore, India");
24  session.save(emp);
25  tx.commit();
26  session.close();
27 }
28}

Hope this article will help you to setup your Hibernate 5 Workspace.For any issue please post your comments and leave your feedback