Hibernate CRUD Tutorial

Hibernate CRUD Operation Example:


pom.xml
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-core</artifactId>
	<version>5.4.28.Final</version>
	</dependency>

		
	<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.6</version>
	</dependency>
Teacher.java
package com.deepsingh44.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Teacher {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	private String name;
	private String address;

	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 String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}
Dao.java
package com.deepsingh44.dao;

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;

import com.deepsingh44.model.Teacher;

public class Dao {
	private static StandardServiceRegistry ssr = 
			new StandardServiceRegistryBuilder()
			.configure("hibernate.cfg.xml")
			.build();
	private static Metadata meta = new MetadataSources(ssr)
			.addAnnotatedClass(Teacher.class)
			.getMetadataBuilder()
			.build();
	private static SessionFactory sf = meta.
			getSessionFactoryBuilder().
			build();

	public static SessionFactory getSessionFactory() {
		return sf;
	}
}

TeacherDao.java
package com.deepsingh44.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;

import com.deepsingh44.model.Teacher;

public class TeacherDao {
	private static TeacherDao teacherDao = new TeacherDao();

	public static TeacherDao getTeacherDao() {
		return teacherDao;
	}

	private TeacherDao() {
	}

	public int insert(Teacher teacher) {
		int i = 0;
		Session session = Dao.getSessionFactory().openSession();
		i = (Integer) session.save(teacher);
		session.beginTransaction().commit();
		session.close();
		return i;
	}

	public int delete(Teacher teacher) {
		int i = 0;
		Session session = Dao.getSessionFactory().openSession();
		session.delete(teacher);
		session.beginTransaction().commit();
		session.close();
		return i = 1;
	}

	public int update(Teacher teacher) {
		int i = 0;
		Session session = Dao.getSessionFactory().openSession();
		session.update(teacher);
		session.beginTransaction().commit();
		session.close();
		return i = 1;
	}

	public Teacher fetchTeacher(int id) {
		Teacher teacher = null;
		Session session = Dao.getSessionFactory().openSession();
		teacher = session.get(Teacher.class, id);
		session.close();
		return teacher;
	}

	public List<Teacher> fetchAllTeacher() {
		Session session = Dao.getSessionFactory().openSession();
		@SuppressWarnings("deprecation")
		Criteria cr = session.createCriteria(Teacher.class);
		List<Teacher> ll = cr.list();
		return ll;
	}

	
}
Test.java
package com.deepsingh44.test;

import java.util.List;
import java.util.Scanner;

import com.deepsingh44.dao.TeacherDao;
import com.deepsingh44.model.Teacher;

public class Test {

	public void insert(Teacher teacher) {
	int id = TeacherDao.getTeacherDao().insert(teacher);
	System.out.println((id > 0) ?
		"Successfully Inserted " + id : "Insertion Failed");
	}

	public void delete(int id) {
		Teacher teacher = fetchById(id);
		if (teacher != null) {
		System.out.println(
			(TeacherDao.getTeacherDao().delete(teacher) > 0)
			? "Successfully deleted" : "Deleted failed");
		} else {
			System.out.println("This id is not exist");
		}
	}

	public void update(Teacher teacher) {
	System.out.println(TeacherDao.getTeacherDao().update(teacher) > 0 ?
		"Successfully Update" : "Update Failed");
	}

	public Teacher fetchById(int id) {
		return TeacherDao.getTeacherDao().fetchTeacher(id);
	}

	public void fetchAll() {
		List<Teacher> teachers = TeacherDao.getTeacherDao().
			fetchAllTeacher();
		for (Teacher t : teachers) {
		System.out.println(t.getId() + "\t" + t.getName() + 
				"\t" + t.getAddress());
		}
	}

	public static void main(String[] args) {
	Scanner scanner = new Scanner(System.in);
	Test t = new Test();
	String confirm = "", name = "", address = "";
	int id = 0;
	do {
		System.out.println("press 1 for insert Teacher");
		System.out.println("press 2 for delete Teacher");
		System.out.println("press 3 for update Teacher");
		System.out.println("press 4 for fetchById Teacher");
		System.out.println("press 5 for fetchAll Teachers");
		System.out.println("press 6 for exit");
		System.out.println("Enter your choice : ");
		int choice = scanner.nextInt();
		switch (choice) {
		case 1:
		System.out.println("Enter teacher name");
		name = scanner.next();
		System.out.println("Enter teacher address");
		address = scanner.next();
		Teacher teacher = new Teacher();
		teacher.setName(name);
		teacher.setAddress(address);
		t.insert(teacher);
		break;
		case 2:
		System.out.println("Enter teacher id");
		id = scanner.nextInt();
		t.delete(id);
		break;
		case 3:
		System.out.println("Enter teacher id");
		id = scanner.nextInt();
		System.out.println("Enter teacher name");
		name = scanner.next();
		System.out.println("Enter teacher address");
        address = scanner.next();
		Teacher tt = t.fetchById(id);
		if (tt != null) {
		t.update(tt);
		} else {
		System.out.println("this id is not exist");
		}
		break;
		case 4:
	    System.out.println("Enter teacher id");
		id = scanner.nextInt();
		Teacher ttt = t.fetchById(id);
		if (ttt != null) {
           System.out.println(ttt.getName() + "\t" + ttt.getAddress());
		} else {
			System.out.println("this id is not exist");
		}
		break;
        case 5:
		t.fetchAll();
		break;
		case 6:
		System.exit(0);
		break;
		default:
		System.out.println("Wrong choice");
		}
	System.out.println("Do you want to continue(y/n)");
	confirm = scanner.next();

} while (confirm.equalsIgnoreCase("y"));
}
}

hibernate.cfg.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 5.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-5.0.dtd">

<hibernate-configuration>
<session-factory>

<property name="hibernate.connection.driver_class">com...Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://.../stds</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>

</session-factory>
</hibernate-configuration>

No comments: