Hibernate topics

The content is mostly boring, and there is no real understanding yet.

definition:

Simply put, the role of Hibernate is to map Java classes to relational tables in the database.

Hibernate is an open source object-relational framework created by Gavin King in 2001 . It is powerful and efficient to build Java applications with relational object persistence and query services.

Hibernate maps Java classes to database tables, from Java data types to SQL data types, and frees developers from 95% of the continuous programming of public data.

Hibernate is a bridge between traditional Java objects and database servers to process those objects based on O/R mapping mechanisms and patterns.

Baidu definition : Hibernate is an open source object-relational mapping framework, which encapsulates JDBC very lightweight objects. It establishes a mapping relationship between POJOs and database tables. It is a fully automatic ORM framework that can be automatically generated by hibernate. SQL statements are automatically executed, allowing Java programmers to use object programming thinking to manipulate the database as they like. Hibernate can be used in any occasion where JDBC is used, either in Java client programs or in Servlet/JSP Web applications.

ORM: Object Relation Mapping (English: Object Relation Mapping, ORM for short, or O/RM, or O/R mapping), is a kind of programming technology used to realize the data between different types of systems in object-oriented programming languages Conversion.

Architecture and development steps:

Hibernate uses the database and configuration data to provide continuous services for applications.

Architecture:

Below is a very high-level view of the Hibernate application architecture.

Insert picture description here
Below is a detailed view of the Hibernate application architecture and some important classes.
Insert picture description here
Development steps:

  1. Create a persistent class
  2. Create object-relational mapping file
  3. Create Hibernate configuration file
  4. Write code to access the database through Hibernate API
    Insert picture description here

Session in Hibernate

Session is used to obtain a physical connection to the database. The Session object is lightweight and designed to be instantiated every time it needs to interact with the database. The persistent object is saved and retrieved through the Session object.

The Session objects should not remain open for a long time, because they usually cannot guarantee thread safety, and should be created and destroyed as required. The main function of Session is to provide create, read and delete operations for instances of mapped entity classes. These instances may exist in one of the following three states at a given point in time:

  1. Transient state: A new persistent instance, considered by Hibernate to be instantaneous, it is not associated with Session, there is no record associated with it in the database and no identifier value.
  2. Persistent state: A transient state instance can be transformed into a persistent state instance by being associated with a Session. The persistent state instance has no record associated with it in the database, has an identifier value, and is associated with a Session.
  3. Disconnected state: Once the Hibernate Session is closed, the persistent state instance will become the unmanaged state instance.

Persistent classes in Hibernate

The complete concept of Hibernate is to extract the values ​​in the Java class properties and save them to the database form . The mapping file can help Hibernate determine how to extract values ​​from the class and map them in tables and related fields.

In Hibernate, Java classes whose objects or instances will be stored in database forms are called persistent classes. If this class follows some simple rules or the well-known Plain Old Java Object (POJO) programming model , Hibernate will be in its best running state. The following are the main rules of the persistence class. However, none of these rules is a hard requirement.

  1. All Java classes that will be persisted need a default constructor.
  2. In order for the object to be easily identified in Hibernate and the database, all classes need to contain an ID. This attribute is mapped to the primary key column of the database table.
  3. All properties that will be persisted should be declared as private and have getXXX and setXXX methods defined by the JavaBean style.
  4. An important feature of Hibernate is proxy, which depends on whether the persistence class is non-final or in an
    interface where all methods are declared as public .
  5. All classes are special classes and interfaces that are not extensible or implemented according to EJB requirements . (?)

Examples of persistent classes:

public class Employee {
    
    
   private int id;//主键(ID)
   private String firstName; //类似JavaBean
   private String lastName;   
   private int salary;  

   public Employee() {
    
    //默认构造函数
      firstName=null;
      lastName=null;
      salary =0;
   }
   public Employee(String fname, String lname, int salary) {
    
    
      this.firstName = fname;
      this.lastName = lname;
      this.salary = salary;
   }
   public int getId() {
    
    
      return id;
   }
   public void setId( int id ) {
    
    
      this.id = id;
   }
   public String getFirstName() {
    
    
      return firstName;
   }
   public void setFirstName( String first_name ) {
    
    
      this.firstName = first_name;
   }
   public String getLastName() {
    
    
      return lastName;
   }
   public void setLastName( String last_name ) {
    
    
      this.lastName = last_name;
   }
   public int getSalary() {
    
    
      return salary;
   }
   public void setSalary( int salary ) {
    
    
      this.salary = salary;
   }
}

Hibernate mapping relationship:

1. Collection mapping

2. Association mapping

3. Component mapping

Hibernate object status:

The state of the object in Hibernate: temporary/transient state, persistent state, free state .

  1. Temporary status
    Features:
    directly new objects;
    not under session management;
    no object records in the database;
  2. Persistent state
    When calling the save/saveOrUpdate/get/load/list methods of the session, the object is the persistent state.
    Objects in a persistent state will be reflected in the database when the object properties are changed!
    Features:
    in session management;
    there are corresponding records in the database;
  3. Free state
    Features
    Not in session management;
    there is a corresponding record in the database
    after the session is closed, the state of the object;

Hibernate application examples:

1. Create POJO class (it feels similar to JavaBean)

public class Employee {
    
    
   private int id;
   private String firstName; 
   private String lastName;   
   private int salary;  

   public Employee() {
    
    }
   public Employee(String fname, String lname, int salary) {
    
    
      this.firstName = fname;
      this.lastName = lname;
      this.salary = salary;
   }
   public int getId() {
    
    
      return id;
   }
   public void setId( int id ) {
    
    
      this.id = id;
   }
   public String getFirstName() {
    
    
      return firstName;
   }
   public void setFirstName( String first_name ) {
    
    
      this.firstName = first_name;
   }
   public String getLastName() {
    
    
      return lastName;
   }
   public void setLastName( String last_name ) {
    
    
      this.lastName = last_name;
   }
   public int getSalary() {
    
    
      return salary;
   }
   public void setSalary( int salary ) {
    
    
      this.salary = salary;
   }
}

2. Create a relational table in the database (may not necessarily be a relational table, but I currently only learn relational databases)

It seems to be a mysql database. I didn't practice it specifically, but it shouldn't be difficult to build a table.

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

3. Create a mapping configuration file

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>
  1. The mapping document is an XML format document that has as the root element, this element contains all the elements.
  2. Elements are used to define specific mappings from Java classes to database tables. The name of the Java class is specific, it uses the name
    attribute of the class element, and the name of the database table is also specific, it uses the table attribute.
  3. The element is an optional element that can be used to create a description of the class.
  4. The element maps a specific ID attribute in the class to the main key table of the database. The name attribute of the id element refers to the attributes in the class and the column attribute refers to the columns in the database table. The type attribute masters the mapping type of hibernate, which will transfer from Java to SQL data type.
  5. The elements in the id element are used to automatically generate the value of the main keyword. Set the class attribute of the generator element to native so that Hibernate can use the identity, sequence or hilo algorithm to create the main keywords based on the performance of the underlying database.
  6. Elements are used to map the attributes of a Java class to columns in the database table. The name attribute of this element relates to the attributes in the class, and the column attribute relates to the columns in the data table. The type attribute controls Hibernate's mapping type, which will be transferred from Java to SQL data type.

4. Create an application class

It feels similar to Dao. JavaBean stores class objects and their attributes. Dao is responsible for manipulating the database.

import java.util.List; 
import java.util.Date;
import java.util.Iterator; 

import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {
    
    
   private static SessionFactory factory; 
   public static void main(String[] args) {
    
    
      try{
    
    
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) {
    
     
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      ManageEmployee ME = new ManageEmployee();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);

      /* List down all the employees */
      ME.listEmployees();

      /* Update employee's records */
      ME.updateEmployee(empID1, 5000);

      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);

      /* List down new list of the employees */
      ME.listEmployees();
   }
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
    
    
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
    
    
         tx = session.beginTransaction();
         Employee employee = new Employee(fname, lname, salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      }catch (HibernateException e) {
    
    
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
    
    
         session.close(); 
      }
      return employeeID;
   }
   /* Method to  READ all the employees */
   public void listEmployees( ){
    
    
      Session session = factory.openSession();
      Transaction tx = null;
      try{
    
    
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list(); 
         for (Iterator iterator = 
                           employees.iterator(); iterator.hasNext();){
    
    
            Employee employee = (Employee) iterator.next(); 
            System.out.print("First Name: " + employee.getFirstName()); 
            System.out.print("  Last Name: " + employee.getLastName()); 
            System.out.println("  Salary: " + employee.getSalary()); 
         }
         tx.commit();
      }catch (HibernateException e) {
    
    
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
    
    
         session.close(); 
      }
   }
   /* Method to UPDATE salary for an employee */
   public void updateEmployee(Integer EmployeeID, int salary ){
    
    
      Session session = factory.openSession();
      Transaction tx = null;
      try{
    
    
         tx = session.beginTransaction();
         Employee employee = 
                    (Employee)session.get(Employee.class, EmployeeID); 
         employee.setSalary( salary );
         session.update(employee); 
         tx.commit();
      }catch (HibernateException e) {
    
    
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
    
    
         session.close(); 
      }
   }
   /* Method to DELETE an employee from the records */
   public void deleteEmployee(Integer EmployeeID){
    
    
      Session session = factory.openSession();
      Transaction tx = null;
      try{
    
    
         tx = session.beginTransaction();
         Employee employee = 
                   (Employee)session.get(Employee.class, EmployeeID); 
         session.delete(employee); 
         tx.commit();
      }catch (HibernateException e) {
    
    
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
    
    
         session.close(); 
      }
   }
}

Reference: Hibernate Examples
Reference: Hibernate Detailed

Guess you like

Origin blog.csdn.net/qq_52212721/article/details/112552276