import org.hibernate.Session;
import org.hibernate.Transaction;
public class Main {
public static void main(String[] args) {
// Create
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
// Create Department
Department department = new Department("IT");
// Create Employees
Employee emp1 = new Employee("Alice");
Employee emp2 = new Employee("Bob");
// Add Employees to Department
department.setEmployees(Arrays.asList(emp1, emp2));
emp1.setDepartment(department);
emp2.setDepartment(department);
// Save Department (Employees will also be saved due to CascadeType.ALL)
session.persist(department);
transaction.commit();
session.close();
// Read
session = HibernateUtil.getSession();
department = session.get(Department.class, 1L);
System.out.println("Department: " + department.getName());
for (Employee emp : department.getEmployees()) {
System.out.println("Employee: " + emp.getName());
}
session.close();
// Update
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
department = session.get(Department.class, 1L);
if (department != null) {
department.setName("Engineering");
session.merge(department);
}
transaction.commit();
session.close();
// Delete
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
department = session.get(Department.class, 1L);
if (department != null) {
session.remove(department); // This will also delete employees due to CascadeType.ALL
}
transaction.commit();
session.close();
HibernateUtil.shutdown(); // Close sessionFactory
}
}