Create Hibernate SessionFactory example
In the code snippets that follow, you can see the CreateHibernateSessionFactoryExample Class that applies all above steps and the hibernate.cfg.xml file, that holds all configuration for Hibernate.
package com.javacodegeeks.snippets.enterprise; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class CreateHibernateSessionFactoryExample < @SuppressWarnings("unused") private static SessionFactory sessionFactory; public static void main(String[] args) throws Exception < sessionFactory = new Configuration().configure().buildSessionFactory(); >>
com.mysql.jdbc.Driver jdbc:mysql://localhost/companydb jcg jcg 5 org.hibernate.dialect.MySQLDialect thread org.hibernate.cache.NoCacheProvider true true update
This was an example of how to create a new SessionFactory example in Hibernate.
Sessionfactory in java example
- Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
- A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
- How to maintain polyglot persistence for microservices Managing microservice data may be difficult without polyglot persistence in place. Examine how the strategy works, its challenges.
- Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
- How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
- GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
- Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
- 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
- How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
- BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
- The latest from Black Hat USA 2023 Use this guide to Black Hat USA 2023 to keep up on breaking news and trending topics and to read expert insights on one of the .
- API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
- AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
- Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
- Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Bootstrapping SessionFactory in Hibernate
If you have been watching previous Hibernate releases then you must have noticed that they have deprecated a lot of classes in quick succession. Deprecated classes are AnnotationConfiguration , ServiceRegistryBuilder and so on.
In this tutorial, I am giving few examples of building SessionFactory in Hibernate 5 and 6 without using deprecated classes mentioned above. I am using the latest available hibernate version of Hibernate 6.
As we know that in hibernate, the services are classes that provide Hibernate with pluggable implementations of various types of functionality. Specifically, they are implementations of certain service contract interfaces. To hold, manage and provide access to services, we use service registry.
Generally, the following classes are used as per the requirements for building SessionFactory .
- ServiceRegistry : defines service registry contracts that applications are likely to want to utilize for configuring Hibernate behavior. The two popular implementations are BootstrapServiceRegistry, StandardServiceRegistry and SessionFactoryServiceRegistry.
- BootstrapServiceRegistry : holds the services Hibernate will need during bootstrapping and at run time. For example, it can store the reference to ClassLoaderService, IntegratorService or StrategySelector through BootstrapServiceRegistry instance.
- StandardServiceRegistry : hosts and manages services in runtime.
- SessionFactoryServiceRegistry : is designed to hold services that need access to the SessionFactory, for example, EventListenerRegistry and StatisticsImplementor.
- MetaData : an object containing the parsed representations of an application domain model and its mapping to a database.
- MetadataSources : provides the source information to be parsed to form MetaData.
2. Building SessionFactory with XML Configuration
Generally, the hibernate.cfg.xml file contains the database connectivity and Enitity classes information. Additionally, we can have .hbm files as well.
org.h2.Driver jdbc:h2:mem:test sa org.hibernate.dialect.H2Dialect true true create-drop thread
To build the SessionFactory using the above XML configuration, we can follow the given code template.
public class HibernateUtil < private static SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() < try < if (sessionFactory == null) < StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .configure() .build(); Metadata metadata = new MetadataSources(standardRegistry) .getMetadataBuilder() .build(); sessionFactory = metadata.getSessionFactoryBuilder().build(); >return sessionFactory; > catch (Throwable ex) < throw new ExceptionInInitializerError(ex); >> public static SessionFactory getSessionFactory() < return sessionFactory; >public static void shutdown() < getSessionFactory().close(); >>
Do not forget to close the session factory using close() method when the application shuts down.
3. Building SessionFactory with Properties Configuration
If we do not want to create hibernate.cfg.xml file then we can provide all the connection properties using a Map in the StandardServiceRegistryBuilder.applySettings() method.
SessionFactory sessionFactory = null; Map settings = new HashMap<>(); settings.put("hibernate.connection.driver_class", "org.h2.Driver"); settings.put("hibernate.connection.url", "jdbc:h2:mem:test"); settings.put("hibernate.connection.username", "sa"); settings.put("hibernate.connection.password", ""); settings.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); settings.put("hibernate.current_session_context_class", "thread"); settings.put("hibernate.show_sql", "true"); settings.put("hibernate.format_sql", "true"); settings.put("hibernate.hbm2ddl.auto", "create-drop"); try < ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .applySettings(settings).build(); Metadata metadata = new MetadataSources(standardRegistry) .addAnnotatedClass(EmployeeEntity.class) .getMetadataBuilder() .build(); sessionFactory = metadata.getSessionFactoryBuilder().build(); >catch (Throwable ex)
To add the metadata about entity classes and field mappings, we can use various methods provided by MetadataSources.
MetadataSources sources = new MetadataSources(standardRegistry) .addAnnotatedClass(MyEntity.class) .addAnnotatedClassName("org.hibernate.example.Customer") .addResource("org/hibernate/example/Order.hbm.xml") .addResource("org/hibernate/example/Product.orm.xml");
In this hibernate tutorial, we learned to create the SessionFactory using hibernate’s native support. We learned to provide the metadata using the XML file, and also properties files.