Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Hibernate persistence class


May 17, 2021 Hibernate


Table of contents


Persistence class

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

In Hibernate, its objects or instances are stored in a database form in a Java class called a persistence class. H ibernate would be at its best if it followed some simple rules or the well-known Plain Old Java Object (POJO) programming model. The following are the main rules of the persistence class, however, none of these rules is a hard requirement.

  • All Java classes that will be persisted require a default constructor.
  • To make objects easy to identify in Hibernate and databases, all classes need to contain an ID. This property maps to the primary key column of the database table.
  • All properties that will be persisted should be declared private and have getXXX and setXXX methods defined by the JavaBean style.
  • An important feature of Hibernate is the proxy, which depends on whether the persistence class is in a non-final or an interface that all methods declare as public.
  • All classes are non-scalable or implemented as required by EJB for some special classes and interfaces.

The name POJO is used to emphasize that a given object is a normal Java object, not a special object, especially an Enterprise JavaBean.

A simple example of POJO

Based on the rules described above, we are able to define the following POJO classes:

public class Employee {
   private int id;
   private String firstName; 
   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;
   }
}