Interfaces of Hibernate framework

Interfaces of Hibernate framework

Hibernate is an ORM (Object-Relational Mapping) framework for Java, which simplifies the development of Java applications to interact with databases. Hibernate provides several important interfaces that play a crucial role in managing the persistence of objects and interactions with the database. Some of the key interfaces in Interfaces of Hibernate include:

1.  Session:

  • Purpose:  Represents a single unit of work with the database. It is used to create, read, update, and delete operations for instances of mapped entity classes.
  • Lifecycle:  A session is typically a short-lived object, which is created and destroyed with each transaction.

2.  SessionFactory

  • Purpose:  A thread-safe, immutable factory for Session instances. It is typically created once and used to create Session instances throughout the application.
  • Lifecycle:  Typically created at the start of the application and destroyed at shutdown.

3.  Transaction:

  • Purpose:  Represents a single unit of work and is used to manage transactions. It ensures that operations are completed successfully and allows for rollback in case of errors.
  • Lifecycle:  Bound to the lifecycle of a Session.

4.  Query:

  • Purpose:  Used to create and execute queries against the database. It supports both HQL (Hibernate Query Language) and native SQL queries.
  • Lifecycle:  Created using a Session and executed to retrieve results.

5.  Criteria

  • Purpose:  Provides a programmatic way to create queries using criteria instead of HQL. It is used to build and execute complex queries in a flexible manner.
  • Lifecycle:  Created and executed within a Session.

Interfaces of Hibernate

Interfaces of Hibernate in Java:

Here is a simple example demonstrating the use of some key Hibernate interfaces:

Hibernate Configuration (hibernate.cfg.xml):

xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.url">jdbc:h2:mem:test</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping class="com.example.User"/>	
    </session-factory>
</hibernate-configuration>


Entity Class:

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

@Entity
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String email;
    
    // Constructors
    public User() {}
    
    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }
    
    // Getters and Setters
    public Long getId() {
        return id;
    }
    
    public void setId(Long id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getEmail() {
        return email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
}

Main Application Code:

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

public class HibernateDemo {
    public static void main(String[] args) {
        // Create a Configuration instance
        Configuration configuration = new Configuration().configure();

        // Build a SessionFactory from the Configuration
        SessionFactory sessionFactory = configuration.buildSessionFactory();

        // Obtain a Session from the SessionFactory
        Session session = sessionFactory.openSession();

        // Begin a transaction
        Transaction transaction = session.beginTransaction();

        // Create a new User entity
        User user = new User("John Doe", "john.doe@example.com");

        // Save the User entity
        session.save(user);

        // Commit the transaction
        transaction.commit();

        // Retrieve the User entity
        User retrievedUser = session.get(User.class, user.getId());
        System.out.println("Retrieved User: " + retrievedUser.getName() + ", " + retrievedUser.getEmail());

        // Close the Session
        session.close();

        // Close the SessionFactory
        sessionFactory.close();
    }
}

Explanation of the Interfaces of Hibernate

1.  Hibernate Configuration:

   The hibernate.cfg.xml file configures Hibernate, specifying database connection properties and the entity class mapping.

2.  Entity Class:

   The User class is a JPA entity annotated with @Entity, with @Id marking the primary key and @GeneratedValue for auto-generating the ID.

3.  Main Application Code:

  • A Configuration instance is created and configured using hibernate.cfg.xml.
  • A SessionFactory is built from the configuration.
  • A Session is obtained from the SessionFactory.
  • A Transaction is started, and a User entity is created and saved.
  • The transaction is committed, and the User entity is retrieved and printed.
  • The Session and SessionFactory are closed.

Homepage

Readmore