Hibernate_in_Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Hibernate in Java

Overview

Hibernate is an Object-Relational Mapping (ORM) framework for Java. It simplifies database

interactions by mapping Java objects to database tables and vice versa. Key features include ORM

framework, transparent persistence, HQL (Hibernate Query Language), and automatic table

generation. It boosts productivity, maintainability, and portability by reducing boilerplate code and

simplifying complex SQL queries.

Core Components

- Session: Represents a single unit of work with the database.

- SessionFactory: Configures Hibernate for the application and provides Session instances.

- Configuration: Loads configuration and mapping information.

- Transaction: Abstracts the concept of a database transaction.

- Query: Allows the execution of HQL and SQL queries.

Example Usage

Configuration File (hibernate.cfg.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>
Hibernate in Java

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>

<property name="hibernate.connection.username">root</property>

<property name="hibernate.connection.password">password</property>

<mapping class="com.example.MyEntity"/>

</session-factory>

</hibernate-configuration>

```

Entity Class:

```

@Entity

@Table(name = "my_table")

public class MyEntity {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(name = "name")

private String name;

// Getters and Setters

```
Hibernate in Java

Using Hibernate:

```

public class HibernateUtil {

private static SessionFactory sessionFactory;

static {

try {

Configuration configuration = new Configuration().configure();

sessionFactory = configuration.buildSessionFactory();

} catch (Throwable ex) {

throw new ExceptionInInitializerError(ex);

public static SessionFactory getSessionFactory() {

return sessionFactory;

public class Main {

public static void main(String[] args) {

Session session = HibernateUtil.getSessionFactory().openSession();

Transaction transaction = null;


Hibernate in Java

try {

transaction = session.beginTransaction();

MyEntity entity = new MyEntity();

entity.setName("Hibernate Example");

session.save(entity);

transaction.commit();

} catch (Exception e) {

if (transaction != null) {

transaction.rollback();

e.printStackTrace();

} finally {

session.close();

```

Object States Persistence Life Cycle

Hibernate entities can exist in three primary states during their lifecycle: Transient, Persistent, and

Detached.

1. Transient State:

- An object is in a transient state when it is instantiated but not associated with a Hibernate Session.
Hibernate in Java

- Example: MyEntity entity = new MyEntity();

2. Persistent State:

- An object is in a persistent state when it is associated with a Hibernate Session.

- Example: session.save(entity);

3. Detached State:

- An object is in a detached state when it was once associated with a Hibernate Session, but the

session is now closed or the object has been evicted.

- Example: session.close();

Difference Between get and load Methods

1. get Method:

- Immediate database access.

- Returns the actual object or null if the entity does not exist.

- Example: MyEntity entity = session.get(MyEntity.class, entityId);

2. load Method:

- Lazy loading (delayed database access).

- Returns a proxy object initially.

- Throws ObjectNotFoundException if the entity does not exist when a method is invoked on the

proxy.

- Example: MyEntity entity = session.load(MyEntity.class, entityId);


Hibernate in Java

JPA and JPA Implementation

Java Persistence API (JPA) is a specification for object-relational mapping (ORM) in Java. It

provides a standard way to map Java objects to relational database tables and manage persistent

data. JPA requires a concrete implementation such as Hibernate, EclipseLink, Apache OpenJPA, or

DataNucleus.

Example of JPA Implementation with Hibernate:

1. Dependencies:

Add required dependencies in your pom.xml (if using Maven).

2. Entity Class:

Define an entity class using JPA annotations.

3. Persistence Configuration:

Create a persistence.xml file in the META-INF directory to configure JPA.

4. Using EntityManager:

Create and use an EntityManager to perform CRUD operations.

You might also like