← Back to Advanced Java Course | Chapter 8: Database & JPA | Lesson 3 of 4

Java ORM Introduction (Hibernate)

Entity Declarations

Object-Relational Mapping (ORM) bridges the gap between Java objects and relational database tables. You mark your domain classes with annotations like @Entity and @Id so Hibernate knows which class maps to which table and which field is the primary key, without you writing that mapping SQL by hand.

Example: Entity Declarations

java
import javax.persistence.*;
public class Main {
	@Entity
	static class User {
		@Id
		private Long id;
		private String name;
	}
	public static void main(String[] args) {
		System.out.println("@Entity and @Id map this class to a table, without hand-written mapping SQL");
	}
}

SessionFactory Setup

The SessionFactory compiles all of your mapping configurations once at startup and is responsible for establishing database connections from that point on. It's a heavyweight object meant to be created once per application and reused to generate lightweight Session instances as needed.

Example: SessionFactory Setup

java
public class Main {
	// SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
	// created once per application, heavyweight, reused to open lightweight Sessions
	public static void main(String[] args) {
		System.out.println("SessionFactory compiles mappings once at startup");
	}
}

Persisting Objects (Save)

Hibernate maps an object's properties directly onto the target table's columns based on your entity annotations. Calling session.save() takes a populated entity object and converts it into an INSERT that writes a corresponding row into the database.

Example: Persisting Objects (Save)

java
public class Main {
	static class User { Long id; String name; }
	public static void main(String[] args) {
		User user = new User();
		user.name = "Riya";
		// session.save(user); // Hibernate converts this into an INSERT
		System.out.println("Saving " + user.name);
	}
}

Fetching Objects (Get)

To retrieve a persistent entity that already exists, use session.get(), passing the entity's class and its unique identifier (primary key) value. Hibernate translates this into a SELECT and reconstructs a fully populated object from the returned row.

Example: Fetching Objects (Get)

java
public class Main {
	static class User { Long id; String name; }
	public static void main(String[] args) {
		Long id = 1L;
		// User user = session.get(User.class, id); // translated into a SELECT
		System.out.println("Fetching User with id " + id);
	}
}

Managing Database Transactions

Always wrap your persistence operations inside an explicit transaction boundary. This ensures that a set of related database writes either all commit together or all roll back safely if something fails partway through, rather than leaving the database in an inconsistent half-updated state.

Example: Managing Database Transactions

java
public class Main {
	public static void main(String[] args) {
		// Transaction tx = session.beginTransaction();
		// try {
		//     session.save(new User());
		//     tx.commit();
		// } catch (Exception e) {
		//     tx.rollback(); // rolls back all related writes together
		// }
		System.out.println("Wrap persistence operations in an explicit transaction boundary");
	}
}
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.