Java Hibernate Framework

Java 常用类库Java Common 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 interact with the database in an object-oriented way without writing complex SQL statements.

The main advantages of Hibernate include:

  • Reduces JDBC boilerplate code
  • Provides a transparent persistence mechanism
  • Supports multiple databases
  • Provides a caching mechanism to improve performance
  • Supports transaction management

Hibernate Core Architecture

The Hibernate architecture consists of several important components:

1. SessionFactory

SessionFactory is a thread-safe object that is typically created only once in the entire application. It is responsible for:

  • Creating Session instances
  • Caching generated SQL statements
  • Caching mapping metadata

Example

Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();

2. Session

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

  • Create, Read, Update, and Delete (CRUD) operations
  • Transaction management
  • Query functionality

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 database transactions, ensuring atomicity of operations.


Hibernate Mapping Configuration

Hibernate supports two configuration methods:

1. XML Mapping File

The traditional method, using .hbm.xml files to define the mapping relationship between entity classes and database tables.

Example

<!-- User.hbm.xml -->
<hibernate-mapping>
    <class name="com.example.User" table="USERS">
        <id name="id" column="USER_ID">
            <generator class="native"/>
        </id>
        <property name="name" column="USER_NAME"/>
        <property name="email" column="USER_EMAIL"/>
    </class>
</hibernate-mapping>

2. Annotation Approach

Modern Hibernate recommends using JPA annotations:

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 methods:

1. HQL (Hibernate Query Language)

An object-oriented query language, similar to SQL but operates 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 construction method:

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 complex SQL needs to be executed:

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 Cache Mechanism

Hibernate provides a two-level cache to improve performance:

1. First-Level Cache (Session Cache)

  • Enabled by default
  • Lifecycle is the same as the Session
  • Ensures the same query is executed only once within the same Session

2. Second-Level Cache (SessionFactory Cache)

  • Requires explicit configuration
  • Shared across Sessions
  • Common implementations: EhCache, Infinispan, etc.

Configuration example:

Example

<!-- hibernate.cfg.xml -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">
    org.hibernate.cache.ehcache.EhCacheRegionFactory
</property>

Hibernate Transaction Management

Hibernate supports two transaction management methods:

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 appropriately: Avoid the N+1 query problem
  2. Batch processing: Use batch processing for large volumes of data operations
  3. Avoid long sessions: Close the Session promptly
  4. Design object relationships reasonably: Avoid complex object graphs
  5. Use connection pooling: 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 in Java applications. Through proper configuration and usage, it can significantly improve development efficiency and application performance.

Java 常用类库Java Common Libraries

Other Extensions