HB Core Concepts

Hibernate provides a powerful ORM (Object-Relational Mapping) framework that simplifies database interactions in Java applications. In this section, we'll explore the core components of Hibernate:

Session & SessionFactory

Transaction Management

Entity Classes and Mappings

Hibernate Dialects


Session & SessionFactory:

 What is SessionFactory?

  • A heavyweight object that creates Session instances.
  • It is thread-safe and should be created once per application.
  • Uses a configuration file (hibernate.cfg.xml) to connect to the database.

What is Session?

  • A lightweight object used to interact with the database.
  • It is not thread-safe and should be created per database operation.
  • Used to perform CRUD (Create, Read, Update, Delete) operations.


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

public class Main {
public static void main(String[] args) {
// Create and save Student object
Student student = new Student("John Doe", "john@example.com");
// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.openSession();
// Close session
session.close();
sessionFactory.close();
System.out.println("Hibernate setup successful!");
}
}

Transaction Management

Why Use Transactions?

Transactions ensure data consistency. If an error occurs in the middle of an operation, the changes should be rolled back.


Transaction Methods

  • beginTransaction()Starts a new transaction
  • commit()Saves changes to the database
  • rollback()Reverts changes if an error occurs


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

public class TransactionExample {
public static void main(String[] args) {
Transaction transaction = null;

// Create a new student
Student student = new Student("Bob", "bob@example.com");
// Create Hibernate session
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
session.save(student);

// Commit transaction
transaction.commit();
System.out.println("Transaction Successful!");
} catch (Exception e) {
if (transaction != null) {
transaction.rollback(); // Rollback in case of error
System.out.println("Transaction Rolled Back!");
}
e.printStackTrace();
} finally {
session.close();
sessionFactory.close();
}
}
}

Entity Classes and Mappings

What is an Entity?

An entity is a Java class that is mapped to a database table using annotations or XML mappings.


Common Hibernate Annotations


Annotation

Description

@Entity

Marks the class as an Entity (Table in DB)

@Table(name="table_name")

Defines a custom table name

@Id

Marks a field as Primary Key

@GeneratedValue(strategy = GenerationType.IDENTITY)

Enables Auto-Increment for the ID

@Column(name="column_name")

Maps a field to a specific column name

@Transient

Prevents a field from being saved in the DB

@Temporal(TemporalType.DATE)

Stores Date-only values

@OneToOne,@OneToMany,@ManyToOne,@ManyToMany

Defines Relationships

Example: Entity Class with Mappings:

Student.java
import jakarta.persistence.*;

@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "student_name", nullable = false)
private String name;

@Column(unique = true)
private String email;

// Constructors
public Student() {}
public Student(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; }
}

Hibernate Dialects

What is a Hibernate Dialect?

A dialect helps Hibernate translate HQL (Hibernate Query Language) into SQL for the specific database.


Common Hibernate Dialects


Database

Hibernate Dialect

MySQL

org.hibernate.dialect.MySQLDialect

PostgreSQL

org.hibernate.dialect.PostgreSQLDialect

Oracle

org.hibernate.dialect.OracleDialect

SQL Server

org.hibernate.dialect.SQLServerDialect

H2 (In-Memory)

org.hibernate.dialect.H2Dialect


Example: Setting Dialect in hibernate.cfg.xml

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

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.