Below example explains how to perform Create, Read, Update and Delete (CRUD) operations using Hibernate.
Tools:
Eclipse,
MySQL
Hiberante 4.3.6
Project Structure:
Step1: Creating the POJO class
Step2: Creating the Mapping file (hbm.xml)
Tools:
Eclipse,
MySQL
Hiberante 4.3.6
Project Structure:
Step1: Creating the POJO class
Employee.java
package com.varasofttech.pojo;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = -9001198124094210159L;
// properties
private long id; // identifier
private String name;
private int age;
private float salary;
public Employee() {
super();
}
public Employee(String name, int age, float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
// setters and getters
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age
+ ", salary=" + salary + "]";
}
}
Step2: Creating the Mapping file (hbm.xml)
Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.varasofttech.pojo.Employee" table="employees" >
<id name="id" column="e_id">
<generator class="increment"></generator>
</id>
<property name="name" column="e_name"></property>
<property name="age" column="e_age"/>
<property name="salary" column="e_salary"/>
</class>
</hibernate-mapping>
Step3: Creating the Configuration file (cfg.xml)
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///vara_softtech</property>
<property name="hibernate.connection.username">varasofttech</property>
<property name="hibernate.connection.password">varasofttech</property>
<!-- Dialect class -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Hibernate specific -->
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.format_sql">true</property>
<mapping resource="Employee.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
Step4: Creating the Utility class
HibernateUtil.java
package com.varasofttech.util;
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 = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static void closeSessionFactory() {
if(sessionFactory != null) {
sessionFactory.close();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Step5: Creating the Template class
HibernateTemplate .java
package com.varasofttech.dao.base;
import java.io.Serializable;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.varasofttech.util.HibernateUtil;
public class HibernateTemplate {
private SessionFactory sessionFactory = null;
public HibernateTemplate() {
sessionFactory = HibernateUtil.getSessionFactory();
}
public Serializable save(Object entity) {
Serializable id = null;
Transaction transaction = null;
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
id = session.save(entity);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return id;
}
public Object update(Object entity) {
Transaction transaction = null;
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
session.update(entity);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return entity;
}
public Object findById(Serializable id, Class<?> clas) {
Session session = sessionFactory.openSession();
return session.get(clas, id);
}
public void delete(Serializable id, Class<?> clas ) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Object data = findById(id, clas);
session.delete(data);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public List<?> findAll(Class<?> clas) {
Session session = sessionFactory.openSession();
Query query = session.createQuery( "from " + clas.getName());
return query.list();
}
}
Step6: Creating the Service class
EmployeeService.java
package com.varasofttech.service;
import java.util.List;
import com.varasofttech.dao.employee.EmployeeDAO;
import com.varasofttech.pojo.Employee;
public class EmployeeService {
private EmployeeDAO employeeDAO;
public EmployeeService() {
this.employeeDAO = new EmployeeDAO();
}
public Employee getEmployee(long employeeId) {
return this.employeeDAO.getEmployee(employeeId);
}
public long addEmployee(Employee employee) {
return this.employeeDAO.addEmployee(employee);
}
public void deleteEmployee(long employeeId) {
this.employeeDAO.deleteEmployee(employeeId);
}
public Employee updateEmployee(Employee employee) {
return this.employeeDAO.updateEmployee(employee);
}
public List<Employee> listEmployee() {
return this.employeeDAO.listEmployee();
}
}
Step7: Creating the DAO class
EmployeeDAO.java
package com.varasofttech.dao.employee;
import java.util.List;
import com.varasofttech.dao.base.HibernateTemplate;
import com.varasofttech.pojo.Employee;
public class EmployeeDAO {
private HibernateTemplate hibernateTemplate;
public EmployeeDAO() {
this.hibernateTemplate = new HibernateTemplate();
}
public Employee getEmployee(long employeeId) {
return (Employee) this.hibernateTemplate.findById(employeeId, Employee.class);
}
public long addEmployee(Employee employee) {
return (long) this.hibernateTemplate.save(employee);
}
public void deleteEmployee(long employeeId) {
this.hibernateTemplate.delete(employeeId, Employee.class);
}
public Employee updateEmployee(Employee employee) {
return (Employee) this.hibernateTemplate.update(employee);
}
@SuppressWarnings("unchecked")
public List<Employee> listEmployee() {
return (List<Employee>) this.hibernateTemplate.findAll(Employee.class);
}
}
Step8: Creating the Client class
Application.java
package com.varasofttech.client;
import java.util.List;
import com.varasofttech.pojo.Employee;
import com.varasofttech.service.EmployeeService;
public class Application {
public static void main(String[] args) {
EmployeeService employeeService = new EmployeeService();
Employee employee = new Employee("Ranga", 27, 300000);
System.out.println("Before Saving Employee Info : "+employee);
// CREATE
long employeeId = employeeService.addEmployee(employee);
// READ - Single Record
employee = employeeService.getEmployee(employeeId);
System.out.println("After Saving Employee Info : "+employee);
// READ - Multiple Records
System.out.println("Displaying all Employee Info : ");
List<Employee> employees = employeeService.listEmployee();
for (Employee employee2 : employees) {
System.out.println(employee2);
}
// UPDATE
employee.setName("Ranga Reddy");
employee.setAge(28);
employee = employeeService.updateEmployee(employee);
System.out.println("After Updation Employee Info : "+employee);
// DELETE
employeeService.deleteEmployee(employeeId);
employee = employeeService.getEmployee(employeeId);
System.out.println("After Deletion Employee Info : "+employee);
}
}
Happy Coding!!
0 comments:
Post a Comment