This post is a quick reference to Hibernate XML or Java-based configuration. You can simply copy paste these hibernate configuration snippets in your Hibernate application.
Hibernate configuration File [XML based configuration] - hibernate.cfg.xml
The configuration file contains information about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml.
Let's create an XML file named as hibernate.cfg.xml under resources folder and write the following code in it.
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate_db?useSSL=false</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create-drop</property>
<!-- dbcp connection pool configuration -->
<property name="hibernate.dbcp.initialSize">5</property>
<property name="hibernate.dbcp.maxTotal">20</property>
<property name="hibernate.dbcp.maxIdle">10</property>
<property name="hibernate.dbcp.minIdle">5</property>
<property name="hibernate.dbcp.maxWaitMillis">-1</property>
<mapping class="net.javaguides.hibernate.entity.Student" />
</session-factory>
</hibernate-configuration>
Database connection properties
- hibernate.connection.driver_class or javax.persistence.jdbc.driver (e.g. org.postgresql.Driver) - Names the JDBC Driver class name.
- hibernate.connection.url or javax.persistence.jdbc.url (e.g. jdbc:postgresql:hibernate_orm_test) - Names the JDBC connection URL.
- hibernate.connection.username or javax.persistence.jdbc.user - Names the JDBC connection user name.
- hibernate.connection.password or javax.persistence.jdbc.password - Names the JDBC connection password.
- hibernate.connection.isolation (e.g. REPEATABLE_READ or Connection.TRANSACTION_REPEATABLE_READ) - Names the JDBC connection transaction isolation level.
- hibernate.connection.autocommit (e.g. true or false (default value)) - Names the initial autocommit mode for JDBC Connections returned from a connection pool created in certain ConnectionProvider impl.
- hibernate.connection.provider_disables_autocommit (e.g. true or false (default value)) - Indicates a promise by the user that Connections that Hibernate obtains from the configured ConnectionProvider have auto-commit disabled when they are obtained from that provider, whether that provider is backed by a DataSource or some other Connection pooling mechanism.
Hibernate internal connection pool options
- hibernate.connection.initial_pool_size (e.g. 1 (default value)) - Minimum number of connections for the built-in Hibernate connection pool.
- hibernate.connection.pool_size (e.g. 20 (default value)) - Maximum number of connections for the built-in Hibernate connection pool.
- hibernate.connection.pool_validation_interval (e.g. 30 (default value)) - The number of seconds between two consecutive pool validations. During validation, the pool size can increase or decreases based on the connection acquisition request count.
c3p0 properties
- hibernate.c3p0.min_size (e.g. 1) - Minimum size of C3P0 connection pool.
- hibernate.c3p0.max_size (e.g. 5) - Maximum size of C3P0 connection pool.
- hibernate.c3p0.timeout (e.g. 30) - Maximum idle time for C3P0 connection pool.
- hibernate.c3p0.max_statements (e.g. 5) - Maximum size of C3P0 statement cache.
- hibernate.c3p0.acquire_increment (e.g. 2) - The number of connections acquired at a time when there’s no connection available in the pool.
- hibernate.c3p0.idle_test_period (e.g. 5) - Idle time before a C3P0 pooled connection is validated.
- hibernate.c3p0 - A setting prefix used to indicate additional c3p0 properties that need to be passed to the underlying c3p0 connection pool.
Hibernate utility Class - Read hibernate.cfg.xml file
Create a helper class to bootstrap hibernate SessionFactory. In most Hibernate applications, the SessionFactory should be instantiated once during application initialization. The single instance should then be used by all code in a particular process, and any Session should be created using this single SessionFactory. The SessionFactory is thread-safe and can be shared; a Session is a single-threaded object.
The bootstrapping API is quite flexible, but in most cases, it makes the most sense to think of it as a 3 step process:
- Build the StandardServiceRegistry
- Build the Metadata
- Use those 2 to build the SessionFactory
package net.javaguides.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Create registry
registry = new StandardServiceRegistryBuilder().configure().build();
// Create MetadataSources
MetadataSources sources = new MetadataSources(registry);
// Create Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
Hibernate Java Based Configuration
The HibernateUtil Java configuration file contains information about the database and mapping file. Java Hibernate settings equivalent to hibernate.cfg.xml's properties. Let's create a HibernateUtil file and write the following code in it.
package net.javaguides.hibernate.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import net.javaguides.hibernate.entity.Student;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3306/hibernate_db?useSSL=false");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "root");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Student.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
- ServiceRegistry holds the services that Hibernate will need during bootstrapping and at runtime.
- StandardServiceRegistryBuilder - Builder for standard ServiceRegistry instances.
- HibernateUtil - This is helper class to bootstrap hibernate SessionFactory. In most Hibernate applications, the SessionFactory should be instantiated once during application initialization. The single instance should then be used by all code in a particular process, and any Session should be created using this single SessionFactory. The SessionFactory is thread-safe and can be shared; a Session is a single-threaded object.
GitHub Repository
The complete source code of this article available on my GitHub Repository - https://github.com/RameshMF/Hibernate-ORM-Tutorials
Conclusion
In this post, we have discussed a quick reference to Hibernate XML or Java-based configuration. You can simply copy paste these hibernate configuration snippets in your Hibernate application.
You can learn more about Hibernate ORM Framework at Hibernate Tutorial
Comments
Post a Comment
Leave Comment