Basic Persistent Operations in the Client Application by using Hibernate Framework:
By using Hibernate to perform the basic Persistent operations in the client application we need to implement some basic steps.The basic steps involved in client Application are:
Step 1: Prepare Configuration Object.
Step 2: Build SessionFactory object.
Step 3: Obtain a Session.
Step 4: Perform the Persistence operations. Step 5: close the Session.
Step 1: Prepare Configuration Object:
Test.java
Test.java
After successfully preparing the configuration object by setting all the configuration parameters and mapping documents location, the configuration object is used to create the SessionFactory object, to do this we can use the buildSessionFactory() method of configuration.
After creating the SessionFactory the configuration object can be discarded.
Step 2: Build SessionFactory object:
SessionFactory:
Test.java
Explanation of above diagram:
Why Session factory is a heavy weight?
Session factory encapsulates session object, connections, Hibernate properties caching and mappings.
How To Create Session Factory in Hibernate ?
There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it states that the documentation is in complete. Also each incremental version gets changes on some of the important API.
In our earlier versions we have created the session factory as below: -
SessionFactory sessionFactory = configuration.buildSessionFactory();
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
Test.java
Step 3: Obtain a Session:
Session :-
SessionFactory:
Test.java
After obtaining the session we can use the session methods to perform CRUD(Create, Read, Update and Delete). Operations on the instances of mapped persistence classes.
Step 4: Perform the Persistence operations:
Session session=sessionFactory.openSession();
Test.java
- The org.hibernate.cfg.Configuration is a class and is the basic element of the Hibernate Api.
- An Object Oriented Representation of hibernate configuration file along with mapping file is known as Configuration object.
- By default Hibernate reads configuration file with the name “hibernate.cfg.xml” which is located in classes’ folder.
- If we want to change the file name (OR) if we want change the location of “hibernate.cfg.xml” then we need to pass user given configuration file name along with path to “configure()” method of Configuration class.
Configuration config = new Configuration();
config.configure("/com/gurugubelli/xml/hibernate.cfg.xml");
config.configure("/com/gurugubelli/xml/hibernate.cfg.xml");
- The Configuration class configure() method described in the below table
- configure() - Use the mappings and properties specified in an application resource named hibernate.cfg.xml.
- configure(Document document) - Use the mappings and properties specified in the given XML document.
- configure(File configFile) - Use the mappings and properties specified in the given application file.
- configure(String resource) - Use the mappings and properties specified in the given application resource.
- configure(URL url) - Use the mappings and properties specified in the given document.
- All the configure() methods described in the above table returns Configuration object.
- Configuration object stores the Configuration file data in different variables. Finally all these variables are grouped and created one high level hibernate object called as SessionFactory object.
- So configuration object only meant for creating SessionFactory object.
- We can also provide the configuration information programmatically, without writing configuration file.(But it will become Hard Coding, So not advisable)
//Configuration in a programmatic manner:
Configuration configuration = new Configuration();
//Adding the Connection details to Configuration object in Programmatically
configuration.setProperty("connection.driver_class", "oracle.jdbc.driver.OracleDriver");
configuration.setProperty("hibernate.connection.url","jdbc:oracle:thin:@localhost:1521:XE");
configuration.setProperty("hibernate.connection.username", "gurugubelli");
configuration.setProperty("hibernate.connection.password", "gurugubelli");
//Adding the hibernate properties to Configuration object in Programmatically
configuration.setProperty("hibernate.dialect","org.hibernate.dialect.Oracle9Dialect")
//Adding the mapping files to configuration object programmatically
configuration.addResource("Employee.hbm.xml");
configuration.addResource("PersonalDetails.hbm.xml");
Note: The Configuration object we can create only once for an application, at startup-time, that is while initializing the application.Configuration configuration = new Configuration();
//Adding the Connection details to Configuration object in Programmatically
configuration.setProperty("connection.driver_class", "oracle.jdbc.driver.OracleDriver");
configuration.setProperty("hibernate.connection.url","jdbc:oracle:thin:@localhost:1521:XE");
configuration.setProperty("hibernate.connection.username", "gurugubelli");
configuration.setProperty("hibernate.connection.password", "gurugubelli");
//Adding the hibernate properties to Configuration object in Programmatically
configuration.setProperty("hibernate.dialect","org.hibernate.dialect.Oracle9Dialect")
//Adding the mapping files to configuration object programmatically
configuration.addResource("Employee.hbm.xml");
configuration.addResource("PersonalDetails.hbm.xml");
After successfully preparing the configuration object by setting all the configuration parameters and mapping documents location, the configuration object is used to create the SessionFactory object, to do this we can use the buildSessionFactory() method of configuration.
After creating the SessionFactory the configuration object can be discarded.
Step 2: Build SessionFactory object:
SessionFactory:
- SessionFactory is an interface, present in "org.hibernate" package.
- SessionFactoryImpl is an implemented class of SessionFactory interface.
- SessionFactory is a heavy weight object that has to be created only once per application.
- SessionFactory is not a singleton.
- SessionFactory object provides lightweight session object's.
- Session Factory object is the factory for session objects.
- Generally one SessionFactory should be created for one database.
- When you have multiple databases in your application you should create multiple SessionFactory objects.
- If you are using two databases called MySQL and Oracle in your hibernate application then you need to build 2 SessionFactory object's.
- Sessionfactory is long live multithreaded object.
- SessionFactory is a ThreadSafe object.
- SessionFactory is an ImmutableObject.
- To build the SessionFactory object we can call buildSessionFactory() method from Configuration class.
- public SessionFactory buildSessionFactory()
Configuration configuration=new Configuration();
configuration.configure("/hibernate.cfg.xml");
SessionFactory sessionFactory = cfg.buildSessionFactory();
configuration.configure("/hibernate.cfg.xml");
SessionFactory sessionFactory = cfg.buildSessionFactory();
Explanation of above diagram:
- Hibernate software creates Built in JDBC connection pool having the set of JDBC connection object's.
- This connection pool created based on the details given in the configuration file and will represented with Hibernate SessionFactory object.
- Hibernate Session Object represents Persistence context
- Check next post for more details about connection pooling
Why Session factory is a heavy weight?
Session factory encapsulates session object, connections, Hibernate properties caching and mappings.
How To Create Session Factory in Hibernate ?
There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it states that the documentation is in complete. Also each incremental version gets changes on some of the important API.
In our earlier versions we have created the session factory as below: -
SessionFactory sessionFactory = configuration.buildSessionFactory();
- since Hibernate 4.x, this approach is deprecated. According to Hibernate 4.0 API docs, the Configuration class's buildSessionFactory() method is deprecated and it recommends developers to use the buildSessionFactory(ServiceRegistry) instead.
- Here is the new recommended code that is used to builds the SessionFactory based on a ServiceRegistry and obtains the Session:
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
- In hibernate 4.3 ServiceRegistryBuilder is deprecated so in the new Version’s it is recommended to use StandardServiceRegistryBuilder instead of ServiceRegitryBuilder.
Configuration configuration = new Configuration().configure("/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder();
serviceRegistry.applySettings(configuration.getProperties()).build();
// builds a session factory from the service registry
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder();
serviceRegistry.applySettings(configuration.getProperties()).build();
// builds a session factory from the service registry
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Step 3: Obtain a Session:
Session :-
- Session is an interface present in org.hibernate package and Sessionlmpl is an implemented class.
- Session object is called persistent manager for the hibernate application.
- It is a single-threaded (not-thread safe), short-lived object.
- It encapsulates the functionality of JDBC connection, statement object.
- It has convenience methods to perform persistent operations.
- When a session is opened then internally a connection with the database will be established.
- It is a factory for Transaction objects.
- Session Holds a mandatory(first-level) cache of persistent objects.
SessionFactory:
- The SessionFactory object is used to open a Hibernate Session. To do this we can use any one of the openSession() methods of SessionFactory.
- Methods of SessionFactory interface to open a new Session:
- public Session openSession() - This method Prepares a new session that obtains a jdbc connection object by using the connection Manager.
- public Session openSession(Connection connection) - This method prepares a new session that uses the given Connection
- public Session openSession(Interceptor interceptor) - This method prepares a new session that obtains a JDBC connection object by using the connection manager. The session is registered with the given Interceptor.
- public Session openSession(Connectioncon connection, Interceptor interceptor) - This method prepares a new session that uses the given JDBC connection object. The session is registered with the given Interceptor.
Configuration configuration = new Configuration();
configuration.configure("/hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
//get SessionFactory object reference, After getting the sessionFactory object we can obtain the session from sessionFactory
Session session = sessionFactory.openSession();
The Session interface has various convenience methods to perform the persistence operations.configuration.configure("/hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
//get SessionFactory object reference, After getting the sessionFactory object we can obtain the session from sessionFactory
Session session = sessionFactory.openSession();
After obtaining the session we can use the session methods to perform CRUD(Create, Read, Update and Delete). Operations on the instances of mapped persistence classes.
Step 4: Perform the Persistence operations:
Session session=sessionFactory.openSession();
- Thew session is an interface present in org.hibernate package, Using session object we can perform all the operations on DB, hibernate given to many methods in hiberate session object to perform operation on Data Base.
- Below are the some useful methods in hibernate sesssion object.
public Object get(Class class, Serializable id)
public Object load(Class class, Serializable id)
public Object get(String className, Serializable id)
public Object load(String className, Serializable id)
public Serializable save(Object object)
public void saveOrUpdate(Object object)
public void persist(Object object)
public Object merge(Object object)
public void update(Object object)
public void delete(Object object)
public Connection close();
public void clear();
public void evict(Object object)
public void refresh()
public void flush()
public Connection connection()
public boolean contains(Object object)
public boolean isConnected()
public Object load(Class class, Serializable id)
public Object get(String className, Serializable id)
public Object load(String className, Serializable id)
public Serializable save(Object object)
public void saveOrUpdate(Object object)
public void persist(Object object)
public Object merge(Object object)
public void update(Object object)
public void delete(Object object)
public Connection close();
public void clear();
public void evict(Object object)
public void refresh()
public void flush()
public Connection connection()
public boolean contains(Object object)
public boolean isConnected()
Step 5: close the Session:
- After we complete the use of session, it has to be closed to release all the resources such as cached entity object’s, collections, proxies, and a JDBC connection. But it is recommended to close the session explicitly by calling close() method.
Basic Persistent Operations in the Client Application by using Hibernate
Reviewed by Gurugubelli Technologies
on
December 28, 2016
Rating:
No comments: