Hibernate Notes
2a. Illustrate Architecture of Hibernate
2.1 Introduction to Hibernate
- Hibernate is an Object-Relational Mapping (ORM) framework for Java.
- It maps Java objects to relational database tables.
- Simplifies database interactions using objects instead of SQL.
2.1 Exploring the Hibernate Architecture
Hibernate Architecture Components:
1. Configuration: Loads configuration from hibernate.cfg.xml or hibernate.properties.
2. SessionFactory: A factory for Session objects.
3. Session: Single-threaded object for CRUD operations.
4. Transaction: Manages atomic units of work.
5. Query: Interface for HQL (Hibernate Query Language).
6. Criteria: Used for object-oriented queries.
7. Persistent Objects: Java objects mapped to database tables.
Architecture Flow:
Java App -> Hibernate Core (Session, Query, etc.) -> JDBC -> Database
2b. Setting Up Environment for Hibernate
2.2 Downloading, Installing and Setting up Environment
- Prerequisites: JDK, Eclipse/IntelliJ, MySQL.
- Download Hibernate from https://hibernate.org/orm/
- Add Hibernate JARs to build path or use Maven:
Maven Dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.15.Final</version>
</dependency>
2.2 Exploring HQL (Hibernate Query Language)
- HQL is object-oriented and operates on Java objects.
Example:
Query query = session.createQuery("from Employee");
List<Employee> list = query.list();
2c. Implementing O/R Mapping in Hibernate
2.3 Understanding O/R Mapping in Hibernate
- ORM maps Java classes to tables and Java data types to SQL types.
- Benefits: less code, abstraction of JDBC, consistency.
2.3 Working with Hibernate O/R Mapping
1. Hibernate Configuration File (hibernate.cfg.xml)
Defines DB connection and mappings.
Example:
<hibernate-configuration>
<session-factory>
<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 resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2. Hibernate Mapping File (Employee.hbm.xml)
<hibernate-mapping>
<class name="com.example.Employee" table="employee">
<id name="id" column="id"><generator class="increment"/></id>
<property name="name" column="name"/>
<property name="department" column="department"/>
</class>
</hibernate-mapping>
3. Java Bean (POJO)
public class Employee {
private int id;
private String name;
private String department;
// Getters and Setters
}
Typical Flow:
1. Create POJO.
2. Create mapping file.
3. Create config file.
4. Use SessionFactory and Session.
5. Perform DB operations.