Hibernate Notes by Sriman
Hibernate Notes by Sriman
by Mr.sachin gaikwad
Hibernate class 1
• There are some drawbacks in file system:
• Data stored in not structured manager.
• No semantics .
• Hard to manage(like insert, delete , update the data etc).
• It is only Human understandable but not computer
understandable.
• We can’t reuse data for operation in program .
• It is like keeping records in notebook only.
• Data stored in character basis, B’Z of that it is very hard
to read the data char By char.
by Mr.sachin gaikwad
Hibernate class 2
• To overcome the problems of file system
CSV(character separated value) file has been invented.
• CSV is the file system which is used to stored data in
character format with value separator using comma(,).
It also lead to a problem while reading the data. B’z
actual data may contains a comma(,) it’s lead to get
wrong data input. And also it take more time to read
data.
• As same as file System CSV also have the bunch of
problems.
by Mr.sachin gaikwad
Hibernate class 2
• 1st CSV file leads some problems:
• It stored data in Character format .
• Data separated with comma.
• It is understandable by Human only.
• It is very hard to manipulation.
• Data may contains commas.
by Mr.sachin gaikwad
Hibernate class 3
• In the next version of CSV DisAdvantages:
• Data stored in fixed field size format which leads too many problems
for 5 character it take too much memory
• Wastage of memory.
• Its not easy to structured in file.
• Data not reusable it take more time to read char by char
• Data not in semantic format.
• Performance is very low.
• No relation between data.
• Its critical in manipulation of data.
• Even though it is extension of file system but not enough to perform
persistency.
by Mr.sachin gaikwad
Hibernate class 3 and 4
• XML(Extensible markup language)
• It is language used to stored data in tag based format.
• XML is invented by W3C org. and the version is 1.0 in current day also.
• Advantages
• Data will be stored in tag based format.
• Data will have high relationship b’w them.
• it has well structured .
• It has well semantics.
• Anyone can understand the data.
• It provided a validator called dtd (Document type Definition and xsd(xml schema
definition).
• Dtd and xsd have protocols about how to write the xml file.
• It is operable(means it can run in any platform).
• It does have any keywords (in the prog. World only XML lang. does have any keywords)
by Mr.sachin gaikwad
Hibernate class 4 and 5
• Disadvantages of XML
• It is not easy for common people to understand it.
• Without knowing we can’t write the xml file.
• Data will be stored in hierarchical format.
• Before writing xml we have to know dtd or xsd file.
• Xml speak more for storing the data.
• It consume more memory for little data also.
• We can stored data but while reading we’ll get more problems.
• IOStreams read data line by line, it couldn’t identified actual data in xml file.
Parsing technology we have to use.
• B’z of above reason xml also failed to persistence the data in it.
• To overcome the problems of xml Java has invented a Serialization concepts
which seems to be good compared with earlier file systems.
by Mr.sachin gaikwad
Hibernate class 5 and 6
• Serialization
• Its concept provided by Java Prog. Lang. to persist the data into file.
• Serialization means change the status of an objects in bit or byte.
• While Serialization use public static final serialVersionUID to match the exact sender or receiver.
• Advantages
• Serialization make an object serializable it will transfer through network.
• Using FileInputStream and FileOutputStream as well as ObjectInputStream and ObjectOutputStream we make an
object serializable.
• It contains bits or bytes of information.
• No need to verification while accessing the data.
• Data will be in high security mode while transmission.
• Serializable is the marker interface in Java. It doesn’t contains any methods.
• Static and final keywords are not usable in serialization.
• Transient keyword used to hide the data while serialization.
• We can perform operation on the serialized data.
• Disadvantages
• Serialization only used in Java it is not universal.
• We can stored multiple object using collection but it is complex to read and write.
• It is used by only programmer.
• It may fail while transmission the data from different platform.
by Mr.sachin gaikwad
Hibernate 7
• DBMS(Database management System)
• To overcome the problems DBMS has been invented.
• DBMS is the process of storing, managing and
retrieving related data from the DBMS.
• DBMS contains four parts
-Hierarchical Database
-Network Database
-Relational Database
-Object oriented Database
by Mr.sachin gaikwad
Hibernate 7
• Hierarchical Database:
• in hierarchical database data will stored in parent and child format
which lead to duplication of data.
• We can not relate one data to another data object B’z of hierarchical
concept.
• There Is only one bottle neck to access the data it lead to low
performance.
• There are many chances to loss of data B’z subsequent data
depends on the parent only. once parent deleted means all the data
will lost.
• Data may be in structured format but not in semantics and
accessing will be complex.
by Mr.sachin gaikwad
Hibernate 7
• Network Database
• In Network database all data are related to each
other by address.
• It is critical to keep all the addresses in memory.
• While manipulation it lead to the problems.
• We can not delete the data without knowing all
info. About it.
• Address P1,p2,p3,p4……..
person1 person2
by Mr.sachin gaikwad person3 person4
Hibernate 7
• Relational Database
• It is the world wide used database concept.
• Data stored in the form of tables.
• Relationship between data depend on logical addresses.
• Different types of databases supported by Relational database concept(oracle, DB2, mysql,
mysqlServer etc.).
• We can stored related data in it .
• To make data clear and consistence we can use Normalization form.
• It also provide different constraints which helps developer to stored data in persistence manner.
• It uses different model to store the data.
• A table also called as an entity.
• A record also called as a tuple.
• Domain means datatype which allow to store accurate data in it.
• It is easy to persist the data in RDBMS.
• Java provided a package called JDBC API which help you to connect with the data bases.
by Mr.sachin gaikwad
• It is seem to be good while working with
RDBMS but there are no. of drawbacks also
there.
• In RDBMS primary kay means logical address of
the data which is unique to every record in the
database.
• RDBMS use hashing indexing technique to fetch
the data and stored the data
• Physical address and logical address are
different for each record.
by Mr.sachin gaikwad
Hibernate 8
• RDBMS and Other Database Drawbacks
• Java provided a JDBC API which deals with all databases.
• Using JDBC API we can perform operations on the databases but there are
no. of databases are available in the market. Like CSV, xml, RDBMS etc.
• For every database we have to write separated business logic to perform
operation on it.
• If we want the data from database, we will get data in relational format
rather than object format.
• Relational database will retrieve data in rows and columns format.
• CSV, XML, Hierarchical, Network database are structured, semantics, if any
change In database make the change in corresponding code in the
application. So it is very expensive task , we cant modify our code every time.
by Mr.sachin gaikwad
Hibernate 9
• Data stored in databases in different format. Relational database can stored
data in rows and columns.
• CSV stored data in record format.
• XML stored data in tag based format.
• So it is very difficult to get operational data from the different databases.
• If we are using RDBMS to get operational data then we will get data in
relational format, in ResultSet.
• But the problem is that we have to know the internal column names with
datatypes to get the operational data. Using rs.next() we access the data.
• we have to expose the internal format of the database to the programmer.
• In future database will change into other database then again we have to
rewrite the whole business logic code to perform same operations.
• To access data and perform business logic we have to write code in one
class but it may not recommended B,z if database get change means we
have to change whole accuser code and business code.
by Mr.sachin gaikwad
• so to overcome above problem we write code in two different classes,
one is for data accuser and other for business logic.
• physically they are different but logically same, B’z we are sending data
in relational format only.
• If we want to work independently then we have create POJO or domain
or DAO class which separated the data access logic from business logic.
• We want a object which take care about all internal activities and give
only required data.
• If we want object as a input then we have to store data as a object only.
• But there are several problems if we stored in object format. We cant
store object directly into the RDBMS before that we have to serialize the
object and stored into the database using BLOB datatype.
• Again there is problem to persistence the data. It is understandable by
only java programmer.
• Serialized data means bits or bytes format and we can’t perform queries
on the serialized data.
by Mr.sachin gaikwad
• If we want to stored object or access object before
that as programmer manually stored the data into
object and persist into database.
• We hold accessed data into ResultSet but we can’t
send ResultSet object as operational data to the
business logic. B’z once conn get close how it is
possible to access data from the database that is
the drawback of ResultSet.
by Mr.sachin gaikwad
Class OrderProcessing{
Public void dataAccusor(ResultSet ){
//Business logic
}
Class OrderConn{
connection con……//operational data
statement stmt…….
ResultSet rs=stmt.executeQuery(sql);
OrderProcessing op = new OrderProcessing();
op.dataAccusor(rs);
Close.con;
Close.st;
}
– Once connection has been closed how it is possible to send
ResultSet data to the dataAccusor()
by Mr.sachin gaikwad method.
• ResultSet cant stored all data in it. There is some
internal logic which make ResultSet object to access
data from the cursor.
• Cursor which hold logical data in it. It have start
pointer which points the starting address.
by Mr.sachin gaikwad
Hibernate 10
if(conn!=null){
try{
con.close();
}catch(Exceptio e){}
}
• To close the connection we have to write more lines of code in finally block.
by Mr.sachin gaikwad
• 5. JDBC face problem in Transaction management
• While dealing with Transaction management we manually set setAutoCommit(false), B’z by default it is AutoCommit mean
after every transaction it will commit and if there is any problems with query then it will rollback all the previous queries.
• lets see the example
Class A{
boolean isException = true;
try{
loading driver
Connection……
Statement………
Con.setAutoCommit(false);
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
isException = false;
}catch(Exception e )
{
isException = true;
}
Fanally{
if(isException==true)
con.rollback();
if (isException == false)
con.commit();
}
by Mr.sachin gaikwad
• Most of the people going to commit() in try block only but the
problems is while updating there may be chances to get exception, then
we can not handle. using finally we can handle as per above example.
• 6. There are two Transactions
– 1. Local Transaction -----JDBC API
– 2. Global Transaction-----JTA API
Local Transaction handled by JDBC api but Global Transaction handled by JTA api.
We can not handle both using JDBC api, if we want to work with Global
Transaction we have to learn JTA api which is not good for programmers.
7. While changing our database from one database to another database it will
affect all the SQL queries in the application, B’z JDBC doesn’t have such kind of
support.
Oracle queries syntax are different from mysql queries syntaxes so it will affect all
the queries.
8.We can’t maintain VERSION of the data for maintaining version we have to
write individual code.
9. We can’t find and TimeStamp feature in JDBC API.
10. In jdbc if we want same data 100 time then jdbc will execute same query 100
time to get data. We have to write same code
by Mr.sachin gaikwad no. of times.
• Hibernate: Hibernate is the framework which is
provided by JBOSS vendors. Hibernate is the most
used ORM Tool in the market.
• Hibernate is the framework which contains bunch of
classes and classes contains pre-identified code.
• Hibernate provide boiler plat logic to the developers .
Framework make programmer job easy, programmer
need not to write much coding for development.
• As we discussed in previous classes what are the
problems with the JDBC API.
• To overcome all the drawback developer going to use
Hibernate.
by Mr.sachin gaikwad
• Using JDBC we going to face below problem:
– We have to Write more lines of code.
– More code more bugs.
– More maintenance .
– More Budget.
– More developer.
– More time.
– We will not get good quality.
by Mr.sachin gaikwad
Hibernate 13
• Advantages in Hibernate:
• Hibernate has provided predefined classes which avoid all the above problems.
• 1.We will get more quality code from hibernate. B’z of that we have to write
less no. of code.
– Less code less bugs.
– Less maintenance.
– Less Budget.
– Less time
– Less developer.
• 2.Hibernate take of underlying conversion of the data to object and object to
data.
• 3. we need not to provide internal details schema about the database to the
hibernate , we going to create an class and just talk to the hibernate only once .
• Hibernate can get the data in to object format or it can persist the data in
relational format.
by Mr.sachin gaikwad
• 4. Hibernate take care of managing the resources itself we need
not wary about the closing the connection…..
• 5. We need not wary about the SQL query language while
working with the hibernate. B’z hibernate provided HQL to the
programmers, to works with the database.
• Without knowing single query also we can work with hibernate.
• 6. Hibernate use dilate internally B’z as per programmer
requirement he can switch databases. From oracle to mysql,
mysql to myseversql ….etc.
• Hibernate has provided one criteria class with take care of
managing the all HQL queries.
• 7. most powerful advantage is hibernate has a caching memory,
it improve the performance of the application .
• It keep your data in caching and as per request he give the data.
• 8.hibernate has version feature which is take of maintaining the
version of the modified record.
by Mr.sachin gaikwad
• If we want know how much time a data has
modified or inserted in the database so there is
no need to write extra logic, Hibernate has
provided VERSION feature which take care of
maintaining record.
• 9. TimeStamp it is also one of the feature of
hibernate, if we want to know when it is
modified or when it is inserted in the database
then TimeStamp will going to keep the records.
• 10. Hibernate manages the Transactions
internally we need not be wary either it is local
transaction or Global Transaction.
by Mr.sachin gaikwad
Hibernate 14
• As we discussed earlier advantages of hibernate now we will
learn how to deals with the application.
• In application contains multiple classes very class have it own
uses.
• There are three kinds of classes we will use
– POJO(plan old java object)
– Java bean
• Business objects
• Entity objects
--Component class
1. POJO(plan old java object)
POJO class is java class which will compile and execute using
underlying JDK without any third party support called as POJO
class. by Mr.sachin gaikwad
• 2. Java Bean: java bean are java classes which contains
attributes and accuser method.
– Java bean use to hold the data in object format.
i).Business Objects: A java bean class attributes are used for
performing some business operation called as Business
Object. But business object contains only required data which
is used for performing the operation.
ii).Entity Objects: A java bean class attributes are used for
persist a data also in the relational format.
A Entity objects contains all the table attributes for
persistence.
We mostly concentrate on Entity Objects B’z hibernate deals
with persistency.
How to map object to data and data to object, we will learn
all the concept. by Mr.sachin gaikwad
• 3.Component class: It is java class contains attributes
and (methods)business logic to perform the
operations.
• In Spring we mostly deals with component classes
B’z Spring used for Business logic.
• As Hibernate Application one class can depend on
other class easily and having multiple relationship
between classes. So there are two way to deals with
other classes either by inheritance or composition.
• As we know that inheritance means IS-A
relationship, one class is same as other class then
only we can use inheritance.
• For example child is same as parent use inheritance.
by Mr.sachin gaikwad
• Composition: Composition means HAS-A relationship, A class may
contains multiple attributes and method called as composition.
• A Object is the combination of multiple thing in it called as
composition.
• As we know if we want to use one class features into other class we
will use inheritance or composition.(placing the relationship between
two class.)
• Relational Object model:
• Inheritance having multiple problems
– We can’t extends more than one class
– It forces other class to use all features
– There is problem or fragile the classes
– Problems in testability.
• There are two type in inheritance
– Generalization
– Realization
– Specialization
by Mr.sachin gaikwad
• i).Generalization: It is the process of keeping duplicate method in
one class, and extends that class to other subsequent classes.
A
m4()
B C D
M1() m2() m3()
=>As we see class A contains method m4() which is common for all the
concern classes whoever want to use that method extends class A and
access that method.
ii).Realization: It deals like mediator for main class and subsequent classes.
If a method name is same but implementation will be different then we
can use Realization concept.
iii).Specialization: A class want to create a new feature and it is specific to
that particular class called Specialization. A may contains it own methods
which is not sharable to other classes.
Lets see the example for more understanding.
by Mr.sachin gaikwad
Realization example
Class A{
private IB ib;
public static void main(String ars[]){
ib = new B();
ib.m1();
}
}
Interface IB{
Public void m1(){
}
Class B implements IB{
Public void m1(){
//logic
}
Class C implements IB{
Public void m1(){
//logic
}
Here class B and Class C Realizing the method m1() in it.
Whoever want that method just implements IB interface and provide the implementation to
by Mr.sachin gaikwad
the method.
Hibernate 15
• As we discussed in previous class what are the ways to speak with other classes using inheritance.
• Now we will discuss Composition
• Composition: A class contains other class attributes and method called as Composition.
• A object has a other object data called as Composition.
• Composition classified into three ways
– Association
– Aggregation
– Composition
– Dependency
• Association: Two classes are associated with each other. One class can survive without other class called
as Association.
A B
In association parent and child relationship is not there both are equal to carry there work.
-owner :not applicable
-relationship: independent
• Aggregation : Two classes are aggregate with each other. One class can survive without other class But
here classes has there own parents.
A B
ex: students are depends on teacher but without student teacher can survive and without teacher
student can survive.
- owner : parent is there
-relationship: independent by Mr.sachin gaikwad
• Composition: one class can not survive without other class
that is composition.
• Means class A contains class B attribute to survive if B is not
there means class A also not there.
A B
– owner : parent is there
– Relationship: dependent
by Mr.sachin gaikwad
.
by Mr.sachin gaikwad
Hibernate 17
• As we discussed relationship between tables i.e. one-to-one,
one-to-many, many-to-one and many-to-many.
• Giving the relationship between tables mean analyzing the real
world relationship.
• Normal forms are very important while normalizing the data into
tables.
• Normal form: It is the procedure to avoid the anomalies/
redundant data form the table.
• There are
– 1NF
– 2NF
– 3NF
– BYEES CODD RULES
– 5NF by Mr.sachin gaikwad
• 1NF:
– Avoid redundant data from the table.
– The row/tuple should have an atomic name.
– The table should have primary key column.
by Mr.sachin gaikwad
• Hibernate 18,19,20,21 are the property usecase
which is in excel format. Plz refer excel file.
• Hibernate 22 , 23 are How to create the ER
Diagram using MYSQL workbench and discussion
of joins.
• Hiberntae 24 Customer support center usecase.
Which is in excel format .
by Mr.sachin gaikwad
Hibernate 25 and 26 and 27
Mapping information:
class Customer{//entity class
private int customerID;
private String customer_FN;
private String customer_LM
private Date dob;
private String gender;
//setter and getters
}
• Customer is the entity class B’z the class is going to store the exact table related columns as
attributes in it.
• Entity class used to hold the data we can’t write any business logic or database logic. If we
do so its lead to problems in the application , b’z application contains number of classes
and they also want the data. So it again programmer has to write duplicate code for same
job.
• Even if we develop a mapping logic its to tricky to write mapping.
• While retrieving the data from relational model it may come from more then one table . To
handle and write such logic will lead to the maintenance problems and boiler plat logic.
by Mr.sachin gaikwad
• Hibernate provided a mapping configuration file which is avoid all the boiler
plat logic
• We can avoid connection, preparedStatement logic , closing the connection,
try-catch block, so on. It is handled by hibernate mapping file.
• But here is the programmer job to tell what to map with which table and
which class.
• Hibernate provided a structure which is hierarchical format and follow the dtd
which is provided by the hibernate people.
• Programmer has to map class name , table name, type of the data and also
specify the id which is unique to every table i.e. primary key column.
• A project may contains 25 entity classes so programmer has to map all the
entity classes in to the mapping file, but the problem is we can write all entity
classes in one single mapping file but it lead very huge mapping file .
• Every class contains no. of attributes so it is not possible to write all the entity
in the one hibernate mapping file.
• We have to write separate mapping file for each and every class with specific
file name corresponding table name and column names.
• We can give any name to mapping file but recommended to use only
hibernate provided convention i.e <className>.hbm.xml
by Mr.sachin gaikwad .
• Let see the hibernate mapping file
Customer.hbm.xml
================
<hibernate-mapping>
<class name=“customer table=“CUSTOMER”>
<id=“customerid column=“CUSTOMER_ID” type=“int”>
<property name=“customerFN” column=“CUSTOMER_FN”
type=“String”>
<property name=“customerLN” column=“CUSTOMER_LN”
type=“String”>
<property name=“dob” column=“DOB” type=“Date”>
<property name=“gender” column=“GENDER” type=“String”>
</hibernate-mapping>
Just understand the uses of the tags which is given by hibernate dtd.
Class, name, table, id, property, type column these all are tags and tags
properties which is given by hibernate. Using these tags we have to map
the entity class to table. by Mr.sachin gaikwad
Hibernate 28
• As per the previous class having mapping file is not enough we b’z we are
mapping a table with class and columns with attributes but to perform the
any operation we want a connection.
• To get the connection have to pass the database information to the mapping
file. But if there are 10 classes are there who wanted to perform the
database operation. Then we have to write 10 mapping files with same
database connection details.
• Means we are end up with duplicating the database information.
• To avoid such duplication hibernate has provided a configuration file I.e
hibernate.cfg.xml which is common for all the mapping files. If we are
performing operation with one database write one hibernate configuration
file and if we are using multiple databases then we have to write multiple
hibernate configuration file.
• A every configuration file contains a dialect which is very important while
performing the database opertion.
• Dialect is the one of interface which is connect the underlying database and
programmer using database. by Mr.sachin gaikwad
• In hibernate very database contains a separate dialect to perform the
corresponding operation.
• What is the need of dialects in the hibernate?
Ex.
<hibernate-mappings>
<class>….
<propery name=“dob” column=“DOB” type=“date”>
……</class>
</hibernate-mappings>
In the above example a property with date datatype which is may not be same
to every databases. Every database may varied from another database.
• Oracle may contains date , mysql contains timeStamp, MsAccess may
contains different .
• Hibernate using his own provided datatype i.e. date and depends on the
database dialects going to convert the date format in to the java
understandable format.
• Means if there is changes in database there is no effect on mapping file .
• Dialect works many places we will see later.
by Mr.sachin gaikwad
• Let see how we are duplicating the database configuration details if we are using multiple mapping
files.
Customer.hbm.xml
<hibernate-mappings>
<class>…………..</class>
</hibernatemappings>
<hibernate-configuration>
<session-factory>
<property name=connection.driver_className>OracleDriver</property>
<property name=connection.url>jdbc:oracle:thin:@localhost:1521:xe</property>
<property name=connection.username>hbm_user</property>
<property name=connection.password>hbm_pass</property>
<property name=hibernate.dialect>oracle10gDialect</property>
</hibernate-configuration>
employee.hbm.xml
<hibernate-mappings>
<class>…………..</class>
</hibernatemappings>
<hibernate-configuration>
<property name=connection.driver_className>OracleDriver</property>
<property name=connectionurl>jdbc:oracle:thin:@localhost:1521:xe</property>
<property name=connection.username>hbm_user</property>
<property name=connection.password>hbm_pass</property>
<property name=hibernate.dialect>oracle10gDialect</property>
</hibernate-configuration>
To avoid such problem hibernate provided a configuration file we can write database
details in one place. by Mr.sachin gaikwad
• Session:
• Session is a state which contains mapping and configuration
information.
Session is the special class which take care of mapping the hibernate
file info and configuration file info and creating the connection to
perform the DB operation, but it is wrong bz if Session is used for all
these thing then there are many classes are want to perform the
database operation then every time Session going to created and very
new operation hibernate mapping , configuration , connection has to
created means if there are 25 classes wanted to perform the database
operation means 25 time session going to create and 25 time he has
to lead the same file. So it is some what tedious job for session.
If session is doing this job the we end up with duplicating and same
mapping and configuration file.
So don’t create a Session your own ask someone to create the session.
by Mr.sachin gaikwad
• SessionFactory:
• Factories are the classes which going to create the
object of other class. But main advantage is hiding the
complexity of creating the object of another class.
• In hibernate also there is a Factory class called as
SessionFactory which is able to create the session
object.
• In SessionFactory we are giving the mapping file ,
configuration file information, by that sessionFactory
going to create the session object. And all the required
information with the session Factory there is no need to
create multiple sessionFactory. One sessionFactory can
share the same information to the created session
object. by Mr.sachin gaikwad
Hibernate 29
• If a wanted to create the session object must and should mapping information and
configuration information is crucial. We have to pass this information to the SessionFactory to
create the object of session.
• If create a empty sessionFactory object then there is no use, we want the all mapping and
configuration inforamation injected to the sessionFactory object.
• Bz session object required the mapping and configuration information to generate the
corrosponding sql query by help of Dialect.
• So it is the programmer responsibility to pass all mapping and configuration information to
sessionFactory.
• As per the below example we can able see how the happing information build with the
configuration file. There is a reason to build the mapping file with the configuration file.
• One configuration file for one database environment and the all corresponding entities work
with same DBEnv, so always database is same tables are same, columns are same and
attributes also same.
• Rather to configure separate mapping to the sessionFactory better to configure in the
configuration file which is single for every database. Bz there is no need to pass every
mapping file to the sessionFactory every time.
• While creating the object of sessionFactory, sessionFactory will take input as a configuration
file and store as a metadata in SessionFactory registry for future reference.
• Whenever we create the session object there is no need to read the physical mapping and
configuration file rather than we can read it fromgaikwad
by Mr.sachin the SessionFctory Registry .
.
by Mr.sachin gaikwad
How to attach with sessionfactory by example:
Class customerTest{
p s v m ()
{
Configuration cong = new Configuaration();
cong.configure();
SessionFactory sfactory =
cong.buildSessionFactory();
Session session = sfactory.getSessionFactory();
………………….
}
} by Mr.sachin gaikwad
• Dialect:
• In hibernate dialect is the concept is use to translate HQL to
underlying database and underlying database to HQL;
• Hibernate is the database independent framework bz of only dialect.
• Dialect contains all the syntaxes, structure of the databases depends
on that dialect act like that.
• Hibernate provided a type date, so depend up on the underlying
database, hibernate dialect get a particular date type structure and
convert into that type.
• Some time a application may change one database to another
database, it is easy to change the configuration details but it is very
hard to change the underlying queries. Bz very database may have
different query structure at that time we have to change it manual.
• But if you are using hibernate there is no need to change the queries
manually just only change your database details and hiberntae-
dialect . Hibernate – dialects will automatically perform
conversation. by Mr.sachin gaikwad
Internal work of Dialects
OracleDialect
I MySqlDialect
Session Dialect
DB2Dialect
Mapping information
SessionFactory
Database information
by Mr.sachin gaikwad
• Factory Design pattern
Class A{
A(B a){} Class Afactory{
Public static A createA(){
} C c = new C();
Class B { B b = new B(c);
B(C c){} A a = new A (b);
Return a;
} }
Class c{
}
}
Class T1{
A a = Afactory.createA();
}
Class T2{
A a = Afactory.createA();
}
In the above design pattern we are avoid the complexity to create the object
of another class by this design pattern.
by Mr.sachin gaikwad
• Builder Design pattern : It is used to create the object of another class.
It is same like Strategy design pattern but strategy design pattern going
to create empty object, it is depends upon the requirement.
• Here BDP is a special DP which will take the input from the other
classes and inject that information with the particular object and
return the object.
• For example.
• Session object need the information about mapping and configuration,
if we create empty sessionFactory object and depends upon we will
create session object then there is no use. Bz sessionFactory don’t
have mapping and configuration information.
• Here sessionfactory going to take input i.e. mapping and configuration
information and depends on that information sessionFactory object
inject that information in it.
• While creating the object of Session it will give the internal
information to the Session object. Then only session going to inject
with Dialect to perform the operation.
by Mr.sachin gaikwad
• Example
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sFactory = configuration.buildSessionFactory();
Session session = sFactory.getSessionFactory();
……………………..
• If you see the sessionFactory class also taking a
configuration file as a input and injecting with the
session.
• Configuration and mapping information build with the
sessionfactory.
• While createing session object we will get all the
required information from the sessionFactory object.
by Mr.sachin gaikwad
Hibernate 30
• What is sessionFactory?
• What is session?
• Why we have to use sessionFactory?
• What is configuration file? Why we have to use configuration
file?
• What is mapping file and why we have to use mapping file?
• How to write the configuration and mapping files in to
hibernate?
• What is dialect? What is the use to dialect in hibernate?
by Mr.sachin gaikwad
Class Customer{ => entity class
private int customerId;
private String firstName;
private String lastName;
private String dob;
private String gender;
//setter and getters
}
Customer.hbm.xml
================
• <?xml version="1.0"?>
• <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
• "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
• <!-- Generated Sep 29, 2015 9:59:47 AM by Hibernate Tools 3.4.0.CR1 -->
• <hibernate-mapping>
• <class name="com.fh.entities.Customer" table="CUSTOMER">
• <id name="customerId" column="CUSTOMER_ID" />
• <property name="firstName" column="FIRST_NAME"></property>
• <property name="lastName" column="LAST_NAME"></property>
• <property name="dob" column="DOB" type="date"></property>
• <property name="gender" column="GENDER"></property>
• </class>
• </hibernate-mapping> by Mr.sachin gaikwad
Hibernate.cfg.xml === This is the common configuration file
================
• <?xml version="1.0" encoding="UTF-8"?>
• <!DOCTYPE hibernate-configuration PUBLIC
• "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
• "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
• <hibernate-configuration>
• <session-factory>
• <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
• <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
• <property name="connection.username">system</property>
• <property name="connection.password">system</property>
• <property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
• <mapping resource="com/fh/entities/Customer.hbm.xml"/>
• </session-factory>
• </hibernate-configuration>
To compile and run the application write test class and configure the configuration file and
get the sessionFactory to create Sessionby object.
Mr.sachin gaikwad
• public class FHTest {
• public static void main(String[] args) {
by Mr.sachin gaikwad
• Why DAO?
There are several reasons if we write our persistency related logic
in business logic which impact our business logic, there is change in
table or database then we have to rewrite all the business logic .
If there are 10 servlets available in the project so we have to write
persistency logic in each every servlet. In every servlet we have to
create connection and close the servlet.
Again there are so many problems ……..
• DAO(Data Access Object)
• As per the above discussion we have to use DAO in our application.
To make our application loosely coupled from the persistency logic.
• DAO are the classes which contains only persistency related logic,
they going to interact to the database.
• DAO represents one layer which reflects the tables in the
database. we can easily interact with the DAO.
by Mr.sachin gaikwad
• While developing an application we have to follow
the separation of concern principle, which divide
our application in three layer.
– Presentation layer
– Business layer
– Persistency layer
by Mr.sachin gaikwad
Hibernate 33
by Mr.sachin gaikwad
• 2). Hibernate.properties
• By help of hibernate.properties we can configure the configuration details to the
hibernate.
• When to use hibernate.properties approach in the project. When there is piece of code
(POC) development then we can use hibernate.properties file.
• In this approach we will get any dtd and pre-validation feature.
• Hibernate.properties should be the name to the file.
• It should be placed under classpath location only.
• While configuration there is no need to configure the hibernate.properties file.
• Bz hibernate automatically find and fetch the hibernate.properties file into classpath
location and load it.
• If hibernate.properties file is not available even though hibernate create empty
configuration object which never tell you properties file has been loaded or not.
• We can not add mapping information into the hibernate.properties file bz we can’t store
with same key multiple value.
• So we have to add externally mapping file to the configuration object .
• There is a method in configuration class i.e. addResource(“mapping file
path”);//addClass(“classname.class”);
• If there is small application or for testing purpose we can use hibernate.properties
approach .
• Properties file contains key and value by Mr.sachin gaikwad
• For example :
hibernate.connection.driver_class=oracle.jdbc.driver.
OracleDriver
hibernate.connection.url=jdbc:oracle:thin:@localhost:
1521:xe
hibernate.connection.username=hibernate
hibernate.connection.password=hibernate
hibernate.dialect=org.hibernate.dialect.Oracle10gDial
ect
by Mr.sachin gaikwad
Hibernate 36
• 3).Programmatic approach:
• This approach is rarely used while development of application.
• By example we can understand this concept.
If there is old legacy application which is developed in old language and my requirement is
to add the new components in the legacy application. But now I want to use hibernate
instead of old technology.
But in that legacy application there is a property file containing some sort of data. For
example
Db.properties
============
con.driverClass=oracle.jdbc.driver.OracleDriver
con.url=jdbc:oracle:thin:@localhost:1521:xe
con.username=hibernate
con.password=hibernate
by Mr.sachin gaikwad
Hibernate 37,38
• Get Vs Load:
• Session class contains number of methods and every method used for specific
purpose.
• Get and Load both are session class method used for retrieving the data from the
database.
• Get and Load method going to return data in the object format.
• There are number of differences available in get and load methods.
• Get() : get() is the eager initializer method.
• Syntax : get(class, primary key id);
• Get() is the special method which is used for retrieving the data from the database, get
going to take two parameter as input i.e. class name and a primary key id.
• Internally hibernate going to take that class name and going to find the canonical
name of the class, after that hibernate matches that class name with the mapping file
which is available into the classpath.
• according to the mapping information it will go to the table and fetch the one record
and return to the session object, session object going to return the object to the
corresponding class.
by Mr.sachin gaikwad
• But there are several disadvantages available.
• 1) get() method is eager initializer mean once it get the call it will go to the
underlying database and fetch all the records, rather than particular records.
• If there is a association between two classes and if we call the get method, it
will load current class data as well as associative class data also, even we are
not certainty sure we will use that data or not.
• 2).It will forcibly consume more amount of memory in the JVM.
• 3).it will decrease the performance.
• 4).it will consume the more bandwidth while transformation.
• Get() method will return the actual class object to the session.
• For example:
Customer customer =(Customer) session.get(Customer.class,101);
• Here session class going to return the actual class object. By type casting we
are able to use the Customer class object.
System.out.println(customer);
• There are sort of procedure available how the session class get() method
mapping the Customer.hbm.xml and there corresponding attributes with
columns.
by Mr.sachin gaikwad
• Load(): it is lazy initializer.
• Load() method also present in the session class only, both get() and load()
method used for retrieving the data from the database.
• Why load method is called as lazy initializer?
• Syntax: load(class, primary key id);
• Both get() and load() method having same parameter but load() method will
not go directly to the database.
• Load() method will take the input and hibernate will return the object to the
load method which contains prepopulated id value.
• But internally hibernate will call the javaassists package, which is executed
while bytecode optimization time. Hibernate will take help of javaassists and
generate one proxy class which is same as original class.
• Proxy class contains all the original class properties.
• When programmer call the session class load () method it will return proxy
class object which is look like same as original one with prepopulated id.
• Actually load () method fetch the data on demand, mean when we call a
particular method , then load() method going to fetch the data from the
database, but fetching the data will going to happen into the proxy class and
by Mr.sachin gaikwad
we are calling proxy class methods only.
• For exampele
Event event = (event)session.load(Event.class,10);
In the above statement a load() returning the proxy class object
which contains prepopulated data i.e. id. After getting event object
we are calling the methods
For example :
event.getId();
event.getEventName();
Here we called the methods but these method belongs to the
Event$Proxy class.
• After getting call Event$Proxy class going to execute
Some special method these method will going to fetch the data from
database and going to set the value to the Event$Proxy class method.
For example:
by Mr.sachin gaikwad
Class Event$Proxy extends Event{
private object id;
private Event event;
public Event$Proxy( object id){
this.id= id;
event = new Event();
}
//setter and getter
//business logic which is going to connect to the mapping file and validating the
data has been populated or not .
//special methods which contains logic related to separating the association
between the classes.
}
• Load() method going to fetch only current class records even association presents
into the classes.
• In performance load() method is good.
• It will not consume more memory into the JVM.
• Depends on the demand it will fetch the data.
• It will fetch one record at a time. by Mr.sachin gaikwad
Hibernate 39,40
• Internally how the proxy going to work lets see the example.
• There is InvocationHandler interface which is present under
java.lang.reflect.InvocationHandler.
• Which contains only one method i.e.
public object invoke(object obj,Method m1,Object[] args)
The above method used by the proxy to invoke the proxy method.
There are three parameters are available which going to take as following
1. Object of the current classLoader
2. object of the interface (for all method )
3. It take all arguments .
Example:
while creating the proxy object we going to pass these parameters to the InvocationHandler.
Account proxy =
Proxy.newProxyInstance(Account.class.getClassLoader(),account.class.getClass.getInterface(),n
ew Invocationhandler (new object));
Lets see the example:
by Mr.sachin gaikwad
.
by Mr.sachin gaikwad
• Some internal details about how the proxy going generate
Class session{
public Object Load(Class classType, Object id) {
return newProxyInstance(classType.class, new Class[]
{classType.class},new InvocationHanlder(new Event(id));
}
The above code is internal code….for understanding purpose.
Proxy used by pre-validation, to avoid boiler plat logic, etc.
So better understanding just refer the examples which are in the
eclipes IDE.
• if data is not available into the table then get() method will return
null . But load() method throws an exception.
• In table data is there but some column data are not available and
we are trying to fetch the data then we will get the runtime
exception. by Mr.sachin gaikwad
• Rule while writing the entities
– Entity must contains default constructor
– Entity contains only accusers method it should not contains
business logic or other logic.
– Entity should not be final.
– Entity should not contains parameterized constructor, if it is
there then we can not perform save operation.
– Entity should not contains private constructor, hibernate can
create the object but we can not create the object.
– Entity contains equals() and hashCode() method.
– Entity should be implemented by Serializable interface. Even
we are not implements, we can write the entity no problem.
– Even if we declared all attributes as private no problems we
can easily access and set the values to these attributes form
outside class , b’z of setter and
by Mr.sachin getter (accusers method).
gaikwad
Hibernate 41
• We have to follow certain rules while writing the entities classes. If our entities are final then hibernate will
not create proxy for the entities, rather it will return original class object only.
• Even our entity class final we can create the proxy, but we have to follow certain procedure.
• Create one interface and your entity should be implements to the interface and override all the methods.
• While calling session.load(.,.) create the interface reference and typecast into interface variable only.
Interface Ilaptop{
//methods declaration
}
Final Class Laptop{
//override all the methods
}
Class LaptopDao{
//create sessionFactory
//create session
Ilaptop laptop;
public void getData(int id){
laptop = (Ilaptop)session.load(Laptop.class,id);
syso(laptop.getName());
}
}
by Mr.sachin gaikwad
• After creating Laptopdao class make sure while
creating your mapping file write one extra tag which
help hibernate to create the proxy of your class.
• Ex:
<class name=“com.gl.Laptop” table =“LAPTOP”
proxy=“com.gl.Ilaptop”>
………..
</class>
For more understanding just see GetAndLaod example
in eclipse.
by Mr.sachin gaikwad
Hibernate 42
• Hibernate Tools
– Graphical user interface
• Hibernate Configuration Tools
• Hibernate Mapping Tools
• hibernate console Tools / Query Editor
• Reverse Engineering Tools
– Command-line utilities
• Schema Export
• Schema Visibility
• Schema update
• Hibernate configuration Tools:
– We are manually writing the configuration information information into the cfg.xml file , But hibernate has
provided the hibernate configuration tool, so we can write configuration file using graphical user interface.
• Hibernate Mapping tools :
– Even we can create mapping file using graphical user interface but it will assume that your entity
attributes are same as the table column names.
• Hibernate console file/tools:
– Hibernate has provided the HQL console to query the data from the table but we have to query data in
HQL format.
• Reverse Engineering Tools
– It’s a tool which help more efficiently to the programmers. If you given table to this tool it will generate
by Mr.sachin gaikwad
mapping file as well as entities class related to the table column attributes.
Hibernate 43
by Mr.sachin gaikwad
Hibernate 44
by Mr.sachin gaikwad
Hibernate 45
by Mr.sachin gaikwad
Hibernate 46
by Mr.sachin gaikwad
Hibernate 47
• Because of that we can not easily switch from one frameworks to another frameworks.
• But now a days every one has the support for JPA annotation and JPA annotation is the standard acorss the platform. we no need
to change the mapping or configuation when we are using JPA Annotation.
• while working with the hibernate annotation we can mix JPA annotation, also we can mix annotation and configuaration
information. both we can use.
• without writing configuaration and mapping information we can work with the hibernate, but we have to use the programmatic
approach to pass the cfg and mapping information to hibernate.
•
• Both way we can provide the mapping information to the hibernate,
• 1). By annotation
• 2). By mapping file(hbm.xml)
• if we specified both into the configuration then hibernate by default take hbm.xml only.
• by Mr.sachin
To make hibernate to take annotation entity class the specify gaikwad into the configuration file.
the precedence
• Let see the example
(1)
@Entity
@Table(name=“EVENT”)
Class Event{
@Id
private int eventId;
@Column(name=“DESCR”)
private String description;
……
//setter and getters
}
(2)
@Entity
@Table(name=“EVENT”)
Class Event{
private int eventId;
private String description;
……
@Id
public int getEventID(){}
public int setEventID(){}
@Column(name=“DESCR”)
public String getDescription(){}
public void setDescription(){}
}
by Mr.sachin gaikwad
Hibernate 48 & 49
•
• First level Cache
• =================
• Hibernate support three level of cache,
• 1) First level cache
• 2) Second level cache
• 3) Query level cache
• Q. what are the drawbacks, if we develop our application with our cache?
• ==> There are several problems we have to face if we wont follow the cache concept
• 1) Performance issue
• 2) Resource management issue
• 3) network bandwidth problems
4) Database Scalability problems
• Ex:==>
• If we want to develop an e-commerce site, so we have to provide the product information
to the customers, if customer choose a product and he requested our servlet then servlet
container going to execute our servlet, but problems are if multiple users going to request
to the servlet for the same data then it is end up with accessing the data from the
by Mr.sachin gaikwad
database.
.
by Mr.sachin gaikwad
• In the above application user going to find the product , after
entering the productName or productCode user going to click on
search button, and the request received by the servlet Container
and container going call appropriate servlet.
• and call the service method of the SearchProductServlet , service
method read the jsp page data by request object using
getParameter() method . Once the data available with the service
method it will connect to the database and perform the query and
retrieve the data to the servlet.
• But there are lacs of user want the same data then each and every
request end up with executing the same the query one database.
• Every time same query going to execute here creating the
database connection is expensive job, and we are sacking the
performance of the application.
• Because of executing same query CPU resources not used
properly even we are killing the scalability of the application.
by Mr.sachin gaikwad
• Because of repetitive execution of same query we are wasting
bandwidth.
• To overcome we have to use the cache concept into the
application.
• Cache will improve the performance of your application.
• According to the above example if we use cache concept to
get the product from the database then we easily improve
the performance to the application.
• Instead of going every time to the database, go once and get
the data and store into the attribute, for feature reference.
• If other request will request for same product then easily we
can utilizes the previous data.
• If the coming request is new the it will check and if it is not
available it will get the data from the database and store into
the cache and sent to target page.
by Mr.sachin gaikwad
• Cache General example
by Mr.sachin gaikwad
Hibernate 50
• In the above example we implemented the simple cache
which work with one product item or one similar type of data
only, we can’t store heterogeneous data into the HashMap.
• For example a project contains multiple tables and if we want
to store data into HashMap it may overlap.
• Ex:
– HashMap(1,product1)
– HashMap(2,product2)
– HashMap(1,customer1)
– HashMap(2,customer2)
– HashMap(1,seller1)
Here in HashMap data overlapping if user want a particular data then
it is difficult to get the corresponding data.
by Mr.sachin gaikwad
• There is one more alternate we can store data into has
map but if kill the performance of the application. And to
get the data haspMap has to go line by line to search the
data.
– Ex:
• Product.class+1,productObject1
• Product.class+2,productObject2
• Customer.class+1, CustomerObject1
• Customer.class+2,CustomerObject2
• Seller.class+1,SellerObject1
– Here to get the seller object HashMap has to check from first
line to the last line to get the data.
– It is linear search so it will kill the performance of the
application.
• So to make over cache more intelligence we have to
rewrite the cache with new logic.
by Mr.sachin gaikwad
Above example describe the generalized view of the hibernate
by Mr.sachin gaikwad
Hibernate 51
• By the generalized example we can optimize the solution over the
roundtrip to the database. But the problems is if more then one
class want to the same data then every class has to write
checking logic in it.
• It has to check data is available into the cache or not and if it is
not then go to the database and fetch the data and stored into
the cache.
• When to use the cache
– If data is same around the application and it will change every rarely
then go and implements the cache.
– But if data is changing frequently we should not use cache here .
– But within a second 200 time same data required and after one second
it will change even though we have to implements the Cache. B’z we
cant allow the application to go and get the data from the DB for 200
time within second. so it is better to implements the cache.
– Again there are several placesby Mr.sachin gaikwad
we can use the cache concept.
• Problems with the cache is we cannot maintains two copy of data to work with cache.
• It must be one an the same only then only use going to get correct data.
• If we directly update the data into the DB it will not reflect to the cache b’z both are
two different copies of the data.it will change into the cache.
• if user access the data then a class going to check data into the cache and user will get
the steal/old data. which is wrong.
• In application perspective both cache data and DB data must be same, if user want to
modify the data then user has to modify through the application and as programmer
has to write the intelligence logic to make sure both the copies of the data will going
modify. i.e. cache data and DB data.
• Actually for every operation we need identifier without identifier we can not deal with
cache to database.
– Fetching the data (need identifier)
– Update the data(need identifier)
– Delete the data (need identifier)
– Save the data(need identifier)
• For each operation we need identifier means identifier is the common for cache as
well as DB.
• So we need some one who take the identifier and perform the operation.
• But the operation first reflected into the cache then database because user will not get
wrong or steal data. by Mr.sachin gaikwad
• We do such kind of operation we need the
persistanceManager
by Mr.sachin gaikwad
• In the above program we can see persistenceManager contains
cache object and DB data.
• PM handle the modification of the data will be reflected into two
places i.e. cache and DB.
• A get() method in PM will take two parameter entity name and
second the identifier.
• It will first check data is available into the cache with
corresponding identifier or not, if it is available it will return the
same data.
• If data is not available then it will go to the DB and query the
data using identifier and stored into the cache and return the
entity object along with data.
• Not only get() even it will manages the update, save, delete
operation.
• By this we can avoid all the problems while implementing the
cache which we discussed earlier.
by Mr.sachin gaikwad
• How the hibernate session is working?
– Hibernate session has its own session manager to manage the cache.
– First level cache or session level cache or object level cache these three represent the same cache
concept.
– When we use session.get(class,id); automatically hibernate open the first level cache and will manage the
operations.
– If subsequently if we call the session.get(class,id);
– Session will check into session cache and perform the operation.
Ex:
Product p1= (Product)session.get(Product.class,1);
we will get the product data, and session perform internal operation like enabling the cache. Fetching the
data, storing in to the cache so on.
If next time we will call the same product then will get the same data from the cache.
Ex:
p1.setProductName(“LCD Color TV”);
session.update(p1);
when we modified the data of the product then changes reflected into the session cache only, it will not
modified into the database .but next time when we call the session.get(product.class,1); we will get
modified data.
It means modification done into the cache but not into the DB. Actually it will modified into the database
after calling the commit() method.
Ex: session.getTransaction().commit();
by Mr.sachin gaikwad
after calling above method change will going to reflected into the database.
• What is the reason it will not update each and every time?
– if a user updating the data for every one second with in the
same product class then for every second hibernate has to
connect to the DB and update the data update and cache and
close the connection.
– It is very costly to do such kind of operation.
– B’z of that hibernate session cache will not update the data very
time it will update will we session.getTransaction().commit().
– Internally commit() method going to call the flush() method.
– Flush() : it will store all updated data into the database.
Product p3 = (Product)session1.get(product.class,1);
here we will not get updated data b’z one session object is different then other
session object. To get the upgraded data.
session.evict(p1);
Product p3 = (Product)session1.get(product.class,1);
now we’ll get ungraded data.
by Mr.sachin gaikwad
• Clear():
if we want to clear all the session cache then we can use
clear()tmethod as part of the application.
– Session.clear();
• Flush(): it is used to stored updated data into the
DB. This method called by commit() method
internally .
• Is session object is singletone or not?why?
– No, session cache or first level cache not an singletone
class, b’z many time in application we can not relay on
one single object we need multiple session object.
– Application has multiple classes and multiple classes
want to interact with session cache , then it is necessity
to allow multiple object creation.
by Mr.sachin gaikwad
Hibernate 53
• Flush() Vs commit():
• Flush():
– If we tried to update the data , it will updated into the cache but not into the database.
– If there are 10 update methods are there then in general in jdbc 10 update query has
been generated, but when we use hibernate Flush() method it will generate only one
update query but it will not updated into the database. To update into the database we
have to call the commit() method.
– Flush() method will cross check the database constraint when we are applied flush()
method.
– It will check database table constraint and hibernate inserted data if both are valid then
only flush() method will generate the query, neither is will throw the exception.
– Flush() method used for inserting , updating, deleting the records into the cache. As
well as database once the validation happen.
• Commit():
– In general we know the usage of the commit(), in hibernate also until we call the
session.getTransaction().commit(); the updated data will not reflected into the
database.
– Once we call commit() method it will update the data into database but it will not
reflect into the active session cache.
by Mr.sachin gaikwad
Ex: product p1 = (product)session1.get(product.class,1);
p1.setProductName(“LCD COLOR TV”);
session1.update(p1);
session.getTransaction().commit();
product p2 = (product)session2.get(product.class,1);
by Mr.sachin gaikwad
Hibernate 54
• ID Generator:
– Before we discussing about ID Generator, we should have
know why ID generator came into feature.
– In olden days people used to store the data into the DB, but
they unable to distinguish the primary column into the DB.
– They used to use natural key as a primary key into the DB.
But when there is change into the natural key column they
has to rewrite whole table.
– They unable to hold the relationship between tables.
– So they are failing while storing the data, even they relay on
composite key column they can not distinguish the primary
column.
– Because of the above reasons people thinks about primary
key column, which is unique and easily hold the ralationship.
by Mr.sachin gaikwad
• It is common requirement every has to use the primary key
into the database, but when we relay on relational model
then we have to write complex logic to generating the
primary keys.
• In oracle we use to use sequences to generated the
primary key, but writing the sequence it is not complicated
but when we migrate from oracle to mysql or any other DB,
they does not contains sequence feature then we have to
rewrite the logic.
• It is common requirement for every DB to have a Identity
column.
• Id is the more important into the DB table, b’z of id we can
easily hold the relationship with other DB tables.
• So hibernate has provided multiple key generator, to
overcome the problems byofMr.sachin
above gaikwad
reasons.
• Hibernate provided KEY Generator
– Assigned
– Identity
– Sequence
– Holi
– Holi_seq
– Select
– native
– Increment
– guid
– Uuid
– Foreign
by Mr.sachin gaikwad
• ID generator / key generator / surrogate key /
identity generator these are name for hibernate ID
generators.
• Hibernate is the ORM Tech. at each and every place
he has provide the flexibility to avoid the boiler plat
logic.
• Here also hibernate has provided id generator to
avoid the duplicate the logic and it will make our
application portable from on DB to another DB.
• But when we deal with RDBMS and we can not
migrate from oracle to Mysql, b’z both DB has there
own syntaxes.
by Mr.sachin gaikwad
Hibernate 55
• Every ID generator has there own implemented classes which is internally
called by session object.
• Assigned, identity, native, sequence are the short name of the id
generators.
• Even we can create our own id generator by overriding the internal
class/interfaces.
• We can call custom id generator.
• Every id generator having there own strategy to generate a primary key
value.
• Every id generator different from each other and there implementations
also.
• actually session never generate the primary key for table, it will take the
metadata and pass to the corresponding class to generate the primary
key value.
• A class going to generate the primary key value and return to the session
object and session will add to the cache.
by Mr.sachin gaikwad
• 1)assigned:
• How does it work?
– Hibernate will not generate any surrogate key for assigned ID generator,
programmer has to provide the primary key value to the hibernate.
– Session object will take the provided class name it will go to the
sessionFactory , it will get the metadata for corresponding class from
mapping information, it look to id generator, if it is ASSIGNED Id
generator then it will take programmer provided value and computed
into the cache.
• Data- type : int , short , long
• Benefit :
– It is database independent
• Syntax:
<ID name=“att_name” column=“col_name”>
<generator class=“assigned”/>
by Mr.sachin gaikwad
2)Increment :
• How does it work? :=> MAX(ID)+1;
• It will going to fire query on the DB table
– Ex: select max(AGENT_ID) from AGENT;
– Session object will take the provided class name, it will go to the sessionFactory and it will get
the metadata for corresponding class from mapping information, it look to id generator, if it is
INCREMENT Id generator then it will generate one query to get the max value from the
database and it will add +1.
– And it will give to the session object, session object going to perform rest of the operation.
• Data-type : int , short , long.
• Benefits:
– It is database independent
– It will work with any database.
• Drawback:
– It will not generate unique primary key in multi-threaded environment or cluster environment.
– If two or more classes wanted to persist the data at a time then it may chance to generate
duplicate primary key.
• Syntax:
<ID name=“att_name” column=“col_name”>
<generator class=“increment”/> by Mr.sachin gaikwad
• 3) Identity:
• How does it work?
– Identity one of the id generator which relay on the database auto-generated elements.
– Here hibernate will not do any thing, session object will play the role for getting the primary key value from the
corresponding database.
– Session will get the metadata from the mapping file and it will go to the specific DB and will run the auto-
generate column which is available into DB.
– Here programmer and hibernate will not have any work everything is takes care by session, and it will
automatically generate the primary key values.
• Data-type: int , short , long.
• Benefits:
– It will work with auto- sequence database.
• Drawback:
– It only work with auto-generated value databases.
• Ex: mysql, ms-sql server.
• What is the difference between assigned and identity?b’z both the places hibernate will not do
anything ?
– Assigned : here programmer is the responsible for providing the primary key value to the session to persist into
the database.
– Identity: hare identity specific class will automatically execute the corresponding database sequence and it will
generate the primary key value.
– Both the places hibernate will not do anything.
• Syntax:
<ID name=“att_name” column=“col_name”>
<generator class=“identity”/> by Mr.sachin gaikwad
• 4) sequence:
• How does it work?
– Sequence id generator relay on the specific DBs which having the sequences concept.
– Session will get the metadata from the mapping file and it will go to the specific DB and will run the
sequence which is available into DB.
• Data-types: int , short, long.
• Benefits:
• Drawback:
– It will work with only those DBS which are having the concept called sequence.
– If we are using sequence and if we are not specifying any name to the sequence the hibernate going
to give the default name to the sequence.
– But if there are more then one entities are there and we haven’t specified sequence name then it lead
to generate incorrect primary key value .
• Syntax:
– <generator class=“sequence”>
<param name=“sequence” > agent_ID</param>
</generator>
– <generator class=“sequence”>
<param name=“sequence” > property_ID</param>
</generator>
• Ex: create sequence hibernate_sequence
• Ex: select hibernate_sequence.nextval
by Mr.sachin gaikwad
from dual
Hibernate 56
• 5) Hilo :
– How does it works?
• Hilo work on one of the formula
– (Max_lo * next_hi + next_hi)
– Hilo is the one to the mathematical algorithm which work with batch
of records.
– Hibernate going to generate one default table with the name
(hibernate_unique_key) with one column and column name is
next_hi.
– If we don’t want to work with the default generated DB table or
column then we can configure our own table name and column.
– Hilo works with the batch of records.
– Already other ID generators are there then what is the need for going
to word Hilo id generators
• Actually every id generator have there own drawbacks while generating the id
of the table.
by Mr.sachin gaikwad
• They have to do maximum around trips while generating the primary value.
– Hilo will not make maximum around trips with the database
for generating the primary key value.
– Actually session object will take the class name with that it
will go to the sessionFactory and get the metadata for
corresponding class with table and it will check which id
generator has been used for generating the primary key.
– If it is hilo it will check any table and column has been
configured or not along with max_lo value.
– If it is already configured it will use existing table and
column to generate the primary key value, if table and
column not configured then hibernate will generate its own
table with the name hibernate_unique_key and the column
name next_hi.
– Max_lo is the value which is talk about how much records
inserted at one short. E.g. if we provide 10 means it will
insert 10 records. by Mr.sachin gaikwad
• Internally hilo work as fallows
• Ex <generator class=“hilo”>
<param name=“max_lo”>10</param>
[optional]
<param name=“table”>tbl_name</param>
<param name=“column”>col_name</param>
</generator>
– Now hibernate will generator one table with name hibernate_unique_key with the
column name next_hi and it will assign the value as 1 .( next_hi = 1).
– We already configured max_lo with the value 10.
– Hibernate will compute the formula as below
(max_lo *next_hi * next_hi)
10 * 1 * 1 = 11
– While taking the next_hi from the DB it will increase the next_hi with 1, means next time
if other session object want to insert the batch of record, then it will get 10 * 2 * 2 = 22
and they will insert the records.
– No one session object will get duplicate next_hi value.
– It will start inserting the records with id 11, 12 , 13…20. means it will not around trips on
the DB it will compute first time and for next 10 records it will get it from hibernate only.
– After inserted 10 records it will go to the DB and get the current next_hi and increments
by 1. and perform the tansaction. by Mr.sachin gaikwad
• Data-types : int , short , long.
• Benefits:
– It will work with any application environment.
– And it will not around trips to the DB maximum time.
– It will use internally locking system while working, b’z in
jee application more possibilities are there more then
one person can insert the records into the DB, making
sure every no one object will get the same hilo value.
• Drawbacks:
– It will work with JEE apllication only.
by Mr.sachin gaikwad
• 6) Seq_hilo:
– Seq_hilo same as the hilo id generator, hilo id generator relay on the formula
but seq_hilo id generator work with the sequence generator.
– While inserting the data it will generate one of the sequence in to the database.
– It is also used to insert the batch of records, only the difference is, we will get
primary value by executing the seq_hilo.
– It will also perform same operation like hilo only.
– How does it works?
• Same as hilo but it will get the value from the sequence.
– Benefits:
– It will work with any application environment.
– Data-types: int , short , long.
– Drawback:
• It will work with oracle database only.
• It will support all the application environment.
Syntax:
<generator class=“seq_hilo”>
<param name=“max_lo”>10</param>
<param name=“sequence”>agent_id_seq</param>
</generator> by Mr.sachin gaikwad
• 7)GUID: ( global uid):
– How does it works?
• Actually session object will take the class name with that it will go to the
sessionFactory and get the metadata for corresponding class with table and it
will check which id generator has been used for generating the primary key.
• Actually GUID work with JEE environment, and it will uses one algorithm which
going to generator primary key value.
• GUID will take number of parameter to generator the primary key value. It will
generator the value in String format with max length is 256 character.
• It will unique across the universe.
Ex: select sys_guid() from dual;
– Benefits:
• We will get unique id in the universe.
– Data-types : string
– Drawbacks:
• It will work with GUID generator databases only.
• It will consume more memory space for storing the primary key value.
• It is very hard to remember and query the data.
• It is used in special environment only.gaikwad
by Mr.sachin
Hibernate 57
• UUID
• Foreign
• Select
– Legacy based application
– Internally trigger has been used
–
by Mr.sachin gaikwad
Hibernate 62
by Mr.sachin gaikwad
Hibernate 63
• Working with entity lifecycle states:
– In programming world every object has state while transition from one place to
another place.
– In normal java object lifecycle there are infinite state are available for one object, but
coming to the hibernate there are finite set of states are available.
– Actually hibernate object deals with persistency related context so it has finite set of
states.
– There are four states where hibernate object will go through to perform the
persistency.
• Transient state
• Persistent state
• Detached state
• Removed state
• Transient state :
– When object has been created then that state called as transient state.
– If we perform any operation also it will not affect into the database or session cache.
– To perform operation on the database or first level cache then we have to change
the state of the object. By using sort of method which are provided by the hibernate.
by Mr.sachin gaikwad
• Persistent state:
– In this state object has some data and it is attached with the session or
database to perform some operation.
– Once object entered into the persistent state then there is no need to
use additional method to perform the persistency.
– Object itself is responsible for persisting the data.
• Ex:
Address addr = (Address)session.get(Address.class,1);
Addr.setAddressLine1(“solapur”);
Session.getTransaction().commit();
– There are different method provided by hibernate to get object into
persistency state.
• Save
• Persist
• saveOrUpdate
– Get and load are two method which directly make the object
persistent state.
– A object deals with session cache or database then that object should
be in persistency state only.by Mr.sachin gaikwad
• Detached state:
– Once object has been removed the relationship with session
or database then that state called as detached state.
– There are several method which can easily detach the object
from persistency state to detached state.
• Close
• Evict
• Clear
– These three method make object to detached from persistent
state to detached state.
B C D
M1() m2() m3()
=>As we see class A contains method m4() which is common for all the concern classes
by Mr.sachin
whoever want to use that method extends classgaikwad
A and access that method.
ii).Realization: It deals like mediator for main class and
subsequent classes. If a method name is same but
implementation will be different then we can use
Realization concept.
iii).Specialization: A class want to create a new feature and
it is specific to that particular class called Specialization. A
may contains it own methods which is not sharable to
other classes.
by Mr.sachin gaikwad
Relationship model
• As we discussed in previous class what are the ways to speak with other classes using inheritance.
• Now we will discuss Composition
• Composition: A class contains other class attributes and method called as Composition.
• A object has a other object data called as Composition.
• Composition classified into three ways
– Association
– Aggregation
– Composition
– Dependency
• Association: Two classes are associated with each other. One class can survive without other class called
as Association.
A B
In association parent and child relationship is not there both are equal to carry there work.
-owner :not applicable
-relationship: independent
• Aggregation : Two classes are aggregate with each other. One class can survive without other class But
here classes has there own parents.
A B
ex: students are depends on teacher but without student teacher can survive and without teacher
student can survive.
- owner : parent is there
-relationship: independent by Mr.sachin gaikwad
• Composition: one class can not survive without other class
that is composition.
• Means class A contains class B attribute to survive if B is not
there means class A also not there.
A B
– owner : parent is there
– Relationship: dependent
• Granularity:
– Granularity is the problem which come while we are accessing the
data from the underlying database.
– If data is stored in table per class hierarchy then it is very hard to find
the appropriate data from the corresponding table. B’z a table
contains multiple class data so we unable to find appropriate data
from the table .
• Association :
by Mr.sachin gaikwad
• 1)Inheritance Mapping Model
– IMM going to store data into database using following
four ways
• Table per class hierarchy
• Table per concrete class
• Table per subclass
• Implicit polymorphism
by Mr.sachin gaikwad
by Mr.sachin gaikwad
Hibernate 66
by Mr.sachin gaikwad
Hibenate 67
• 2) Table per concrete class:
– It is one of the technique were we can store data into database,
actually tables having the parent child relationship.
– But we can store every entity as separate table into the database.
Lets see the diagram for better understanding.
– How the payment is inherited to other class and what are the
column are available.
– Table per concrete class pays polymorphic behavior which is take
care by hibernate only.
– Polymorphic behavior means if we requested child class object
using parent class reference then hibernate automatically convert
child class ref to parent class and it will return the output.
– Here base class can store any child reference bz of that there no
need to warry while accessing the data by parent reference we
can access any child data.by Mr.sachin gaikwad
• But in table per concrete class technique we have to
configure addition configuration to work with table per
concrete class.
• While mapping our classes with mapping file we have to
configure who is the base class and id but while configuring
child classes we have to be little conscious.bz child table
also have there own table per perform the operation.
• To make sure by base reference to get the data we have to
make our child class as subclasses.
• But while configuring subclasses we have to make they are
union-subclass only.bz while using parent reference if we
are accessing data hibernate has to check all the table
where the actual data is available for that hibernate will
union all the table and it will return the corresponding
record to the user. by Mr.sachin gaikwad
by Mr.sachin gaikwad
• Only base class mapping file having the ID element
rest of the child classes we can not configured ID
element bz these child are inherited by base class
only.
• Even we are trying to store child class data into child
table then hibernate well know to the provided
relationship and hibernate going to generate the
key for our next record.
– Ex:
If parent table contains one record and child want to insert the
new record then hibernate enough intelligence to get the id
from executing parent ID generator and it will assign 2 as the id
for next record into child table.
by Mr.sachin gaikwad
Hibernate 68,69
by Mr.sachin gaikwad
• As we seem how to program the application using table per concrete class by
mapping approach, now we will see how to program the same application using the
annotation based approach.
• It’s more easy when compared to the mapping approach, just add one annotation it
will work with annotation based approach.
ex:
@Entity
@Table(name=“PAYMENT”)
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
Class Payment{
@Id
int paymantid;
…………
}
• just adding @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) hibernate will
perform the table per concrete class operation.
• Once we configured the base class with the above annotation there is no need to add
another annotation to the subclasses automatically hibernate will recognize and
by Mr.sachin gaikwad
perform the corresponding operation.
• 3)Table per subclass:
– As we learnt table per class hierarchy and table per concrete class now
we will see the third approach that is table per subclass.
– In table per subclass parent/base class data shared to the other
subclasses, In table per concrete class duplicate columns present
across multiple table but in table per subclass we put the relation with
the parent class with child classes To make fully normalized table.
– Actually parent table primary key will become the primary key column
for the child class. b’z to avoid the duplication column among
subclasses.
– while storing the data hibernate is intelligence in separating parent
class data and child class data and it will stored into the respective
tables.
– But while accessing hibernate has to follow join strategy b’z while
storing the data sub tables will get the parent primary key id.
– To find out were the actually data is coming from hibernate has to use
join queries, comparing parent key id value with sub table id value and
retrieve the data. by Mr.sachin gaikwad
• In table per subclass if we directly accessing the data from child
table then it will use equi-join to retrieve the data.
• Table per subclass is the fully normalized tables.
• It also support polymorphism queries while retrieving the data.
• Using super class reference we can retrieve the data but it is
every costly b’z to get the data all table has to be join using left
outer join.
• To map these classes we have to use the joined-subclass
element while configuring the mapping file.
• It is recommended to configure the key attributes in each and
every child table bz super class primary key column value
become the foreign key and primary key for the child tables. So
to retrieve the data it is mandatory to provide the key
attributes.
• Lets see the mapping files.by Mr.sachin gaikwad
by Mr.sachin gaikwad
Hibernate 70,71-miss
• As per the above discussion we can run the application using mapping file but there is
another approach which give rest to the mapping approach i.e. annotation driven approach.
• To write the same application using the annotation based approach we have to use below
procedure.
Ex:
@Entity
@Table(name="PAYMENT")
@Inheritance(strategy=InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name="paymentId")
public class Payment {
@Id
@Column(name="PAYMENT_ID")
@GenericGenerator(strategy="increment",name="hib_inc")
@GeneratedValue(strategy=GenerationType.AUTO,generator="hib_inc ")
private int paymentId;
private String merchant;
private float amount;
…
} by Mr.sachin gaikwad
• Above class is the base class which has all the
required annotation but for child class or derived class
we have to add one extra annotation along with the
regular annotation.
• Ex:
@Entity
@Table(“CARD_PAYMENT”)
@PrimaryKeyJoinColumn(name="card_payment Id")
public class CardPayment extends Payment {
…….
}
by this we completed the annotation driven approach
with table per subclass.by Mr.sachin gaikwad
• Implicit polymorphism:
– This technique has provided by the hibernate people to work with
inheritance mapping approach.
– In this approach we have to write the classes only and the mapping
files as normal.
– But classes should be inherited into hierarchy.
– For every class provide the separate mapping file along with the
corresponding tables.
– While persisting the data hibernate has to identify the relation
between the classes and hibernate good enough in storing the data in
corresponding tables.
– But the problem is that while retrieving the data hibernate may not
retrieve correct data, bz each and every table has its primary key
column so hibernate got confuse while retrieving the data, Which
record programmer asking for.
ex:
just write the normal classes and there corresponding mapping and
classes should be in inherited byhierarchy. And execute the application.
Mr.sachin gaikwad
Hibernate 71
by Mr.sachin gaikwad
Hibernate 72
• Association Mapping model:
– We can access properties of one class to another class by two ways
• Inheritance
– Generalization
– Realization
• Association
– Association
– Aggregation
– Composition
– As we learnt how to work with inheritance mapping model, Now we
will learn how to work with the Association Mapping model.
– Association represents the HAS-A relationship between the classes.
– means one class contains multiple attributes of own class and other
class also.
– Association does not have any owner and they are independent, one
can live without other one.
– Composition mean it has the owner and they are completely
dependent on each other, one can not survive without other one.
by Mr.sachin gaikwad
• In relation database we can represent the relation
using primary key and foreign key. But coming to
the java we can represent the relationship using
inheritance or association.
• In relational DB there are cardinalities available for
representing the relationship, in java also we can
represent the cardinalities using association
mapping.
• Let see the below representation.
• As per the below representation we can associate
one table to another table.
by Mr.sachin gaikwad
by Mr.sachin gaikwad
• In java also we can represent the association between the classes, to
represent the association we have to take other class object as a
attribute of the another class.
– Ex:
Class person{
private personID;
….
Address address;
}
Class Address {
int addressId;
…..
}
• Once we taken another class object as a attribute in another class it
is not enough again we have to map that class with the relational
table internally using mapping files.
• While persisting the person data address should be persist into the
address table. And while accessing the person record ,address
by Mr.sachin gaikwad
should be fetch from the DB.
Hibernate 73,74
• Ex:
– <many-to-one name=“attr_name” column=“col_name”
class=“Atrri_class_name” unique=“true”/>
– As per the above example many-to-one is establish the relationship between
two classes. i.e. person and address.
– Name: attribute represent the name of the attribute whichever we defined
inside the person class .
– Column : it represent the where actually we going to store the values into the
table.
– Class: Actually person class hold the address class attribute but coming to the
relational tables person table has foreign key column relation with the address
table which represent the many to one relationship.
– Unique: To make many-to-one as one-to-one we have used the unique as true.
by Mr.sachin gaikwad
• Ex:
<many-to-one name=“address” column=“address_Id”
class=“Address”/>
– address is the attribute for person class but it is the object type
attribute, one we configured as address as attribute hibernate
will can join the relationship between ADDRESS table and
PERSON table by placing the column name as address_id as the
foreign key in the person table.
– Address_id of PERSON table is the primary key of the ADDRESS
table .
– While accessing the data hibernate will join PERSON and
ADDRESS table according to there relationship means address_id
of PERSON table and the address_id of ADDRESS table ,it will
compare and if both are equal then it will return person and
address data.
– By using class hibernate will get the corresponding table for that
class and it is easy to relate the relationship.
by Mr.sachin gaikwad
by Mr.sachin gaikwad
Hibernate 75
• One to one association mapping:
• It is one of the association technique which allow us to map the two tables.
• Here one table primary key will become the primary key of the other table
as a foreign key.
• For such kind of mapping hibernate has provided a tag called one-to-one.
ex:
<one-to-one name=“house” class=“House”/>
• In the above example house will be the object type attribute which is
declared in the layout class.
• Hibernate will take house and it will get the corresponding type, using that
it will go to the particular class and it will get the primary key column and
value and it will inject in to the layout table id column.
• Bz in layout mapping file we configured id generator as foreign and
property name as house.
• Means house table primary key value will be injected to the primary key
value to the layout table. by Mr.sachin gaikwad
• Lets see the example
by Mr.sachin gaikwad
Hibernate 76,77,78
• One-to-Many Association:
– While working with one-to-one we made many-to-one as one-to-
one by making many side as unique and not-null.
– Many side represent more then one value going to associate with
the one side.
• Ex:
1) A person can have multiple address (means in address table we have to make
person id as many side)(set of address)
2) In multiple choice question exams ,one question have multiple answer (means in
answer table we have to make question_id as foreign key column)(set of answer)
3) A property can have multiple approvals (means approval table property_id
became foreign key column)(set of approvals)
4) A order can have multiple Items (means in items table order_id became foreign
key column)(set of items)
• As per the example we will derive the class which will give
more clarity.
• Lets see below by Mr.sachin gaikwad
.
by Mr.sachin gaikwad
• As per the above example we can easily derive the mapping
file.
• Hibernate has provided multiple tags which going to
represents the set of values for a specific attributes.
– Set :
• We can use set when insertion order is not required and duplicate are not
allowed.
• Set represents the attribute name and where that attribute is belongs to
and we can configure cascade, inverse also.
• Within set we have configure the foreign key column inside the key tag.
– List
• We can use list when insertion order will be required and duplicate will be
allow.
• While configuring the list we have to tell to the hibernate take this column
and starting index no and maintaining the insertion order.
• In list also we have to configure the foreign key column under key tag only.
• While configuring list we have to write and attribute name and
by Mr.sachin gaikwad
corresponding table and cascade , inverse and so on.
• Let see how actually we can able to derive the
mapping for property and approval.
• As per the above class one property can have
multiple approvals for example electricity approval,
water board approval , land cert approvals…. Etc.
by Mr.sachin gaikwad
Hibernate 79
by Mr.sachin gaikwad
by Mr.sachin gaikwad
• One-To-Many with Bag:
– Bag is collection type tag which is provided by hibernate
people.
– Why bag collection has provided by hibernate people?
– Set collection will store the data in unordered manner but
it will not allow duplicate .
– List collection will store the data in ordered manner but it
will allow duplicate value.
– But sometime requirement is data should be unordered
and duplicate also allow bz of that hibernate has provided
a collection called bag collection.
– Bag collection is configured same as set just we need to
change the tag name i.e. bag.
– Bag collection is implementation of collection we can use
any collection to map the bag collection data.
by Mr.sachin gaikwad
• We can map bag as set only lets see the example
<bag name=“aprovals” cascade=“all” inverse=“false”>
<key>
<column name=“P_property_id” />
</key>
</bag>
by Mr.sachin gaikwad