Hibernate Architecture
Hibernate Architecture
Prerequisites: Introduction of Hibernate
Hibernate: Hibernate is a framework which is used to develop persistence logic
which is independent of Database software. In JDBC to develop persistence logic
we deal with primitive types. Whereas Hibernate framework we use Objects to
develop persistence logic which are independent of database software.
Following is a detailed view of the Hibernate Application Architecture with its
important core classes.
Hibernate uses various existing Java APIs, like JDBC, Java Transaction
API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a
rudimentary level of abstraction of functionality common to relational
databases, allowing almost any database with a JDBC driver to be supported by
Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application
servers.
Following section gives brief description of each of the class objects involved in
Hibernate Application Architecture.
Configuration Object
The Configuration object is the first Hibernate object you create in any
Hibernate application. It is usually created only once during application
initialization. It represents a configuration or properties file required by the
Hibernate.
The Configuration object provides two keys components −
Database Connection − This is handled through one or more
configuration files supported by Hibernate. These files
are hibernate.properties and hibernate.cfg.xml.
Class Mapping Setup − This component creates the connection between
the Java classes and database tables.
Configuration is a class which is present in org.hibernate.cfg package. It
activates Hibernate framework. It reads both configuration file and
mapping files.
It activate Hibernate Framework
Configuration cfg=new Configuration();
It read both cfg file and mapping files
cfg.configure();
It checks whether the config file is syntactically correct or not.
If the config file is not valid then it will throw an exception. If it is valid
then it creates a meta-data in memory and returns the meta-data to
object to represent the config file.
SessionFactory Object
Configuration object is used to create a SessionFactory object which in turn
configures Hibernate for the application using the supplied configuration file and
allows for a Session object to be instantiated. The SessionFactory is a thread
safe object and used by all the threads of an application.
The SessionFactory is a heavyweight object; it is usually created during
application start up and kept for later use. You would need one SessionFactory
object per database using a separate configuration file. So, if you are using
multiple databases, then you would have to create multiple SessionFactory
objects.
Session Object
A Session is used to get a physical connection with a database. The Session
object is lightweight and designed to be instantiated each time an interaction is
needed with the database. Persistent objects are saved and retrieved through a
Session object.
The session objects should not be kept open for a long time because they are
not usually thread safe and they should be created and destroyed them as
needed.
Session is an interface which is present in org.hibernate package. Session
object is created based upon SessionFactory object i.e. factory.
It opens the Connection/Session with Database software through
Hibernate Framework.
It is a light-weight object and it is not thread-safe.
Session object is used to perform CRUD operations.
Session session=factory.buildSession();
Transaction Object
A Transaction represents a unit of work with the database and most of the
RDBMS supports transaction functionality. Transactions in Hibernate are
handled by an underlying transaction manager and transaction (from JDBC or
JTA).
This is an optional object and Hibernate applications may choose not to use this
interface, instead managing transactions in their own application code.
Query Object
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve
data from the database and create objects. A Query instance is used to bind
query parameters, limit the number of results returned by the query, and finally
to execute the query.
What is JDBC?
JDBC stands for Java Database Connectivity. It provides a set of Java API for
accessing the relational databases from Java program. These Java APIs enables
Java programs to execute SQL statements and interact with any SQL compliant
database.
JDBC provides a flexible architecture to write a database independent application
that can run on different platforms and interact with different DBMS without any
modification.
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
Consider the above objects are to be stored and retrieved into the following RDBMS
table −
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
First problem, what if we need to modify the design of our database after having
developed a few pages or our application? Second, loading and storing objects in a
relational database exposes us to the following five mismatch problems −
1
Granularity
Sometimes you will have an object model, which has more classes than the number of
corresponding tables in the database.
2
Inheritance
RDBMSs do not define anything similar to Inheritance, which is a natural paradigm in object-
oriented programming languages.
3
Identity
An RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines
both object identity (a==b) and object equality (a.equals(b)).
4
Associations
Object-oriented languages represent associations using object references whereas an
RDBMS represents an association as a foreign key column.
5
Navigation
The ways you access objects in Java and in RDBMS are fundamentally different.
What is ORM?
ORM stands for Object-Relational Mapping (ORM) is a programming technique for
converting data between relational databases and object oriented programming
languages such as Java, C#, etc.
An ORM system has the following advantages over plain JDBC −
Sr.No Advantages
.
Sr.No Solutions
.
2 A language or API to specify queries that refer to classes and properties of classes.
4 A technique to interact with transactional objects to perform dirty checking, lazy association
fetching, and other optimization functions.
First
nex Hibernate Example without
IDE
Here, we are going to create the first hibernate application without IDE. For creating
the first hibernate application, we need to follow the following steps:
Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Employee {
4. private int id;
5. private String firstName,lastName;
6.
7. public int getId() {
8. return id;
9. }
10. public void setId(int id) {
11. this.id = id;
12. }
13. public String getFirstName() {
14. return firstName;
15. }
16. public void setFirstName(String firstName) {
17. this.firstName = firstName;
18. }
19. public String getLastName() {
20. return lastName;
21. }
22. public void setLastName(String lastName) {
23. this.lastName = lastName;
24. }
25.
26.
27. }
o hibernate-mapping : It is the root element in the mapping file that contains all
the mapping elements.
o class : It is the sub-element of the hibernate-mapping element. It specifies the
Persistent class.
o id : It is the subelement of class. It specifies the primary key attribute in the
class.
o generator : It is the sub-element of id. It is used to generate the primary key.
There are many generator classes such as assigned, increment, hilo, sequence,
native etc. We will learn all the generator classes later.
o property : It is the sub-element of class that specifies the property name of the
Persistent class.
employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.mypackage.Employee" table="emp1000">
8. <id name="id">
9. <generator class="assigned"></generator>
10. </id>
11.
12. <property name="firstName"></property>
13. <property name="lastName"></property>
14.
15. </class>
16.
17. </hibernate-mapping>
3) Create the Configuration file
The configuration file contains information about the database and mapping file.
Conventionally, its name should be hibernate.cfg.xml .
hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</
property>
12. <property name="connection.username">system</property>
13. <property name="connection.password">jtp</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
15. <mapping resource="employee.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11.
12. public class StoreData {
13. public static void main(String[] args) {
14.
15. //Create typesafe ServiceRegistry object
16. StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configur
e("hibernate.cfg.xml").build();
17.
18. Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
19.
20. SessionFactory factory = meta.getSessionFactoryBuilder().build();
21. Session session = factory.openSession();
22. Transaction t = session.beginTransaction();
23.
24. Employee e1=new Employee();
25. e1.setId(101);
26. e1.setFirstName("Gaurav");
27. e1.setLastName("Chawla");
28.
29. session.save(e1);
30. t.commit();
31. System.out.println("successfully saved");
32. factory.close();
33. session.close();
34.
35. }
36. }
HQL | Introduction
Hibernate Query Language (HQL) is an easy to learn and powerful query language designed
as an object-oriented extension to SQL that bridges the gap between the object-oriented
systems and relational databases. The HQL syntax is very similar to the SQL syntax. it has a
rich and powerful object-oriented query language available with the Hibernate ORM, which is
a technique of mapping the objects to the databases. The data from object-oriented systems
are mapped to relational databases with a SQL-based schema.
Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it
doesn't depends on the table of the database. Instead of table name, we use class name
in HQL. So it is database independent query language.
HQL can also be used to retrieve objects from database through O/R mapping by performing
the following tasks:
Advantage of HQL
There are many advantages of HQL. They are as follows:
o database independent
o supports polymorphic queries
o easy to learn for Java Programmer
o
HQL queries
o A query within a query is known as a subquery and is surrounded by
parenthesis. An example of a subquery is subselect in which a select clause
is embedded in another clause, such as select, from and where clause.
Subquery is executed before the execution of the main query.
The query interface provides many methods. There is given commonly used methods:
8. FROM Clause
9. You will use FROM clause if you want to load a complete persistent objects
into memory. Following is the simple syntax of using FROM clause −
10. String hql = "FROM Employee";
11. Query query = session.createQuery(hql);
12. List results = query.list();
13. If you need to fully qualify a class name in HQL, just specify the package and
class name as follows −
14. String hql = "FROM com.hibernatebook.criteria.Employee";
15. Query query = session.createQuery(hql);
16. List results = query.list();
17. AS Clause
18. The AS clause can be used to assign aliases to the classes in your HQL
queries, especially when you have the long queries. For instance, our
previous simple example would be the following −
19. String hql = "FROM Employee AS E";
20. Query query = session.createQuery(hql);
21. List results = query.list();
22. The AS keyword is optional and you can also specify the alias directly after
the class name, as follows −
23. String hql = "FROM Employee E";
24. Query query = session.createQuery(hql);
25. List results = query.list();
1
avg(property name)
The average of a property's value
2
count(property name or *)
The number of times a property occurs in the results
3
max(property name)
The maximum value of the property values
4
min(property name)
The minimum value of the property values
5
sum(property name)
The sum total of the property values
86. The distinct keyword only counts the unique values in the row set. The
following query will return only unique count −
87. String hql = "SELECT count(distinct E.firstName) FROM
Employee E";
88. Query query = session.createQuery(hql);
89. List results = query.list();
1
Query setFirstResult(int startPosition)
This method takes an integer that represents the first row in your result set, starting with row
0.
2
Query setMaxResults(int maxResult)
This method tells Hibernate to retrieve a fixed number maxResults of objects.
92. Using above two methods together, we can construct a paging component in
our web or Swing application. Following is the example, which you can
extend to fetch 10 rows at a time −
93. String hql = "FROM Employee";
94. Query query = session.createQuery(hql);
95. query.setFirstResult(1);
96. query.setMaxResults(10);
97. List results = query.list();