Software Developer
Hibernate is an ORM (Object-Relational Mapping) that is used to map the gadgets of java instructions with the relational database. It maps the java training to database tables using XML configuration where you do no longer need to put in writing any code.
Hibernate provides two different methods to read data from the database:
Let us now understand the Session.get() using an example.
<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>HibernateGet</groupId>
<artifactId>HibernateGet</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!-- Hibernate 4.3.6 Final -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
</build>
</project>
CREATE DATABASE IF NOT EXISTS tutorialDb;
USE tutorialDb;
DROP TABLE IF EXISTS employee;
CREATE TABLE employee (
emp_id INT(50) NOT NULL AUTO_INCREMENT,
emp_fname VARCHAR(200) DEFAULT NULL,
emp_lname VARCHAR(200) DEFAULT NULL,
emp_age INT(50) DEFAULT NULL,
emp_education VARCHAR(200) DEFAULT NULL,
emp_salary INT(100) DEFAULT NULL,
PRIMARY KEY (emp_id)
);
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="employee")
public class Employee {
@Id
@Column(name = "emp_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int employeeId;
@Column(name = "emp_fname")
private String firstName;
@Column(name = "emp_lname")
private String lastName;
@Column(name = "emp_age")
private int age;
@Column(name = "emp_education")
private String education;
@Column(name = "emp_salary")
private int salary;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString() {
return "Id: " + employeeId + ", Name: " + firstName + " " + lastName + ", Age: " + age + ", Education: " + education + ", Salary:" + salary + "$\n";
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
static Session sessionObj;
static SessionFactory sessionFactoryObj;
private static SessionFactory buildSessionFactory() {
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
public static void createRecord() {
Employee empObj;
int empAge = 26, empSal = 1000;
try {
sessionObj = buildSessionFactory().openSession();
sessionObj.beginTransaction();
for(int j=101; j <= 105; j++) {
empObj = new Employee();
empObj.setFirstName("Editor");
empObj.setLastName(String.valueOf(j));
empObj.setAge(empAge);
empObj.setEducation("Post Graduation");
empObj.setSalary(empSal);
empAge = empAge + 3;
empSal = empSal + 500;
sessionObj.save(empObj);
}
System.out.println("\n.......Records Saved Successfully In The Database.......\n");
sessionObj.getTransaction().commit();
} catch(Exception sqlException) {
if(null != sessionObj.getTransaction()) {
System.out.println("\n.......Transaction Is Being Rolled Back.......");
sessionObj.getTransaction().rollback();
}
sqlException.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
public static void displayRecords() {
int emp_id;
Employee empObj;
try {
sessionObj = buildSessionFactory().openSession();
emp_id=1;
empObj = (Employee)sessionObj.get(Employee.class, new Integer(emp_id));
if(empObj != null) {
System.out.println("\nEmployee Record?= " + empObj.toString());
}
emp_id = 6;
empObj = (Employee)sessionObj.get(Employee.class, new Integer(emp_id));
if(empObj != null) {
System.out.println("\nEmployee Record?= " + empObj.toString());
} else {
System.out.println(empObj);
}
} catch(Exception sqlException) {
if(null != sessionObj.getTransaction()) {
System.out.println("\n.......Transaction Is Being Rolled Back.......");
sessionObj.getTransaction().rollback();
}
sqlException.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
}
package com.jcg.hibernate.get;
public class AppMain {
public static void main(String[] args) {
System.out.println(".......Hibernate Get Example.......\n");
HibernateUtil.createRecord();
HibernateUtil.displayRecords();
System.exit(0);
}
}
<?xml version='1.0' encoding='UTF-8'?>
<hibernate-configuration>
<session-factory>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<!-- Echo All Executed SQL To Console -->
<property name="show_sql">true</property>
<!-- Specifying Session Context -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<!-- Mapping With Model Class Containing Annotations -->
<mapping class="com.jcg.hibernate.get.Employee" />
</session-factory>
</hibernate-configuration>
Hibernate provides different methods to save data into the database:
Let us now understand these using some examples.
<dependencies>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<!-- Hibernate 5.2.6 Final -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.6.Final</version>
</dependency>
</dependencies>
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "CUSTOMER_TBL")
public class Customer {
@Id
@Column(name = "CUST_ID")
private Long id;
@Column(name = "NAME")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.util.HashMap;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
StandardServiceRegistryBuilder registryBuilder =
new StandardServiceRegistryBuilder();
Map<String, String> settings = new HashMap<>();
settings.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
settings.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/SONALI");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "admin");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.hbm2ddl.auto", "update");
registryBuilder.applySettings(settings);
registry = registryBuilder.build();
MetadataSources sources = new MetadataSources(registry)
.addAnnotatedClass(Customer.class);
Metadata metadata = sources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
System.out.println("SessionFactory creation failed");
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
import org.hibernate.Session;
import org.hibernate.Transaction;
public class SessionSaveExample {
public static void main(String[] args) {
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
transaction.begin();
Customer customer = new Customer();
customer.setId(1l);
customer.setName("Sunil");
session.save(customer);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
HibernateUtil.shutdown();
}
}
import org.hibernate.Session;
import org.hibernate.Transaction;
public class SessionPersistExample {
public static void main(String[] args) {
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
transaction.begin();
Customer customer = new Customer();
customer.setId(2l);
customer.setName("Joe");
session.persist(customer);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
HibernateUtil.shutdown();
}
}
import org.hibernate.Session;
import org.hibernate.Transaction;
public class SessionSaveOrUpdateExample {
public static void main(String[] args) {
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
transaction.begin();
Customer customer = new Customer();
customer.setId(3l);
customer.setName("Mike");
session.saveOrUpdate(customer);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
HibernateUtil.shutdown();
}
}