Top Related Projects
Kotlin SQL Framework
Simplifies the development of creating a JPA-based data access layer.
MyBatis SQL mapper framework for Java
jOOQ is the best way to write SQL in Java
requery - modern SQL based query & persistence for Java / Kotlin / Android
Quick Overview
Hibernate ORM is a powerful, high-performance Object/Relational Mapping (ORM) framework for Java. It provides a seamless bridge between object-oriented domain models and relational database systems, simplifying database operations and reducing boilerplate code in Java applications.
Pros
- Simplifies database operations by allowing developers to work with Java objects instead of SQL queries
- Supports a wide range of databases and provides database-independent querying
- Offers excellent performance optimization features, including lazy loading and caching
- Integrates well with other Java frameworks and technologies, such as Spring
Cons
- Steep learning curve for beginners, especially those new to ORM concepts
- Can introduce performance overhead if not configured properly
- May lead to unnecessary complexity for simple applications or small-scale projects
- Debugging can be challenging due to the abstraction layer between the application and the database
Code Examples
- Defining an entity:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
// Getters and setters
}
- Performing a simple query:
Session session = sessionFactory.openSession();
List<User> users = session.createQuery("FROM User", User.class).list();
session.close();
- Saving an entity:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setUsername("johndoe");
user.setEmail("john@example.com");
session.save(user);
tx.commit();
session.close();
Getting Started
To start using Hibernate ORM in your Java project:
- Add Hibernate dependencies to your project (using Maven):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.5.Final</version>
</dependency>
- Create a
hibernate.cfg.xmlconfiguration file in yoursrc/main/resourcesdirectory:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
-
Create your entity classes and annotate them with Hibernate annotations.
-
Use
SessionFactoryto createSessioninstances and perform database operations.
Competitor Comparisons
Kotlin SQL Framework
Pros of Exposed
- Lightweight and less complex, making it easier to learn and use
- Provides type-safe SQL DSL, reducing the risk of runtime errors
- Better integration with Kotlin language features
Cons of Exposed
- Less mature ecosystem and community support compared to Hibernate
- Fewer advanced features and optimizations for complex scenarios
- Limited documentation and learning resources
Code Comparison
Hibernate ORM:
@Entity
public class User {
@Id
private Long id;
private String name;
// Getters and setters
}
Exposed:
object Users : Table() {
val id = long("id").autoIncrement()
val name = varchar("name", 50)
override val primaryKey = PrimaryKey(id)
}
Summary
Hibernate ORM is a mature, feature-rich ORM framework with extensive documentation and community support. It offers advanced features for complex scenarios but can be more complex to set up and use.
Exposed is a lightweight, Kotlin-specific SQL framework that provides a type-safe DSL for database operations. It's easier to learn and use, especially for Kotlin developers, but lacks some advanced features and optimizations found in Hibernate.
The choice between the two depends on project requirements, team expertise, and the specific use case. Hibernate may be better suited for large, complex applications, while Exposed could be ideal for smaller Kotlin projects or those prioritizing simplicity and type safety.
Simplifies the development of creating a JPA-based data access layer.
Pros of Spring Data JPA
- Simplifies data access layer with repository interfaces
- Provides powerful query methods and custom query creation
- Integrates seamlessly with Spring ecosystem
Cons of Spring Data JPA
- Steeper learning curve for developers new to Spring
- Less flexibility in complex scenarios compared to Hibernate ORM
- Potential performance overhead due to abstraction layer
Code Comparison
Spring Data JPA:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByLastName(String lastName);
}
Hibernate ORM:
Session session = sessionFactory.openSession();
List<User> users = session.createQuery("FROM User WHERE lastName = :lastName", User.class)
.setParameter("lastName", lastName)
.getResultList();
Spring Data JPA simplifies data access with repository interfaces and method naming conventions, while Hibernate ORM requires more explicit query definitions. Spring Data JPA abstracts away much of the boilerplate code, making it easier to work with JPA entities. However, Hibernate ORM offers more fine-grained control over queries and database operations, which can be beneficial in complex scenarios.
Both projects are widely used in the Java ecosystem, with Spring Data JPA being more tightly integrated with the Spring framework, while Hibernate ORM can be used independently or with other frameworks.
MyBatis SQL mapper framework for Java
Pros of MyBatis
- Simpler learning curve and easier to use for SQL-centric developers
- More fine-grained control over SQL queries and database interactions
- Lighter weight and potentially better performance for simple use cases
Cons of MyBatis
- Less abstraction from the database, requiring more manual SQL writing
- Fewer advanced ORM features compared to Hibernate
- Limited support for complex object relationships and cascading operations
Code Comparison
MyBatis:
@Select("SELECT * FROM users WHERE id = #{id}")
User getUser(int id);
Hibernate:
@Entity
public class User {
@Id
private int id;
// Other fields and annotations
}
User user = session.get(User.class, id);
MyBatis focuses on mapping SQL queries to method calls, while Hibernate uses annotations to define entity relationships and handles most SQL generation automatically. MyBatis provides more direct control over SQL, whereas Hibernate offers a higher level of abstraction from the database.
jOOQ is the best way to write SQL in Java
Pros of jOOQ
- Type-safe SQL queries with compile-time checking
- Easier to write complex SQL queries and joins
- Better performance for read-heavy applications
Cons of jOOQ
- Steeper learning curve for developers familiar with ORM concepts
- Less abstraction from the database, requiring more SQL knowledge
- Limited support for automatic schema generation and migrations
Code Comparison
Hibernate ORM:
Session session = sessionFactory.openSession();
List<User> users = session.createQuery("FROM User WHERE age > :age", User.class)
.setParameter("age", 18)
.getResultList();
jOOQ:
DSLContext create = DSL.using(connection, SQLDialect.MYSQL);
Result<Record> result = create.select()
.from(USER)
.where(USER.AGE.gt(18))
.fetch();
Key Differences
- Hibernate ORM is an Object-Relational Mapping tool, while jOOQ is a SQL builder and executor
- Hibernate focuses on object-oriented domain modeling, jOOQ on type-safe SQL generation
- Hibernate provides automatic dirty checking and lazy loading, jOOQ requires manual management
- jOOQ offers better support for database-specific features and optimizations
- Hibernate is more suitable for complex domain models, jOOQ for data-centric applications
requery - modern SQL based query & persistence for Java / Kotlin / Android
Pros of requery
- Lightweight and less complex, with a smaller codebase
- Supports reactive programming with RxJava integration
- Faster compile times and reduced build complexity
Cons of requery
- Less mature and smaller community compared to Hibernate
- Fewer advanced features and customization options
- Limited documentation and learning resources
Code Comparison
Hibernate ORM:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
// Getters and setters
}
requery:
@Entity
public interface User {
@Key @Generated
int getId();
String getName();
void setName(String name);
}
Summary
requery offers a lightweight alternative to Hibernate ORM with reactive programming support and faster compile times. However, it lacks the maturity, extensive feature set, and community support of Hibernate. The code comparison shows that requery uses interfaces for entity definitions, while Hibernate uses classes with annotations. Developers should consider their project requirements and team expertise when choosing between these ORM solutions.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
== Hibernate ORM
image:https://img.shields.io/maven-central/v/org.hibernate.orm/hibernate-core.svg?label=Maven%20Central&style=for-the-badge[Maven Central,link=https://central.sonatype.com/search?namespace=org.hibernate.orm&sort=name] image:https://img.shields.io/github/actions/workflow/status/hibernate/hibernate-orm/ci.yml?branch=main&logo=GitHub&style=for-the-badge[GitHub Actions Status,link=https://github.com/hibernate/hibernate-orm/actions/workflows/ci.yml?query=branch%3Amain] image:https://img.shields.io/badge/Revved%20up%20by-Develocity-06A0CE?style=for-the-badge&logo=gradle[Develocity,link=https://develocity.commonhaus.dev/scans?search.rootProjectNames=Hibernate%20ORM] image:https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/jvm-repo-rebuild/reproducible-central/master/content/org/hibernate/orm/hibernate-core/badge.json&style=for-the-badge[Reproducible Builds,link=https://github.com/jvm-repo-rebuild/reproducible-central/blob/master/content/org/hibernate/orm/hibernate-core/README.md] image:https://testpilot.oracle.com/ords/testpilot/badges/github/hibernate/hibernate-orm[Oracle Test Pilot,link=https://testpilot.oracle.com/]
Hibernate ORM is a powerful object/relational mapping solution for Java, the de facto standard implementation of the https://www.oracle.com/java/technologies/persistence-jsp.html[Java Persistence API] (now also known as https://jakarta.ee/specifications/persistence/4.0/[Jakarta Persistence]), https://jakarta.ee/specifications/query/1.0/[Jakarta Query], and https://jakarta.ee/specifications/data/1.1/[Jakarta Data].
Hibernate exposes relational data in a natural and type safe form,
- making it easy to write complex queries and work with their results,
- letting the program easily synchronize changes made in memory with the database,
- respecting the ACID properties of transactions,
- automatically handling temporal data and audit logging,
- taking care of multi-tenancy and row-level security,
- and allowing performance optimizations to be made after the basic persistence logic has already been written.
Hibernate is the best way for a program written in Java to take advantage of the power of the relational model, and of the expressivity of SQL, without sacrificing performance or code reuse.
See https://hibernate.org/orm/[hibernate.org] for more information.
== Getting started
Documentation for Hibernate ORM is available at:
https://hibernate.org/orm/documentation
https://github.com/hibernate/hibernate-orm/blob/main/documentation/src/main/asciidoc/introduction/Configuration.adoc[This page] explains how to include Hibernate ORM in a Java project and configure a connection to the database.
== Building from sources
The build requires at least JDK 25, and produces Java 17 bytecode.
Hibernate uses https://gradle.org[Gradle] as its build tool. See the Gradle Primer section below if you're new to Gradle.
Contributors should read the link:CONTRIBUTING.md[Contributing Guide].
See the guides for setting up https://hibernate.org/community/contribute/intellij-idea/[IntelliJ] or https://hibernate.org/community/contribute/eclipse-ide/[Eclipse] as your development environment.
== Gradle Primer
The Gradle build tool has excellent documentation.
- https://docs.gradle.org/current/userguide/userguide_single.html[Gradle User Guide] is a typical user guide in that it follows a topical approach to describing all of the capabilities of Gradle.
- https://docs.gradle.org/current/dsl/index.html[Gradle DSL Guide] is unique and excellent in quickly getting up to speed on certain aspects of Gradle.
Here we summarize the features you'll need to get started in this project.
NOTE: The project has a https://docs.gradle.org/current/userguide/gradle_wrapper.html[Gradle Wrapper]. The rest of the section will assume execution via the wrapper.
=== Executing Tasks
To print a list of available build tasks, execute:
./gradlew tasks
To execute a task across all modules, simply execute the task from the root directory.
cd hibernate-orm ./gradlew build
Gradle visits each subproject and executes the task if the subproject defines it.
To execute a task in a specific module, either:
cdinto that module directory and execute the task, or- explicitly qualify the task name with the name of the module.
For example, to run the tests for the hibernate-core module from the root directory you could type:
./gradlew hibernate-core:test
=== Common tasks
The common tasks you might use in building Hibernate include:
build :: Assembles (jars) and tests this project
compile :: Performs all compilation tasks including staging resources from both main and test
jar :: Generates a jar archive with all the compiled classes
test :: Runs the tests
publishToMavenLocal or pTML :: Installs the project jar to your local Maven cache at ~/.m2/repository. Note that Gradle never uses this, but it can be useful for testing a build with other local Maven-based builds.
clean :: Cleans the build directory
== Testing and databases
Testing Hibernate against an embedded h2 database is easy. Just run:
./gradlew test
To run against another database:
- <<start-test-database,start the database>> using
podmanordocker, and then - run the tests with the correct <<profiles,profile>> for that database.
=== Using profiles [[profiles]]
The Hibernate build defines several database testing profiles in local.databases.gradle.
A profile may be activated by name using the db build property which can be passed either:
- as a JVM system property
-Ddb=..., or - as a Gradle project property
-Pdb=....
Examples below use the Gradle project property.
gradle clean build -Pdb=postgresql
To run a test from your IDE, you need to ensure the property expansions happen. Use the following command:
gradle clean compile -Pdb=postgresql
NOTE: To run tests against a JDBC driver that is not available via Maven central, add the driver to your local Maven repository (~/.m2/repository) or to a personal Maven repository server.
=== Starting a test database as a container [[start-test-database]]
If podman or docker is installed, there's no need to install any database to test Hibernate.
The script db.sh starts a preconfigured database which can be used for testing.
Simply run the following command:
./db.sh postgresql
Running ./db.sh without an argument prints a list of available database configurations.
By default, ./db.sh kills any previously started database.
To keep multiple databases running, use --keep-orphans or -k:
./db.sh -k postgresql ./db.sh -k mysql
When the database is properly started, run tests with the corresponding profile, for example, -Pdb=postgresql for PostgreSQL.
The system property dbHost configures the IP address of your docker host.
The command for running tests might look like the following:
./gradlew test -Pdb=postgresql "-DdbHost=192.168.99.100"
The following table illustrates a list of commands for various databases that can be tested locally.
|=== |Database |Start database |Run tests
| H2 |
|---|
./gradlew test -Pdb=h2 |
| HSQLDB |
|---|
./gradlew test -Pdb=hsqldb |
| Apache Derby |
|---|
./gradlew test -Pdb=derby |
|MySQL
|./db.sh mysql
|./gradlew test -Pdb=mysql
|MariaDB
|./db.sh mariadb
|./gradlew test -Pdb=mariadb
|PostgreSQL
|./db.sh postgresql
|./gradlew test -Pdb=postgresql
|PostgreSQL with PostGIS (required for hibernate-spatial)
|./db.sh postgis
|./gradlew test -Pdb=postgis
|EnterpriseDB
|./db.sh edb
|./gradlew test -Pdb=edb
|Oracle
|./db.sh oracle
|./gradlew test -Pdb=oracle
|DB2
|./db.sh db2
|./gradlew test -Pdb=db2
|SQL Server
|./db.sh mssql
|./gradlew test -Pdb=mssql
|Sybase ASE (jTDS)
|./db.sh sybase
|./gradlew test -Pdb=sybase
|Sybase ASE (jConnect)
|./db.sh sybase
|./gradlew test -Pdb=sybase_jconn
|SAP HANA
|./db.sh hana
|./gradlew test -Pdb=hana
|CockroachDB
|./db.sh cockroachdb
|./gradlew test -Pdb=cockroachdb
|TiDB
|./db.sh tidb
|./gradlew test -Pdb=tidb
|Informix
|./db.sh informix
|./gradlew test -Pdb=informix
|Spanner PostgreSQL
|./db.sh spanner_pg
|./gradlew test -Pdb=spannerpgsql
|CUBRID
|./db.sh cubrid
|./gradlew test -Pdb=cubrid
|===
Stopping a test database
To stop a container, use the stop command.
For example:
[source]
podman stop mariadb
Substitute docker for podman if appropriate.
== Continuous Integration
See link:MAINTAINERS.md#ci[MAINTAINERS.md] for information about CI.
Top Related Projects
Kotlin SQL Framework
Simplifies the development of creating a JPA-based data access layer.
MyBatis SQL mapper framework for Java
jOOQ is the best way to write SQL in Java
requery - modern SQL based query & persistence for Java / Kotlin / Android
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot