What is Hibernate:
Hibernate is the ORM tool given to transfer the data between a java (object) application and a database (Relational) in the form of the objects. Hibernate is the open source light weight tool given by Gavin King, actually JBoss server is also created by this person only.
Hibernate is a non-invasive framework, means it wont forces the programmers to extend/implement any class/interface, and in hibernate we have all POJO classes so its light weight.
Hibernate can runs with in or with out server, i mean it will suitable for all types of java applications (stand alone or desktop or any servlets bla bla.)
Hibernate is purely for persistence (to store/retrieve data from Database).
Advantages of hibernates:
- Hibernate supports Inheritance, Associations, Collections
- In hibernate if we save the derived class object, then its base class object will also be stored into the database, it means hibernate supporting inheritance
- Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One
- This will also supports collections like List,Set,Map (Only new collections)
- In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate we only have Un-checked exceptions, so no need to write try, catch, or no need to write throws. Actually in hibernate we have the translator which converts checked to Un-checked

- Hibernate has capability to generate primary keys automatically while we are storing the records into database
- Hibernate has its own query language, i.e hibernate query language which is database independent
- So if we change the database, then also our application will works as HQL is database independent
- HQL contains database independent commands
- While we are inserting any record, if we don’t have any particular table in the database, JDBC will rises an error like “View not exist”, and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us

- Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.
- Hibernate supports annotations, apart from XML
- Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API.
- Getting pagination in hibernate is quite simple.
Disadvantages of hibernates:
- I don’t think there are disadvantages in hibernate
- You know some thing.., Its saying hibernate is little slower than pure JDBC, actually the reason being hibernate used to generate many SQL statements in run time, but i guess this is not the disadvantage

- But there is one major disadvantage, which was boilerplate code issue, actually we need to writesame code in several files in the same application, but spring eliminated this.
Configuration:
Configuration is the file loaded into an hibernate application when working with hibernate, this configuration file contains 3 types of information..
- Connection Properties
- Hibernate Properties
- Mapping file name(s)
We must create one configuration file for each database we are going to use, suppose if we want to connect with 2 databases, like Oracle, MySql, then we must create 2 configuration files.
Syntax Of Configuration xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<hibernate-configuration>
<session-factory><!-- Related to the connection START --><property name="connection.driver_class">Driver Class Name </property>
<property name="connection.url">URL </property>
<property name="connection.user">user </property>
<property name="connection.password">password</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true/false</property>
<property name="dialet">Database dialet class</property>
<property name="hbm2ddl.auto">create/update or what ever</property>
<!-- Related to hibernate properties END-->
<!-- Related to mapping START-->
<mapping resource="hbm file 1 name .xml" / >
<mapping resource="hbm file 2 name .xml" / >
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<hibernate-configuration>
<session-factory> <!-- Related to the connection START --> <property name="connection.driver_class">Driver Class Name </property>
<property name="connection.url">URL </property>
<property name="connection.user">user </property>
<property name="connection.password">password</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true/false</property>
<property name="dialet">Database dialet class</property>
<property name="hbm2ddl.auto">create/update or what ever</property>
<!-- Related to hibernate properties END-->
<!-- Related to mapping START-->
<mapping resource="hbm file 1 name .xml" / >
<mapping resource="hbm file 2 name .xml" / >
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>
|
Steps To Use Hibernate In Any Java Application
Whether the java application will run in the server or without server, and the application may be desktop or stand alone, swing, awt, servlet…what ever, but the steps are common to all.
In order to work with hibernate we don’t required any server as mandatory but we need hibernate software (.jar(s) files).
Follow The Steps:
1. Import the hibernate API, they are many more, but these 2 are more than enough…
import org.hibernate.*;
import org.hibernate.cfg.*;
2. Among Configuration, Mapping xml files, first we need to load configuration xml, because once we load the configuration file, automatically mapping file will be loaded as we registered this mapping xml in the configuration file.
So to load configuration xml, we need to create object of Configuration class, which is given inorg.hibernate.cfg.*; and we need to call configure() method in that class, by passing xml configuration file name as parameter.
Eg:
Configuration cf = new Configuration();
cf.configure(“hibernate.cfg.xml”);
Hear our configuration file name is your choice, but by default am have been given hibernate.cfg.xml, so once this configuration file is loaded in our java app, then we can say that hibernate environment isstarted in our program.
So once we write the line_ cf.configure(“hibernate.cfg.xml”), configuration object cf will reads this xml file hibernate.cfg.xml, actually internally cf will uses DOM parsers to read the file.
Finally…
- cf will reads data from hibernate.cfg.xml
- Stores the data in different variables
- And finally all these variables are grouped and create one high level hibernate object we can call as SessionFactory object.
- So Configuration class only can create this SessionFactory object
likeSessionFactory sf = cf.buildSessionFactory();
Actually SessionFactory is an interface not a class, and SessionFactoryImpl is the implimented class for SessionFactory, so we are internally creating object of SessionFactoryImpl class and storing in the interface reference, so this SessionFactory object sf contains all the data regarding the configuation file so we can call sf as heavy weight object.
3. Creating an object of session,
- Session is an interface and SessionImpl is implemented class, both are given in org.hibernate.*;
- When ever session is opened then internally a database connection will be opened, in order to get a session or open a session we need to call openSession() method in SessionFactory, it means SessionFactory produces sessions.
Session session = sf.openSession();sf = SessfionFactory object
4. Create a logical transaction
While working with insert, update, delete, operations from an hibernate application onto the database then hibernate needs a logical Transaction, if we are selecting an object from the database then we donot require any logical transaction in hibernate. In order to begin a logical transaction in hibernate then we need to call a method beginTransaction() given by Session Interface.
Transaction tx = session.beginTransaction();
session is the object of Session Interface
5. Use the methods given by Session Interface, to move the objects from application to database and from database to application
session .save(s) - Inserting object ‘s’ into database session.update(s) - Updating object ‘s’ in the database session.load(s) - Selecting objcet ‘s’ object session.delete(s) - Deletig object ‘s’ from database
- So finally we need to call commit() in Transaction, like tx.commit();
- As i told earlier, when we open session a connection to the database will be created right, so we must close that connection as session. close().
- And finally close the SessionFactory as sf.close()
- That’s it.., we are done.
Final flow will be______________
ConfigurationSessionFactorySessionTransactionClose Statements
Transient, Persistent, Detaiched States
1.Transient State:
A New instance of a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate:
UserDetail user = new UserDetail();
user.setUserName("Dinesh Rajput");
// user is in a transient state
2. Persistent State:
A persistent instance has a representation in the database , an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session:
Long id = (Long) session.save(user);
// user is now in a persistent state
3. Detached State:
Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn’t attached to a Session anymore (but can still be modified and reattached to a new Session later though).
session.close();
//user in detached state
Hibernate
Caching Mechanism, Hibernate Cache
Every fresh session having its own cache memory, Caching is a mechanism for storing the loaded objects into a
cache memory. The advantage of cache mechanism is, whenever again we want to load the same object from the database then instead of hitting the database once again, it loads from the local cache memory
only, so that the no. of round trips between an application and a database
server got decreased. It means caching mechanism increases the performance of the application.
Caching is all about application performance optimization and it
sits between your application and the database to avoid the number of database
hits as many as possible to give a better performance for performance critical
applications
In hibernate we have two levels of caching
·
First Level Cache [ or ]
Session Cache
·
Second Level Cache [ or
] Session Factory Cache [ or ] JVM Level Cache
Refer: Hibernate Caching Mecanishm
One-To-One


Mapping
<
many-to-one
name
=
"studentAddress"
class
=
"com.vaannila.student.Address"
column
=
"STUDENT_ADDRESS"
not-null
=
"true"
cascade
=
"all"
unique
=
"true"
/>
using Annotations
@Entity
@Table
(name =
"STUDENT"
)
public
class
Student {
@OneToOne
(cascade = CascadeType.ALL)
public
Address getStudentAddress() {
return
this
.studentAddress;
}
public
void
setStudentAddress(Address studentAddress) {
this
.studentAddress = studentAddress;
}
}
One-To-Many

Mapping
<
set
name
=
"studentPhoneNumbers"
table
=
"STUDENT_PHONE"
cascade
=
"all"
>
<
key
column
=
"STUDENT_ID"
/>
<
many-to-many
column
=
"PHONE_ID"
unique
=
"true"
class
=
"com.vaannila.student.Phone"
/>
</
set
>
using Annotations @Entity
@Table
(name =
"STUDENT"
)
public
class
Student {
private
Set<Phone> studentPhoneNumbers =
new
HashSet<Phone>(
0
);
@OneToMany
(cascade = CascadeType.ALL)
@JoinTable
(name =
"STUDENT_PHONE"
, joinColumns = {
@JoinColumn
(name =
"STUDENT_ID"
) }, inverseJoinColumns = {
@JoinColumn
(name =
"PHONE_ID"
) })
public
Set<Phone> getStudentPhoneNumbers() {
return
this
.studentPhoneNumbers;
}
public
void
setStudentPhoneNumbers(Set<Phone> studentPhoneNumbers) {
this
.studentPhoneNumbers = studentPhoneNumbers;
}
}
Many-To-One


Mapping
<
many-to-one
name
=
"studentAddress"
class
=
"com.vaannila.student.Address"
column
=
"STUDENT_ADDRESS"
cascade
=
"all"
not-null
=
"true"
/>
using Annotations
@Entity
@Table
(name =
"STUDENT"
)
public
class
Student {
private
Set<Phone> studentPhoneNumbers =
new
HashSet<Phone>(
0
);
@
ManyToOne(cascade = CascadeType.ALL)
public
Address getStudentAddress()
{
return
this
.
studentAddress;
}
public
void
setStudentAddress(
Address studentAddress) {
this
.studentAddress = studentAddress;
}
}
Many-To-Many


Mapping
<
set
name
=
"courses"
table
=
"STUDENT_COURSE"
cascade
=
"all"
>
<
key
column
=
"STUDENT_ID"
/>
<
many-to-many
column
=
"COURSE_ID"
class
=
"com.vaannila.student.Course"
/>
</
set
>
using Annotations
@Entity
@Table
(name =
"STUDENT"
)
public
class
Student {
private
Set<Course> courses =
new
HashSet<Course>(
0
);
@ManyToMany
(cascade = CascadeType.ALL)
@JoinTable
(name =
"STUDENT_COURSE"
, joinColumns = {
@JoinColumn
(name =
"STUDENT_ID"
) }, inverseJoinColumns = {
@JoinColumn
(name =
"COURSE_ID"
) })
public
Set<Course> getCourses() {
return
this
.courses;
}
public
void
setCourses(Set<Course> courses) {
this
.courses = courses;
}
}
HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
Using HBM Mapping:
sessionFactory = new Configuration().configure().buildSessionFactory();
or
Using Annotations:
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Execution of Hibernate using main method
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; public class Main { public static void main(String[] args) {//Opened session object Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try {// transaction begintransaction = session.beginTransaction();bussiness logic codesession.save(<persistanceobject>);//transaction comited
transaction.commit();
} catch (HibernateException e) {
// If any exception occurred, then that transaction need to roll back
transaction.rollback();
e.printStackTrace();
} finally {
// For every Session opened, need to close those session.
session.close();
}
}
}
List of generators
The following are the list of main generators we are using in the hibernate framework
- assigned
- increment
- sequence
- identity
- hilo
- native
- foregin
- uuid.hex
- uuid.string
save():
save
specifically does an insert.
It can be used to save a new object. It returns the serialiable identity.
So calling save again will result in another row in the db.
persist():
It is same as save(), but is void method and does not return anything.
update():
update
updates an object in the session. So if the object is in the session it will update. If the object is not in the session, you should call merge. I believe calling update
for a detached instance will result in an exception.
saveOrUpdate():
This method will work for both new and old objects. If object is new, it will work like simple save or if object is already persistent, it will work like update.
lock():
Optimistic vs Pessimistic:
Optimistic locking:
(Version concept)
Pessimistic locking : Pessimistic locking aims to avoid conflicts by using locking.
Pessimistic locking aims to avoid conflicts by using locking.
Note : In both data-locking models, the lock is released after the changes are committed to the database.
====================================================================
Property name Purpose
hibernate.dialect The classname of a Hibernate org.hibernate.dialect.Dialect
which allows Hibernate to generate SQL optimized for a particular relational database.e.g. full.classname.of.Dialect
In most cases Hibernate will actually be able to choose the correct org.hibernate.dialect.Dialect
implementation based on theJDBC metadata
returned by the JDBC driver.
hibernate.show_sql Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL
to debug
.e.g. true
| false
hibernate.format_sql Pretty print the SQL in the log and console.
e.g. true
| false
hibernate.default_schema Qualify unqualified table names with the given schema/tablespace in generated SQL.
e.g. SCHEMA_NAME
hibernate.default_catalog Qualifies unqualified table names with the given catalog in generated SQL.
e.g. CATALOG_NAME
hibernate.session_factory_name The org.hibernate.SessionFactory
will be automatically bound to this name in JNDI after it has been created.e.g. jndi/composite/name
hibernate.max_fetch_depth Sets a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0
disables default outer join fetching.e.g. recommended values between 0
and 3
hibernate.default_batch_fetch_size Sets a default size for Hibernate batch fetching of associations.
e.g. recommended values 4
, 8
, 16
hibernate.default_entity_mode Sets a default mode for entity representation for all sessions opened from this SessionFactory
dynamic-map
, dom4j
, pojo
hibernate.order_updates Forces Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems.
e.g. true
| false
hibernate.generate_statistics If enabled, Hibernate will collect statistics useful for performance tuning.
e.g. true
| false
hibernate.use_identifier_rollback If enabled, generated identifier properties will be reset to default values when objects are deleted.
e.g. true
| false
hibernate.use_sql_comments If turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to false
.e.g. true
| false
Property name Purpose
hibernate.jdbc.fetch_size A non-zero value determines the JDBC fetch size (callsStatement.setFetchSize()
).
hibernate.jdbc.batch_size A non-zero value enables use of JDBC2 batch updates by Hibernate.
e.g. recommended values between 5
and 30
hibernate.jdbc.batch_versioned_data Set this property to true
if your JDBC driver returns correct row counts from executeBatch()
. Iit is usually safe to turn this option on. Hibernate will then use batched DML for automatically versioned data. Defaults to false
.e.g. true
| false
hibernate.jdbc.factory_class Select a custom org.hibernate.jdbc.Batcher
. Most applications will not need this configuration property.e.g. classname.of.BatcherFactory
hibernate.jdbc.use_scrollable_resultset Enables use of JDBC2 scrollable resultsets by Hibernate. This property is only necessary when using user-supplied JDBC connections. Hibernate uses connection metadata otherwise.
e.g. true
| false
hibernate.jdbc.use_streams_for_binary Use streams when writing/reading binary
or serializable
types to/from JDBC. *system-level property*e.g. true
| false
hibernate.jdbc.use_get_generated_keys Enables use of JDBC3 PreparedStatement.getGeneratedKeys()
to retrieve natively generated keys after insert. Requires JDBC3+ driver and JRE1.4+, set to false if your driver has problems with the Hibernate identifier generators. By default, it tries to determine the driver capabilities using connection metadata.e.g. true|false
hibernate.connection.provider_class The classname of a customorg.hibernate.connection.ConnectionProvider
which provides JDBC connections to Hibernate.e.g. classname.of.ConnectionProvider
hibernate.connection.isolation Sets the JDBC transaction isolation level. Checkjava.sql.Connection
for meaningful values, but note that most databases do not support all isolation levels and some define additional, non-standard isolations.e.g. 1, 2, 4, 8
hibernate.connection.autocommit Enables autocommit for JDBC pooled connections (it is not recommended).
e.g. true
| false
hibernate.connection.release_mode Specifies when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, use after_statement
to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by using after_transaction
. auto
will choose after_statement
for the JTA and CMT transaction strategies and after_transaction
for the JDBC transaction strategy.e.g. auto
(default) | on_close
| after_transaction
|after_statement
This setting only affects Session
s returned fromSessionFactory.openSession
. For Session
s obtained throughSessionFactory.getCurrentSession
, the CurrentSessionContext
implementation configured for use controls the connection release mode for those Session
s. See Section 2.5, “Contextual sessions”
hibernate.connection.<propertyName> Pass the JDBC property <propertyName> toDriverManager.getConnection()
.
hibernate.jndi.<propertyName> Pass the property <propertyName> to the JNDIInitialContextFactory
.
Property name Purpose
hibernate.cache.provider_class
The classname of a custom CacheProvider
.e.g. classname.of.CacheProvider
hibernate.cache.use_minimal_puts
Optimizes second-level cache operation to minimize writes, at the cost of more frequent reads. This setting is most useful for clustered caches and, in Hibernate3, is enabled by default for clustered cache implementations.
e.g. true|false
hibernate.cache.use_query_cache
Enables the query cache. Individual queries still have to be set cachable.
e.g. true|false
hibernate.cache.use_second_level_cache
Can be used to completely disable the second level cache, which is enabled by default for classes which specify a <cache>
mapping.e.g. true|false
hibernate.cache.query_cache_factory
The classname of a custom QueryCache
interface, defaults to the built-in StandardQueryCache
.e.g. classname.of.QueryCache
hibernate.cache.region_prefix
A prefix to use for second-level cache region names.
e.g. prefix
hibernate.cache.use_structured_entries
Forces Hibernate to store data in the second-level cache in a more human-friendly format.
e.g. true|false
Property name Purpose
hibernate.transaction.factory_class
The classname of a TransactionFactory
to use with Hibernate Transaction
API (defaults toJDBCTransactionFactory
).e.g. classname.of.TransactionFactory
jta.UserTransaction
A JNDI name used by JTATransactionFactory
to obtain the JTA UserTransaction
from the application server.e.g. jndi/composite/name
hibernate.transaction.manager_lookup_class
The classname of a TransactionManagerLookup
. It is required when JVM-level caching is enabled or when using hilo generator in a JTA environment.e.g. classname.of.TransactionManagerLookup
hibernate.transaction.flush_before_completion
If enabled, the session will be automatically flushed during the before completion phase of the transaction. Built-in and automatic session context management is preferred, see Section 2.5, “Contextual sessions”.e.g. true
| false
hibernate.transaction.auto_close_session
If enabled, the session will be automatically closed during the after completion phase of the transaction. Built-in and automatic session context management is preferred, seeSection 2.5, “Contextual sessions”.e.g. true
| false
Property name Purpose
hibernate.current_session_context_class
Supply a custom strategy for the scoping of the "current"Session
. See Section 2.5, “Contextual sessions” for more information about the built-in strategies.e.g. jta
| thread
| managed
| custom.Class
hibernate.query.factory_class
Chooses the HQL parser implementation.
e.g.org.hibernate.hql.ast.ASTQueryTranslatorFactory
ororg.hibernate.hql.classic.ClassicQueryTranslatorFactory
hibernate.query.substitutions
Is used to map from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names, for example).
e.g.hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC
hibernate.hbm2ddl.auto
Automatically validates or exports schema DDL to the database when the SessionFactory
is created. With create-drop
, the database schema will be dropped when the SessionFactory
is closed explicitly.e.g. validate
| update
| create
| create-drop
hibernate.cglib.use_reflection_optimizer
Enables the use of CGLIB instead of runtime reflection (System-level property). Reflection can sometimes be useful when troubleshooting. Hibernate always requires CGLIB even if you turn off the optimizer. You cannot set this property inhibernate.cfg.xml
.e.g. true
| false
No comments:
Post a Comment