📜 ⬆️ ⬇️

Some Hibernate Practice

Since in the process of continuing education, I decided to deal with Hibernate to organize work with databases through the maximum avoidance of using SQL queries, it was decided to form an abstract example. On the one hand, it should be simple, and on the other hand, it should be possible to check the performance of all standard operations that occur when a database is accessed.

Below I present my creation to the court. Initially, I relied on the following material . As for me, it is quite interesting, but it is always interesting to form a complete application, albeit a simple one. So, what happened ...

The original base remained unchanged, as in the above method. image

The list of operations that need to be implemented will look like this:

')
The first step was the formation of mapping to the base. From the material that I reviewed, I realized that there are two ways: using an xml file or using annotations. To simplify perception, a separate xml file for my example for the staff department looks like this:

<?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="logic.Department" table="department" schema="joblist"> <id name="departmentId"> <column name="department_id" sql-type="int(11)"/> <generator class="increment"/> </id> <property name="caption"> <column name="caption" sql-type="text" not-null="true"/> </property> <set name="employies" lazy="false" cascade="all" inverse="true"> <key column="fk_department_id"/> <one-to-many class="logic.Employee"/> </set> </class> </hibernate-mapping> 


Immediately the first disclaimer, the file must contain a header ... <? Xml version = '1.0' encoding = 'utf-8'?>, Etc.

Tried to implement the same thing through annotations that look like this:
 @Entity @Table(name="department") public class Departmant { private long id; private String name; public Department() { } 


Lines starting with @ are annotations. What exactly to use, decide the authors themselves. Both versions have the right to life.

The second employee mapping looks like this:
 <?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="logic.Employee" table="employee" schema="joblist"> <id name="employeeId"> <column name="employee_id" sql-type="int(11)"/> <generator class="increment"/> </id> <property name="fio"> <column name="fio" sql-type="text" not-null="true"/> </property> <many-to-one name="department" class="logic.Department" column="fk_department_id" not-null="true" cascade="save-update"/> </class> </hibernate-mapping> 


Immediately make comments on the formation of relationships. Since the 1- (one-to-many) relationship is used, from the base entity (department) we indicate:
 <set name="employies" lazy="false" cascade="all" inverse="true"> 

The lazy connection to the subordinate table is removed (perhaps this is not entirely correct, I’ll still look), the cascade interaction between the main and subordinate tables is used, and the inversion is turned on, that is, the connection between the tables in both directions, in fact is one connection (as is there is a DBMS).

From the side of the subordinate entity we indicate:
  <many-to-one name="department" class="logic.Department" column="fk_department_id" not-null="true" cascade="save-update"/> 

That is, the key field (foreign key) cannot be zero (ensuring integrity at the database level) and performing cascade operations is allowed to be saved or updated (otherwise, if the employee is removed, his native department will fly off).

The classes “Department” and “Employees” are typical POJOs, as shown in many examples.
 package logic; import java.util.HashSet; import java.util.Set; public class Department { private int departmentId; private String caption; public Department() { } public Department(String caption) { this.caption = caption; } public int getDepartmentId() { return departmentId; } public void setDepartmentId(int departmentId) { this.departmentId = departmentId; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } Set<Employee> employies = new HashSet<Employee>(); public Set<Employee> getEmployies(){ return employies; } public void setEmployies(Set<Employee> employies) { this.employies = employies; } @Override public String toString() { String string = this.departmentId + " " + this.caption; return string; } } 


 package logic; public class Employee { private int employeeId; private String fio; private Department department; public Employee() { } public Employee(String fio) { this.fio = fio; } public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getFio() { return fio; } public void setFio(String fio) { this.fio = fio; } public Department getDepartment() { return department; } public void setDepartment(Department department){ this.department = department; } @Override public String toString() { String string = this.employeeId+ " " + this.fio; return string; } } 


We continue further ... It is necessary to form a class - a factory that will perform a single launch of the configuration and the list of processing methods (interfaces). This is implemented in the form of singletons.

 package factory; import DAO.DepartmentDAO; import DAO.EmployeeDAO; import implement.ImplDepartment; import implement.ImplEmployee; public class Factory { private static DepartmentDAO departmentDAO = null; private static EmployeeDAO employeeDAO = null; private static Factory instance = null; public static synchronized Factory getInstance() { if (instance == null) { instance = new Factory(); } return instance; } public DepartmentDAO getDepartmentDAO() { if (departmentDAO == null) { departmentDAO = new ImplDepartment(); } return departmentDAO; } public EmployeeDAO getEmployeeDAO() { if (employeeDAO == null) { employeeDAO = new ImplEmployee(); } return employeeDAO; } } 


Configuration hibernate - the hibernate.cfg.xml file has the structure:

 <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:mysql://localhost:3306/Joblist</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password">admin</property> <property name="connection.pool_size">1</property> <property name="show_sql">true</property> <property name="current_session_context_class">thread</property> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <mapping resource="logic/Employee.hbm.xml"/> <mapping resource="logic/Department.hbm.xml"/> <mapping class="logic.Department"/> <mapping class="logic.Employee"/> </session-factory> </hibernate-configuration> 


The next step is to create a class to form a work session The usual option, considered in many examples, although it works, but has the status “Deprecated” is not recommended for use. As a result, the connection utility has a slightly different look:

 package utils; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { private static SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; public static final SessionFactory createSessionFactory() { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings( configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } } 


Classes - interfaces for organizing operations with tables, look like this:
 package DAO; import logic.Department; import logic.Employee; import java.io.IOException; import java.sql.SQLException; import java.util.Collection; public interface DepartmentDAO { public void addDepartment(Department department) throws SQLException; public void editDepartment(Department department) throws SQLException; public void deleteDepartment(Integer department) throws SQLException, IOException; public Collection getDepartmentById(Integer department_id) throws SQLException; public Collection getAllDepartments() throws SQLException; public void addEmployee(Department department, Employee employee) throws SQLException; } 


In the second case, I’ll make a reservation right away, not all implemented the methods ...

 package DAO; import logic.Employee; import java.sql.SQLException; import java.util.Collection; public interface EmployeeDAO { public void editEmployee (Employee employee) throws SQLException; public void deleteEmployee (Employee employee) throws SQLException; public Collection getDepartmentByEmployee (Employee employee) throws SQLException; public Collection getAllEmployies() throws SQLException; public void deleteEmployiesByName(String name) throws SQLException; public Collection getEmployiesByDepartment(Integer department) throws SQLException; } 


Further, once there are methods, they must be implemented:

 package implement; import DAO.DepartmentDAO; import logic.Department; import logic.Employee; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import utils.HibernateUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.*; public class ImplDepartment implements DepartmentDAO { @Override public void addDepartment(Department department) throws SQLException { Session session = null; try { session = HibernateUtil.createSessionFactory().openSession(); session.beginTransaction(); session.save(department); session.getTransaction().commit(); } catch (HibernateException exception) { System.out.println("  "); exception.printStackTrace(); } finally { if (session != null && session.isOpen()) { session.close(); } } } @Override public void editDepartment(Department department) throws SQLException { Session session = null; try { session = HibernateUtil.createSessionFactory().openSession(); session.beginTransaction(); session.update(department); session.getTransaction().commit(); } catch (HibernateException exception) { System.out.println("  "); exception.printStackTrace(); } finally { if (session != null && session.isOpen()) { session.close(); } } } @Override public void deleteDepartment(Integer id) throws SQLException, IOException { Session session = null; try { session = HibernateUtil.createSessionFactory().openSession(); session.beginTransaction(); Department department = (Department) session.load(Department.class, id); Employee[] employies = department.getEmployies().toArray(new Employee[]{}); if (employies.length > 0) { System.out.println("   , ?"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String ch = reader.readLine(); if (ch.equals("Y") || (ch.equals("y"))) { session.delete(department); session.getTransaction().commit(); } } else { session.delete(department); session.getTransaction().commit(); } } catch (HibernateException exception) { System.out.println("  "); exception.printStackTrace(); } finally { if (session != null && session.isOpen()) { session.close(); } } } @Override public Collection getDepartmentById(Integer department_id) throws SQLException { Session session = null; List departments = new ArrayList<Department>(); try { session = HibernateUtil.createSessionFactory().openSession(); departments = session.createCriteria(Department.class).add(Restrictions.idEq(department_id)).list(); } catch (HibernateException exception) { System.out.println("  "); exception.printStackTrace(); } finally { if (session != null && session.isOpen()) { session.close(); } } return departments; } @Override public Collection getAllDepartments() throws SQLException { Session session = null; List departments = new ArrayList<Department>(); try { session = HibernateUtil.createSessionFactory().openSession(); departments = session.createCriteria(Department.class).list(); } catch (Exception e) { System.out.println("   "); } finally { if (session != null && session.isOpen()) { session.close(); } } return departments; } @Override public void addEmployee(Department department, Employee employee) throws SQLException { Session session = null; try { session = HibernateUtil.createSessionFactory().openSession(); session.beginTransaction(); department.getEmployies().add(employee); employee.setDepartment(department); session.saveOrUpdate(department); session.saveOrUpdate(employee); session.getTransaction().commit(); } catch (HibernateException exception) { exception.printStackTrace(); System.out.println("  "); } finally { if (session != null && session.isOpen()) { session.close(); } } } } 


 package implement; import DAO.EmployeeDAO; import logic.Department; import logic.Employee; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import utils.HibernateUtil; import java.sql.SQLException; import java.util.*; public class ImplEmployee implements EmployeeDAO { @Override public void editEmployee(Employee employee) throws SQLException { Session session = null; try { session = HibernateUtil.createSessionFactory().openSession(); session.beginTransaction(); session.update(employee); session.getTransaction().commit(); } catch (HibernateException exception) { System.out.println("  "); exception.printStackTrace(); } finally { if (session != null && session.isOpen()) { session.close(); } } } @Override public void deleteEmployee(Employee employee) throws SQLException { } @Override public Collection getDepartmentByEmployee(Employee employee) throws SQLException { return null; } @Override public Collection getAllEmployies() throws SQLException { return null; } @Override public void deleteEmployiesByName(String name) throws SQLException { Session session = null; List employies = new ArrayList<Employee>(); try { session = HibernateUtil.createSessionFactory().openSession(); session.beginTransaction(); employies = session.createCriteria(Employee.class).add(Restrictions.like("fio", name)).list(); Iterator iterator = employies.iterator(); while (iterator.hasNext()) { Employee data = (Employee) iterator.next(); String nameTemp = data.getFio(); if (nameTemp.equals(name)){ int id = data.getEmployeeId(); Object person = session.load(Employee.class, id); session.delete(person); } } session.getTransaction().commit(); } catch (HibernateException exception) { System.out.println("  "); exception.printStackTrace(); } finally { if (session != null && session.isOpen()) { session.close(); } } } @Override public Collection getEmployiesByDepartment(Integer department) throws SQLException { Session session = null; List departments = new ArrayList<Department>(); Collection employies = null; try { session = HibernateUtil.createSessionFactory().openSession(); departments = session.createCriteria(Department.class).add(Restrictions.idEq(department)).list(); Iterator iterator = departments.iterator(); while (iterator.hasNext()) { Department data = (Department) iterator.next(); employies = data.getEmployies(); } } catch (Exception e) { System.out.println("   "); } finally { if (session != null && session.isOpen()) { session.close(); } } return employies; } } 


Dummies with a Null result are not yet implemented methods. But they are not requested from the main class, so there are no problems with this, you can finish at any time. And in principle, the composition of methods may vary according to the situation.

And finally - the main module to verify the correctness of the ideas implemented.
 package main; import factory.Factory; import logic.Department; import logic.Employee; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Main { public static void addDepartment() throws IOException, SQLException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("  : "); String data = reader.readLine(); Department department = new Department(); department.setCaption(data); Factory.getInstance().getDepartmentDAO().addDepartment(department); } public static void editDepartment() throws IOException, SQLException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("  : "); int num = 0; String data = reader.readLine(); try { num = Integer.parseInt(data); Collection collection; collection = Factory.getInstance().getDepartmentDAO().getDepartmentById(num); Set<Department> set = new HashSet<>(collection); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Department department = (Department) iterator.next(); Integer id = department.getDepartmentId(); String name; System.out.println("  "); name = reader.readLine(); Department temporal = new Department(); temporal.setDepartmentId(id); temporal.setCaption(name); Factory.getInstance().getDepartmentDAO().editDepartment(temporal); } } catch (NumberFormatException e) { System.out.println("  "); } } public static void getDepartments() throws SQLException { Collection collection; collection = Factory.getInstance().getDepartmentDAO().getAllDepartments(); showDepartments(collection); } public static void findDepartments() throws SQLException, IOException { System.out.println("  "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String data = reader.readLine(); try { int num = Integer.parseInt(data); Collection collection; collection = Factory.getInstance().getDepartmentDAO().getDepartmentById(num); showDepartments(collection); } catch (NumberFormatException e) { System.out.println("  "); } } public static void findEmployies() throws SQLException, IOException { System.out.println("    "); int num = 0; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { String data = reader.readLine(); num = Integer.parseInt(data); Collection collection = Factory.getInstance().getDepartmentDAO().getDepartmentById(num); showDepartments(collection); if (collection.size() != 0) { Collection employies = Factory.getInstance().getEmployeeDAO().getEmployiesByDepartment(num); showEmployers(employies); } else System.out.println("  "); } catch (NumberFormatException e) { System.out.println("  "); } } public static void showDepartments(Collection collection) throws SQLException { Set<Department> set = new HashSet<Department>(collection); Iterator iterator = set.iterator(); System.out.println("===================================="); System.out.printf("%-20s%-20s%n", " ", " "); System.out.println("===================================="); while (iterator.hasNext()) { Department data = (Department) iterator.next(); System.out.printf("%-20s%-20s%n", data.getDepartmentId(), data.getCaption()); } } public static void showEmployers(Collection collection) throws SQLException { Set<Employee> set = new HashSet<Employee>(collection); Iterator iterator = set.iterator(); System.out.println("===================================="); System.out.printf("%-20s%n", "  "); System.out.println("===================================="); while (iterator.hasNext()) { Employee data = (Employee) iterator.next(); System.out.printf("%-20s%n", data.getFio()); } } public static void deleteDepartment() throws SQLException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int num = 0; System.out.println("  "); try { String data = reader.readLine(); num = Integer.parseInt(data); Factory.getInstance().getDepartmentDAO().deleteDepartment(num); } catch (NumberFormatException e) { System.out.println("  "); } } public static void deleteEmployies() throws SQLException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("  "); String name = reader.readLine(); Collection collection; Factory.getInstance().getEmployeeDAO().deleteEmployiesByName(name); } public static void addEmployee() throws SQLException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("  "); String id = reader.readLine(); try { int num = Integer.parseInt(id); Collection collection; collection = Factory.getInstance().getDepartmentDAO().getDepartmentById(num); showDepartments(collection); Set<Department> set = new HashSet<>(collection); if (set.size() != 0) { System.out.println("  "); String data = reader.readLine(); Employee employee = new Employee(data); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Department department = (Department) iterator.next(); Factory.getInstance().getDepartmentDAO().addEmployee(department, employee); } } else System.out.println("  "); } catch (NumberFormatException e) { System.out.println("  "); } } static public void main(String[] args) throws IOException, SQLException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("===================================="); System.out.println("    "); System.out.println("===================================="); System.out.println("1 -   "); System.out.println("2 -   "); System.out.println("3 -  "); System.out.println("4 -   "); System.out.println("5 -    "); System.out.println("===================================="); System.out.println("6 -   "); System.out.println("7 -    "); System.out.println("8 -  "); System.out.println("===================================="); System.out.println("0 -  "); System.out.println("===================================="); String num = reader.readLine(); switch (num) { case "1": addDepartment(); break; case "2": editDepartment(); break; case "3": deleteDepartment(); break; case "4": getDepartments(); break; case "5": findDepartments(); break; case "6": addEmployee(); break; case "7": findEmployies(); break; case "8": deleteEmployies(); break; case "0": System.exit(0); break; } } } } 


Bottom line: what to look for. First, on the correctness of the file structure for mapping and organization of links. Error results can make you nervous. Secondly, the new organization of the session. Third, sometimes the methods suggest forming a POJO in auto mode, in which case you will have to establish a connection with the database during the design phase. The result will be in the form of annotations (description of the database components inside the classes).

I hope that the example, although simple, is useful for getting first impressions.

Source: https://habr.com/ru/post/305418/


All Articles