Introduction to Hibernate Framework
- Features and benefits of Hibernate Framework
- Architecture of Hibernate Framework
- Introduction to Persistence Lifecycle in Hibernate Framework
Introduction to Hibernate Framework
Hibernate is object-relational mapping framework for java. It simplifies the development of java application to interact with the database. Hibernate is an open source, lightweight, ORM (Object Relational Mapping) tool. The ORM tool internally uses the JDBC API to interact with the database
How Hibernate Works
Firstly we need to load the configuration xml because once we load it , automatically mapping file will be loaded as it is registered in configuration file.To load configuration file, we need to create the object of Configuration class and need to call configure() method.
Configuration cf = new Configuration();
cf.configure(“hibernate.cfg.xml”);
cf will read data from hibernate.cfg.xml, stores the data in different variables and all these variables are grouped into one high level hibernate object we call as SessionFactory object.
SessionFactory sf = cf.buildSessionFactory();
SessionFactory is an interface and SessionFactoryImpl is implemented class for it, So internally we create object of SessionFactoryImpl class and stores it in interface reference.
So sf contains all data regarding configuration file. Then Session is created. It is also an interface and SessionImpl is implemented class. Whenever session is opened, internally database connection will get opened.
Session session = sf.openSession();
sf = SessfionFactory object
While working on insert,update,delete hibernate needs a logical transaction, but for select it doesn't require any transaction. In order to begin transaction, we need to call a method beginTransaction() given by Session Interface
Transaction tx = session.beginTransaction();
We use following Session methods to move objects from application to database
session .save(s) : Inserting object ‘s’ into database
session.update(s) : Updating object ‘s’ in the database
session.load(s) : Selecting objcet ‘s’ object
session.delete(s) : Deleting object ‘s’ from database
Finally we need to call commit() in transaction.
tx.commit();
And we to need to close connection as
session. close()
And finally close SessionFactory as
sf.close()
Features of Hibernate
Transparent PersistenceHere, Transparent mean complete seperation of concerns between the persistent classes and the persistent logic where the persistent classes are unaware of and have no dependency to the- persistence mechanism Hibernate doesnot require that any special superclasses or interfaces to be implemented by the persistent classes.
Object-Oriented Query Language
Hibernate uses HQL(Hibernate Query Language) and HQL is an object-oriented query language similar to SQL but instead of operating on tables and columns, HQL works with persistent objects and its properties. It is database independent query language because instead of table name, we use class name in HQL. It provides full support for polymorphic queries.
A query like:
from Cat as cat
returns instances not only of cat but also of its subclasses. Hibernate query can name any java class in where clause and the query will return instances of all persistent classes that extend that class.
Automatic Primary Key Generation
There are multiple key generation strategies. Increment keyword is used for automatic primary key generation.
Lazy Loading
It decides when to load the child object while loading the parent object. The default behaviour is to load 'property values eagerly' and to load 'collections lazily'
Also @OneToMany and @ManyToMany associations are defaulted to LAZY loading and @OneToOne and @ManyToOne are defaulted to EAGER Laoding. It is by default using xml mappings but not when using annotations.
To Enable lazy load when we are using annotations we must use
"fetch="FetchType.LAZY"
FetchType.LAZY = Doesn’t load the relationships unless explicitly “asked for” via getter(not to load the child )
FetchType.EAGER = Loads ALL relationships
Object/Relational Mapping
It maps the persistent objects to the columns of the tables in the database. Mapping can be done using xml file as well as by using annotations.
Benefits of Hibernate
OpenSource and lightweight : Hibernate Framework is open source under LGPL license and lightweight
Database Independent Query: Hibernate has its own query language i.e HQL. It is object-oriented version of SQL. It generates the database independent queries. We don't need to write database specific queries. If we change our database, then also application will work.
Automatic Table Creation: Hibernate provide facility to create the tables of database automatically.
Fast Performance : The performance of hibernate framework is fast because cache is internally used in hibernate framework. There are two types of cache in hibernate framework- first level cache and second level cache. First level cache is enabled by default and you donot need to do anything to get this functionality working. Infact, you cannot disable it forcefully
First Level Cache
It is associated with session object. Session Object is created on demand from session factory and it is lost, once session is closed. Similarly, first level cache associated with session object is available till session object is alive. It is available to that session object only not accessible to any other session objects. When we query entity for the first time, it is retrived from the database and stored in the first level cache associated with the session.
Second Level Cache
It is created in the session factory scope and is available to all sessions which are created using particluar session factory. It means if one session factory is closed, all the cache associated with it die.
When session try to load an entity, it firstly looks into the first level cache. If cached copy of the entity is present, it is returned as result of load method. If there is no cached entity, Second level cache is looked for cached entity. If Second level cache has cached entity, it is returned as a result of load method. But, before returning the entity, It is stored in first level cache also so that next innvocation for entity will return the entity from first level cache itself and there is no need to go to second level. If entity is not found n both the levels, then database query is executed and the entity is stored in both the cache levels before returning the response.
Architecture of Hibernate
The Hibernate architecture includes many objects: session factory, transaction factory, connection factory, session, transaction etc. There are 4 layers in hibernate architecture: -java application layer, hibernate framework layer, backhand api layer and database layer
High level architecture of Hibernate with mapping file and configuration file.
Elements of Hibernate Architecture
Session Factory: The org.hibernate.SessionFactory interface provides factory method to get the object of Session. It holds second level cache (optional) of data. The SessionFactory is a factory of session and client of ConnectionProvider.
Session: The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object.
Transaction: The org.hibernate.Transaction interface provides methods for transaction management.
Connection Provider: It is the factory of JDBC connections.
Transaction Factory: It is factory of transaction
Persistence Lifecycle
Hibernate is a transparent persistence mechanism - Classes are unaware of their own persistence capability. It has three states respect to its persistence lifecycle which are transient, persistent and detached. In a lifecycle, the object can transition from transient to persistent to detached states.
Transient Objects
Objects instantiated using new operator aren't immediately persistent. Their state is transient. They aren't associated with any database table row. When that object is de-referenced it loses its state and goes to detached state which will be eligible to garbage collected. For an instance to transition from transient to persistent state requires a save() call to persistence manager
Persistent Objects
A persistent instance is any instance with database entity. Persistent instance may be made transient via delete() call to persistence manager, resulting in deletion of corresponding row of the database. Persistent objects are synchronized with the database.
Detached Objects
Detached objects are no longer synchronized with the database. Persistent instances are detached when we close() the session.
Evict() method of session can be used to detach the object from session cache.
How to Re-attach a detached Object?
Both update() and merge() methods in hibernate are used to convert the object which is in detached state into persistence state.
Thank You Amarpreet
No comments:
Post a Comment