Hibernate Q and A
Hibernate Q and A
Hibernate Q and A
cache.
Ex:
Transaction tx = hsession.beginTransaction();
hsession.load(e,new BigDecimal(1));
e.setName(“Raju”);
22
hsession.evict(e);
tx.commit();
When we run the above application with out evict() method. It has update a record
into
database server. When we run the some application with evict() method. It has
removed
employee object from 1st level cache.
*merge(): merge method is used to add a specified object to the 1st level cache.
Ex:
Emp e = new Emp();
e.setEno(new BigDecimal(22));
e.setName(“ABC modified”);
e.setSalary(1234d);
hsession.merge(e);
tx.commit();
When the merge() method is called the object is added to 1st level cache without
registration code. When tx.commit() method is called it will get the object which
does not
contain the registration code. It will check weather the object is available in
database
server by sending select query. If the record is not available it will send an
insert query to
database server. If the record is already available it will send a an update query
to
database server.
*There three states are available to hibernate objects they are:
1. Transient
2. Persistent
3. Detached
Transient: An object is which is not associated with any session object.
Persistent: An object which is added to 1st level cache is called as persistent
state.
Detached: An object which is removed from 1st level cache is called detached state.
*Clear():
Clear is used to remove all the objects from 1st level cache. This will remove
unperformed operations like save and update also. The clear() method will evict all
available objects
*get():
get() method is also used to retrieve the record from database server if the record
is
available it returns that POJO class object. If record is not available it returns
null value.
Ex:
Object o = hsession.get(product.class,2);
If(o! = null){
Product p = (product)o;
System.out.println(p.getPid());
System.out.println(p.getName());
System.out.println(p.getPrice());
}
else{
System.out.println(“Record is not available”);
}
*flush():
When we call in flush() method all the objects which are available in 1st level
cache will be converted into queries and send to database server. Flush will not
store data
permanently. When we all the commit() method the data is stored permanently.
Hibernatejpa annotation
---------------------------------
1> @Entity
-------------------
->it is used to mark the class as persistent java class.
2> @Table
-------------------
->it is used to provide the details of the table.
3> @Id
-----------
->it is used to define the primary key.
4> @GeneratedValue
-------------------------
->it is used to define the primary key generation strategy.
5> @Column
-----------------
->it is used to define the properties of the column that will be mapped to the
annotated field. you can
define several properties like name, length, nullable etc.
6> @OneToOne
---------------------
-> @OneToOne annotation is used to create one to one relationship between Country
and Capital
entities.
7> @joinColumn
------------------------
->it is used to specify a mapped column for joining an entity association.
8> @Inheritance
------------------------
-> For implementing inheritance in hiberante, @Inheritance annotation is used.It
defines inheritance
strategy to be implement for entity class hierarchy.
-> For one table per class hierarhcy,we have used Single_Table as inheritance
strategy.This annotation is
defined at root level or sub hierarchy level
where different strategy is to be applied.
9> @DescriminatorColumn
--------------------------
-> This annotation is used to define discriminator column for Single_Table and
joined strategy.It is used
to distinguish between different class instances.
-> This annotation is defined at root level or sub hierarchy level where different
strategy is to be applied.
-> If @DiscriminatorColumn annotation is not specified,then hibernate will create a
column named as
“DType” and DiscriminatorType will be string.
10> @DescriminatorValue
------------------------------
-> This annotation defines value in discriminator column for that class.This can
only be applied on entity
concrete class.
Diff between getOpen session and getCurrent session.
-------------------------------------------------------------
->getOpen session
-----------------------------
-> It always create new Session object.
-> You need to explicitly flush and close session objects.
-> In single threaded environment, It is slower than getCurrentSession.
getCurrent session.
---------------------------
-> It creates a new Session if not exists , else use same session which is in
current hibernate context.
-> You do not need to flush and close session objects, it will be automatically
taken care by Hibernate
internally.
-> In single threaded environment , It is faster than getOpenSession.
15. what is diff between session.Get() method and session.Load() method.
-----------------------------------------------------------------------------------
---
->get() and load() both are session class method used for retrieving the data from
the database.
->get() and load() return the data in the object format.
get()
----------
->if the record is not present in the database then get() always returns null.
->get() not create proxy obj its always return actual object.
->get() always hits the database.
->performance wise get() is not good.
->get() is eager initializer, get() reads or loads an obj early. so it is called
early loading.
-> If you are not sure if object with id exists or not, you can use get.
load()
-------------
->if the record is not present in the database then it returns
ObjectNotFoundException.
->load() returns proxy objects and loads data only when it is actually required .
so load() is better becoz
its support lazy loading.
->load() doesnt hits the database every time.
->performance wise it is better to get().
->load() lazy initializer.load() reads or loads an object lazely.
-> If you are sure about existence of object, you can use load.
16. what is session.save() and session.persist().
-----------------------------------------------------------
->save() and persist() both method which we are mainly used for saves the object
in the database.
save()
-------------
->save() method will save an obj to the database and returns the id of the saved
objects(primary key) in
the form of serializable type.
->save() can be used inside or outside the transaction boundries. save() is not
fit for long time running
transaction.
->its take more time to execute.
->save() method return type is serializable.
persist()
------------------
-> save/persist both the methods we can use to save/store an obj to database.
->persist() will save an obj into database but it doesnt return id of saved obj.
it doesnt return anything.
its return type is void.
->persist() can be used only within the boundary of transaction. persist() is
suitable for long time
running transaction. It saves data when flush is called.
->persist() takes less time to execute.
->persist() method return type is void.
17. what is session.upadate().
----------------------------------------
->update() just update the record & throws hibernate exception. if record is not
avialable to update.
->this method doesnt return anything becoz its return type is void.
->this method cannot update primary key value.
18. what is session.save or saveorupadate().
---------------------------------------------
->save() perform only insert but saveorupdate() update the record if record is
avialable otherwise insert
the record in the database table.
->this method doesnot return anything becoz its return type is void.
->this method we can update primary key column value.
save -> Save stores object in database. It generates id for the object and returns
it. If object already
exists in database, it will throw an error.
saveorUpdate ->SaveOrUpdate method save the object if id does not exist. If it
exists , it calls update
method.
9. What is diff between first level cache and second level cache.
----------------------------------------------------------------------------
->First level cache
-----------------------------
->First level cache is associated with session obj.
->First level cache is by default enabled.
->First level cache scope is session level.
->First level cache is not sharable.
->First level cache is available only until the session is opened, once the
session is closed. The first level
cache is destroyed.
Second level cache
--------------------------------
->Second level cache is associated with session factory obj.
->it is optional. If u want then enabled hibernate.cfg.xml.
->Second level cache scope is application level.
->Second level cache is sharable.
->Second level cache is available through the application life cycle. it is only
destroy when your
application is restart.
1. what is diff between jdbc and hibernate. and why we are used hibernate.
-------------------------------------------------------------------------------
JDBC
--------
->it is database dependent.
->jdbc does not send the data in the form of object. it will allow to send the
data in form of text or
value.
->jdbc is an api provided by third party vendor. its throw sql exception i.e
checked exception so we
need to write lot of try catch block.its a boiler plate code.
->jdbc does not support cache mechanism so performance of application is low.
->jdbc code is very tightly coupled with the application.
->jdbc does not support relationships.
Hibernate
--------------
-> hibernate is a database independent so we can run any platform.
->but in real-time we need to transfer the data in the form of objs. in hibernate
we can send the data in
the form of object.
-> hibernate is an ORM framework. its throw uncheked exception so we no need to
write try catch an
throws exception.hibernatebuilts in transaction managemnet
system.it removes the usage of try catch blocks.
-> hibernate support caching mechanism .it improves the performance of the
application for efficient
data retrieval.
->hibernate support jpa annotaions. so it removes lot of boiler plate code that
comes jdbcapi the code
looks like more readable and clears.
->its support inheritance or association relationship.
2. what is ORM (object relational mapping).
------------------------------------------------
-> Hibernate is the most-popular persistence framework and ORM tool for Java
Applications.
-> ORM (Object/Relational Mapping) is a methodology where objects in Java
Applications are persisted
transparently in the relational database tables.
-> ORM stands for Object Relational mapping. It is programming paradigm which is
used to persist java
objects to database tables.
3. what is session.
-----------------------------
->session is an interface present in "org.hibernate.package".
->it is used to perform db operation. session provide methods to perform create,
read, update, and
delete operations for a persistent obj.
->we can execute hqlquries, sql native quires and create criteria using session
obj.
4. what is Session Factory.
-----------------------------------
->session factory is an interface present in "org.hibernate package".
->session factory is a state which contain mapping file & configuration file
information and create the
connection to perform the db operation.
-> Session Factory is a heavy weight object and it should be created one per
database. SessionFactory
object is shared by multiple sessions.
->session factory is a heavy weight obj that has to be created only once per
application.
->when u have multiple db in your application you should create multiple session
factory objects. eg if u
are using two db called mysql& oracle in your
hibernate application then u need to build 2 session factory objects.
sessionfactory factory = newconfiguration().buildsessionfactory();.
5. what is diff between session and session factory.
---------------------------------------------------------
->session
--------------
->session is not a threadsafe.
->it is mutable.
->it is a lightweight.
->performance wise it is high compare to session factory.
sessionfactory
--------------------------
->sessionfactory is threadsafe so, many thread can access it concurrently or
simulteniously.
->it is immutable and it will be created as singleton while the server initialize
itself.
->it is heavy weight becoz it maintain datasource, mapping file, and configuration
file information.
->performance wise it is low compare to session.