Hibernate ORM core functionality - a powerful object/relational mapping solution for Java that implements JPA (Jakarta Persistence API)
Hibernate Core provides comprehensive configuration and bootstrap APIs for setting up the ORM framework, including metadata sources, service registries, and SessionFactory creation. The bootstrap process involves configuring mappings, database connections, and runtime behavior.
Entry point for specifying entity mappings and configuration sources.
/**
* Entry point for specifying sources of mapping metadata
*/
public class MetadataSources {
/**
* Create MetadataSources with the given service registry
* @param serviceRegistry the service registry to use
*/
public MetadataSources(ServiceRegistry serviceRegistry);
/**
* Add an annotated class as a source of mapping metadata
* @param annotatedClass the annotated entity class
* @return this MetadataSources for chaining
*/
public MetadataSources addAnnotatedClass(Class<?> annotatedClass);
/**
* Add multiple annotated classes
* @param annotatedClasses the annotated entity classes
* @return this MetadataSources for chaining
*/
public MetadataSources addAnnotatedClasses(Class<?>... annotatedClasses);
/**
* Add a package containing annotated classes
* @param packageName the package name to scan
* @return this MetadataSources for chaining
*/
public MetadataSources addPackage(String packageName);
/**
* Add a mapping resource (hbm.xml file)
* @param name the resource name/path
* @return this MetadataSources for chaining
*/
public MetadataSources addResource(String name);
/**
* Add a mapping file
* @param file the mapping file
* @return this MetadataSources for chaining
*/
public MetadataSources addFile(File file);
/**
* Add a JAR file containing mapping resources
* @param jar the JAR file
* @return this MetadataSources for chaining
*/
public MetadataSources addJar(File jar);
/**
* Get a MetadataBuilder for additional configuration
* @return MetadataBuilder instance
*/
public MetadataBuilder getMetadataBuilder();
/**
* Build the metadata with default settings
* @return the built Metadata
*/
public Metadata buildMetadata();
}Builder for configuring metadata processing options.
/**
* Builder for configuring metadata processing
*/
public interface MetadataBuilder {
/**
* Apply a naming strategy for database objects
* @param namingStrategy the naming strategy to use
* @return this MetadataBuilder for chaining
*/
MetadataBuilder applyNamingStrategy(NamingStrategy namingStrategy);
/**
* Apply basic type configurations
* @param typeContributor the type contributor
* @return this MetadataBuilder for chaining
*/
MetadataBuilder applyTypes(TypeContributor typeContributor);
/**
* Apply additional mapping information
* @param contributor the metadata contributor
* @return this MetadataBuilder for chaining
*/
MetadataBuilder applySources(MetadataSourcesContributor contributor);
/**
* Set the schema charset
* @param charset the charset to use
* @return this MetadataBuilder for chaining
*/
MetadataBuilder enableGlobalNationalizedCharacterDataSupport(boolean enabled);
/**
* Build the final Metadata instance
* @return the configured Metadata
*/
Metadata build();
}Container for mapping metadata and runtime metamodel information.
/**
* Container for mapping metadata
*/
public interface Metadata {
/**
* Get a SessionFactoryBuilder for creating SessionFactory instances
* @return SessionFactoryBuilder instance
*/
SessionFactoryBuilder getSessionFactoryBuilder();
/**
* Build a SessionFactory with default settings
* @return the configured SessionFactory
*/
SessionFactory buildSessionFactory();
/**
* Get database metadata information
* @return Database metadata
*/
Database getDatabase();
/**
* Get all entity bindings
* @return collection of entity bindings
*/
Collection<PersistentClass> getEntityBindings();
/**
* Get entity binding by class
* @param entityClass the entity class
* @return the entity binding or null
*/
PersistentClass getEntityBinding(String entityName);
/**
* Get all collection bindings
* @return collection of collection bindings
*/
Collection<Collection> getCollectionBindings();
/**
* Get named query definitions
* @return map of named queries
*/
Map<String, NamedQueryDefinition> getNamedQueryDefinitions();
/**
* Get named native query definitions
* @return map of named native queries
*/
Map<String, NamedNativeQueryDefinition> getNamedNativeQueryDefinitions();
}Builder for creating and configuring SessionFactory instances.
/**
* Builder for SessionFactory instances with additional configuration
*/
public interface SessionFactoryBuilder {
/**
* Apply additional SessionFactory configuration
* @param setting the setting name
* @param value the setting value
* @return this SessionFactoryBuilder for chaining
*/
SessionFactoryBuilder applySetting(String setting, Object value);
/**
* Apply multiple settings
* @param settings map of settings
* @return this SessionFactoryBuilder for chaining
*/
SessionFactoryBuilder applySettings(Map<String, Object> settings);
/**
* Add a SessionFactory observer
* @param observer the observer to add
* @return this SessionFactoryBuilder for chaining
*/
SessionFactoryBuilder addSessionFactoryObserver(SessionFactoryObserver observer);
/**
* Apply an interceptor
* @param interceptor the interceptor to apply
* @return this SessionFactoryBuilder for chaining
*/
SessionFactoryBuilder applyInterceptor(Interceptor interceptor);
/**
* Apply a statement inspector
* @param statementInspector the statement inspector
* @return this SessionFactoryBuilder for chaining
*/
SessionFactoryBuilder applyStatementInspector(StatementInspector statementInspector);
/**
* Enable/disable statistics collection
* @param enabled whether to enable statistics
* @return this SessionFactoryBuilder for chaining
*/
SessionFactoryBuilder applyStatisticsSupport(boolean enabled);
/**
* Build the configured SessionFactory
* @return the SessionFactory instance
*/
SessionFactory build();
}Core configuration interfaces defining available settings.
/**
* Interface defining all available Hibernate configuration properties
*/
public interface AvailableSettings {
// Database connection settings
String JAKARTA_JDBC_DRIVER = "jakarta.persistence.jdbc.driver";
String JAKARTA_JDBC_URL = "jakarta.persistence.jdbc.url";
String JAKARTA_JDBC_USER = "jakarta.persistence.jdbc.user";
String JAKARTA_JDBC_PASSWORD = "jakarta.persistence.jdbc.password";
String DRIVER = "hibernate.connection.driver_class";
String URL = "hibernate.connection.url";
String USER = "hibernate.connection.username";
String PASS = "hibernate.connection.password";
// Connection pool settings
String POOL_SIZE = "hibernate.connection.pool_size";
String CONNECTION_PROVIDER = "hibernate.connection.provider_class";
// Database dialect
String DIALECT = "hibernate.dialect";
// Schema management
String HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
String SHOW_SQL = "hibernate.show_sql";
String FORMAT_SQL = "hibernate.format_sql";
// Cache settings
String USE_SECOND_LEVEL_CACHE = "hibernate.cache.use_second_level_cache";
String USE_QUERY_CACHE = "hibernate.cache.use_query_cache";
String CACHE_REGION_FACTORY = "hibernate.cache.region.factory_class";
// Transaction settings
String TRANSACTION_COORDINATOR_STRATEGY = "hibernate.transaction.coordinator_class";
String JTA_PLATFORM = "hibernate.transaction.jta.platform";
}
/**
* JDBC-related configuration settings
*/
public interface JdbcSettings {
String STATEMENT_BATCH_SIZE = "hibernate.jdbc.batch_size";
String STATEMENT_FETCH_SIZE = "hibernate.jdbc.fetch_size";
String USE_SCROLLABLE_RESULTSET = "hibernate.jdbc.use_scrollable_resultset";
String USE_GET_GENERATED_KEYS = "hibernate.jdbc.use_get_generated_keys";
}
/**
* Cache-related configuration settings
*/
public interface CacheSettings {
String CACHE_REGION_FACTORY = "hibernate.cache.region.factory_class";
String DEFAULT_CACHE_CONCURRENCY_STRATEGY = "hibernate.cache.default_cache_concurrency_strategy";
String CACHE_KEYS_FACTORY = "hibernate.cache.keys_factory";
}Service registry for managing Hibernate services and dependencies.
/**
* Service registry for managing Hibernate services
*/
public interface ServiceRegistry {
/**
* Get a service by type
* @param serviceRole the service type
* @return the service instance
*/
<R extends Service> R getService(Class<R> serviceRole);
/**
* Check if a service is available
* @param serviceRole the service type
* @return true if service is available
*/
<R extends Service> boolean requireService(Class<R> serviceRole);
}
/**
* Builder for creating service registries
*/
public class StandardServiceRegistryBuilder {
/**
* Create a new builder
*/
public StandardServiceRegistryBuilder();
/**
* Configure from hibernate.cfg.xml
* @return this builder for chaining
*/
public StandardServiceRegistryBuilder configure();
/**
* Configure from specified resource
* @param resourceName the configuration resource name
* @return this builder for chaining
*/
public StandardServiceRegistryBuilder configure(String resourceName);
/**
* Apply a setting
* @param settingName the setting name
* @param value the setting value
* @return this builder for chaining
*/
public StandardServiceRegistryBuilder applySetting(String settingName, Object value);
/**
* Apply multiple settings
* @param settings the settings map
* @return this builder for chaining
*/
public StandardServiceRegistryBuilder applySettings(Map<String, Object> settings);
/**
* Build the service registry
* @return the configured service registry
*/
public StandardServiceRegistry build();
}Hibernate provides access to the underlying JDBC connection for advanced scenarios.
/**
* Access to the underlying JDBC connection
*/
public interface SessionImplementor extends Session, SharedSessionContractImplementor {
/**
* Get the JDBC connection
* @return the underlying JDBC Connection
*/
Connection connection();
/**
* Disconnect from the current JDBC connection
*/
void disconnect();
/**
* Reconnect to a JDBC connection
* @param connection the JDBC connection to use
*/
void reconnect(Connection connection);
/**
* Check if currently connected to a JDBC connection
* @return true if connected
*/
boolean isConnected();
}
/**
* JDBC connection management
*/
public interface ConnectionProvider extends Service, Wrapped {
/**
* Obtain a connection from the underlying datasource
* @return the obtained connection
* @throws SQLException if unable to obtain connection
*/
Connection getConnection() throws SQLException;
/**
* Release a connection back to the underlying datasource
* @param connection the connection to release
* @throws SQLException if unable to release connection
*/
void closeConnection(Connection connection) throws SQLException;
/**
* Does this connection provider support aggressive release of JDBC connections
* @return true if aggressive release is supported
*/
boolean supportsAggressiveRelease();
}
/**
* JDBC work interface for executing work using raw JDBC
*/
public interface Work {
/**
* Execute work using the provided connection
* @param connection the JDBC connection to use
* @throws SQLException if SQL operations fail
*/
void execute(Connection connection) throws SQLException;
}
/**
* JDBC work interface that returns a result
* @param <T> the result type
*/
public interface ReturningWork<T> {
/**
* Execute work using the provided connection and return result
* @param connection the JDBC connection to use
* @return the result of the work
* @throws SQLException if SQL operations fail
*/
T execute(Connection connection) throws SQLException;
}import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
// Create service registry
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // Loads from hibernate.cfg.xml
.build();
try {
// Create metadata sources and add entity classes
MetadataSources sources = new MetadataSources(registry)
.addAnnotatedClass(User.class)
.addAnnotatedClass(Order.class)
.addAnnotatedClass(Product.class);
// Build metadata and SessionFactory
Metadata metadata = sources.buildMetadata();
SessionFactory sessionFactory = metadata.buildSessionFactory();
// Use the SessionFactory...
} finally {
StandardServiceRegistryBuilder.destroy(registry);
}import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
// Configure programmatically
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySetting(AvailableSettings.DRIVER, "org.h2.Driver")
.applySetting(AvailableSettings.URL, "jdbc:h2:mem:testdb")
.applySetting(AvailableSettings.USER, "sa")
.applySetting(AvailableSettings.PASS, "")
.applySetting(AvailableSettings.DIALECT, "org.hibernate.dialect.H2Dialect")
.applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop")
.applySetting(AvailableSettings.SHOW_SQL, true)
.applySetting(AvailableSettings.FORMAT_SQL, true)
.build();
SessionFactory sessionFactory = new MetadataSources(registry)
.addAnnotatedClass(User.class)
.buildMetadata()
.buildSessionFactory();// Create metadata with custom configuration
MetadataBuilder metadataBuilder = new MetadataSources(registry)
.addAnnotatedClass(User.class)
.getMetadataBuilder();
// Apply custom naming strategy
metadataBuilder.applyNamingStrategy(new CustomNamingStrategy());
// Build metadata and SessionFactory with additional options
Metadata metadata = metadataBuilder.build();
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
.applyInterceptor(new AuditInterceptor())
.applyStatisticsSupport(true)
.addSessionFactoryObserver(new CustomSessionFactoryObserver())
.build();Properties props = new Properties();
props.setProperty(AvailableSettings.DRIVER, "com.mysql.cj.jdbc.Driver");
props.setProperty(AvailableSettings.URL, "jdbc:mysql://localhost:3306/mydb");
props.setProperty(AvailableSettings.USER, "username");
props.setProperty(AvailableSettings.PASS, "password");
props.setProperty(AvailableSettings.DIALECT, "org.hibernate.dialect.MySQLDialect");
props.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate");
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(props)
.build();
SessionFactory sessionFactory = new MetadataSources(registry)
.addPackage("com.example.entities")
.buildMetadata()
.buildSessionFactory();Always properly close resources to avoid memory leaks:
StandardServiceRegistry registry = null;
SessionFactory sessionFactory = null;
try {
registry = new StandardServiceRegistryBuilder().configure().build();
sessionFactory = new MetadataSources(registry)
.addAnnotatedClass(User.class)
.buildMetadata()
.buildSessionFactory();
// Use SessionFactory...
} finally {
if (sessionFactory != null) {
sessionFactory.close();
}
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}Use different configuration files for different environments:
// Development
StandardServiceRegistry devRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate-dev.cfg.xml")
.build();
// Production
StandardServiceRegistry prodRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate-prod.cfg.xml")
.build();// Execute raw JDBC work
session.doWork(connection -> {
try (PreparedStatement stmt = connection.prepareStatement(
"UPDATE users SET last_access = ? WHERE user_id = ?")) {
stmt.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));
stmt.setLong(2, userId);
stmt.executeUpdate();
}
});
// Execute JDBC work that returns a result
Integer count = session.doReturningWork(connection -> {
try (PreparedStatement stmt = connection.prepareStatement(
"SELECT COUNT(*) FROM orders WHERE status = 'ACTIVE'");
ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getInt(1);
}
return 0;
}
});
// Access underlying JDBC connection (advanced usage)
SessionImplementor sessionImpl = (SessionImplementor) session;
Connection connection = sessionImpl.connection();
// Perform direct JDBC operations...Install with Tessl CLI
npx tessl i tessl/maven-org-hibernate-orm--hibernate-core