Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Hibernate Framework

Java Hibernate Framework

Common Java Libraries Common Java Libraries


Hibernate is an open-source Object-Relational Mapping (ORM) framework used to simplify database operations in Java applications.

Hibernate maps Java objects to database tables, allowing developers to manipulate the database in an object-oriented way without writing complex SQL statements.

The main advantages of Hibernate include:


Hibernate Core Architecture

The Hibernate architecture consists of several important components:

1. SessionFactory

SessionFactory is a thread-safe object, usually created only once for the entire application. It is responsible for:

Example

Configuration configuration

=

new

Configuration

(

)

.

configure

(

)

;

SessionFactory sessionFactory

=

configuration.

buildSessionFactory

(

)

;

2. Session

Session is the core interface of Hibernate, representing a session with the database. It provides:

Example

Session session

=

sessionFactory.

openSession

(

)

;

Transaction transaction

=

session.

beginTransaction

(

)

;

// Perform database operations

transaction.

commit

(

)

;

session.

close

(

)

;

3. Transaction

The Transaction interface encapsulates the concept of a database transaction, ensuring the atomicity of operations.


Hibernate Mapping Configuration

Hibernate supports two configuration approaches:

1. XML Mapping File

The traditional approach uses .hbm.xml files to define the mapping between entity classes and database tables.

Example

   

       

           

       

       

       

   

2. Annotation Approach

Modern Hibernate recommends the JPA annotation approach:

Example

@

Entity

@Table

(

name

=

"USERS"

)

public

class

User

{

    @Id

    @GeneratedValue

(

strategy

=

GenerationType.

IDENTITY

)

   

private

Long

id

;

   

    @Column

(

name

=

"USER_NAME"

)

   

private

String

name

;

   

    @Column

(

name

=

"USER_EMAIL"

)

   

private

String

email

;

   

   

// getters and setters

}


Hibernate Query Language

Hibernate provides multiple query approaches:

1. HQL (Hibernate Query Language)

An object-oriented query language, similar to SQL but operating on objects rather than tables.

Example

String

hql

=

"FROM User WHERE name = :name"

;

Query

<
User
query
=

session.

createQuery

(

hql, User.

class

)

;

query.

setParameter

(

"name"

,

"John"

)

;

List

<
User
users
=

query.

list

(

)

;

2. Criteria API

A type-safe query building approach:

Example

CriteriaBuilder builder

=

session.

getCriteriaBuilder

(

)

;

CriteriaQuery

<
User
criteria
=

builder.

createQuery

(

User.

class

)

;

Root

<
User
root
=

criteria.

from

(

User.

class

)

;

criteria.

select

(

root

)

.

where

(

builder.

equal

(

root.

get

(

"name"

)

,

"John"

)

)

;

List

<
User
users
=

session.

createQuery

(

criteria

)

.

getResultList

(

)

;

3. Native SQL Query

When you need to execute complex SQL:

Example

String

sql

=

"SELECT * FROM USERS WHERE USER_NAME = :name"

;

NativeQuery

<
User
query
=

session.

createNativeQuery

(

sql, User.

class

)

;

query.

setParameter

(

"name"

,

"John"

)

;

List

<
User
users
=

query.

list

(

)

;


Hibernate Caching Mechanism

Hibernate provides a two-level cache to improve performance:

1. First-level Cache (Session Cache)

2. Second-level Cache (SessionFactory Cache)

Configuration example:

Example

true

    org.hibernate.cache.ehcache.EhCacheRegionFactory


Hibernate Transaction Management

Hibernate supports two transaction management approaches:

1. JDBC Transaction Management

Suitable for standalone applications:

Example

Session session

=

sessionFactory.

openSession

(

)

;

Transaction tx

=

null

;

try

{

    tx

=

session.

beginTransaction

(

)

;

   

// Business logic

    tx.

commit

(

)

;

}

catch

(

Exception

e

)

{

   

if

(

tx

!=

null

)

tx.

rollback

(

)

;

   

throw

e

;

}

finally

{

    session.

close

(

)

;

}

2. JTA Transaction Management

Suitable for distributed environments, such as Java EE application servers.


Hibernate Best Practices

  1. Use lazy loading reasonably: Avoid the N+1 query problem
  2. Batch Processing: Use batch processing for large amounts of data operations
  3. Avoid Long Sessions: Close the Session promptly
  4. Design Object Relationships Reasonably: Avoid complex object graphs
  5. Use Connection Pools: Improve performance

Example

// Batch insert example

Session session

=

sessionFactory.

openSession

(

)

;

Transaction tx

=

session.

beginTransaction

(

)

;

for

(

int

i

=

0

;

i

<

100000

;

i

++

)

{

    User user

=

new

User

(

"User"

i,

"user"

i

"@example.com"

)

;

    session.

save

(

user

)

;

   

   

if

(

i

%

50

==

0

)

{

// Flush every 50 records

        session.

flush

(

)

;

        session.

clear

(

)

;

   

}

}

tx.

commit

(

)

;

session.

close

(

)

;

As a mature ORM framework, Hibernate greatly simplifies the development of the data access layer of Java applications. With proper configuration and usage, it can significantly improve development efficiency and application performance.

Common Java Libraries Common Java Libraries