What is hibernate? Why use it? Benefits over JDBC?
How to set up hibernate?
What is mapping, one to one, etc and how to do it?
How inheritance is handled?
What is the difference between transient, persistent and detached objects?
Explain hibernate cache.
What is session,sessionFactory? Are they threadsafe?
How transaction management is done in hibernate ?
What's the architecture of hibernate?
HQL vs SQL?
save vs saveOrUpdate vs persist vs merge?
How to use second level cache? How to put objects in second level cache?
get vs load?
How to set up hibernate?
What is mapping, one to one, etc and how to do it?
How inheritance is handled?
What is the difference between transient, persistent and detached objects?
Explain hibernate cache.
What is session,sessionFactory? Are they threadsafe?
How transaction management is done in hibernate ?
What's the architecture of hibernate?
HQL vs SQL?
save vs saveOrUpdate vs persist vs merge?
How to use second level cache? How to put objects in second level cache?
get vs load?
*******ANSWERS**********************************
1. What is hibernate? Why use it? Benefits over JDBC?
Hibernate is an ORM (Object Relation Mapping) framework. It is used to solve object-relational impedance problem which is the problem of inconsistency between an OOP(Object Oriented Programming) language and relational/SQL language/database.
It has many benefits over JDBC:
a) It eliminates boilerplate code of JDBC and handling it's checked exceptions.
b) It helps in smooth and faster development as tables are treated like objects now. Also, hibernate provides more intuitive language called HQL which is similar to SQL.
c) It improves the performance of application because of hibernate cache and lazy loading.
d) It improves exception handling(how?)
2. How to set up hibernate? ( explain it further with screenshots and sample project)
Working with hibernate is quite easy. I am using Maven for building project which makes it even easier. After setting up the dependencies in pom.xml , we can create a singleton to get the SessionFactory for hibernate which will be our source for all the sessions. In hibernate 3 , we can create sessionfactory like this :
1. Create a configuration file for hibernate , name it as hibernate.cfg.xml. In this file we will fill the details of driver name , database name, username and password.
2. Code to create sessionFactorynew Configuration.configure.createSessionFactory();3. To map the table in hibernate create a POJO file having properties and their getters and setters correspoding to the columns in the table.
4. Now create a xml file named as <filename>.hbm.xml which will map these properties to the corresponding columns in the corresponding table.
5. This mapping will be configured in the hibernate configuration file created in first step.
6. Now, we are ready to work with hibernate. We can create a session from sessionFactory, create an object of POJO and save it in database.Instead of creating xml files for mapping we can annotate our POJOs with certain annotations and that will work fine too. In fact, that is the preferred approach nowadays.
3. What is mapping, one to one, etc and how to do it?(will do later with screenshots in detail)
There are 3 type of mapping :
a) One to One mapping:
It can be done in two ways:
i. Using one to one with generator class="foreign" (link to example)
ii. Using many to one with unique="true" attribute (link to example)
b) Many to One mapping
c) Many to Many mapping
There are 3 type of mapping :
a) One to One mapping:
It can be done in two ways:
i. Using one to one with generator class="foreign" (link to example)
ii. Using many to one with unique="true" attribute (link to example)
b) Many to One mapping
c) Many to Many mapping
Above examples using annotation:
a) One to One mapping:
It can be done in two ways:
i. Using one to one with generator class="foreign" (link to example)
ii. Using many to one with unique="true" attribute (link to example)
b) Many to One mapping
c) Many to Many mapping
4. How inheritance is handled?
Inheritance can be handled by three strategies:
a) One class per heirarchy
b) One class per concrete class
c) One class per subclass
a) One to One mapping:
It can be done in two ways:
i. Using one to one with generator class="foreign" (link to example)
ii. Using many to one with unique="true" attribute (link to example)
b) Many to One mapping
c) Many to Many mapping
4. How inheritance is handled?
Inheritance can be handled by three strategies:
a) One class per heirarchy
b) One class per concrete class
c) One class per subclass
5. What is the difference between transient, persistent and detached objects?
An object which is in session is persistent.
An objct which is out of scope is detached.
An object which is ?
An object which is in session is persistent.
An objct which is out of scope is detached.
An object which is ?
6. Explain hibernate cache. First level cache vs Second level cache?
Hibernate has two levels of cache.
a) First level cache: This is mandatory and can't be configured by user. Every query in hibernate goes through this level. This is associated with session.
b) Second level cache: This is associated with sessionFactory.
Hibernate has two levels of cache.
a) First level cache: This is mandatory and can't be configured by user. Every query in hibernate goes through this level. This is associated with session.
b) Second level cache: This is associated with sessionFactory.
7. What is session,sessionFactory? Are they threadsafe?
Session is an interface which represents connection with the database. It's quite lightweight and derived from sessionFactory interface.
SessionFactory is the interface which acts a pool of connections. It's quite heavyweight and used a singleton.
SessionFactory is immutable and hence threadsafe however session is not threadsafe and it's the responsiblity of the developer to handle thread safety issues with session.
Session is an interface which represents connection with the database. It's quite lightweight and derived from sessionFactory interface.
SessionFactory is the interface which acts a pool of connections. It's quite heavyweight and used a singleton.
SessionFactory is immutable and hence threadsafe however session is not threadsafe and it's the responsiblity of the developer to handle thread safety issues with session.
How transaction management is done in hibernate?
session.beginTransaction();
session.getTransaction.commit();
Using spring we can do declarative transaction management too.
session.beginTransaction();
session.getTransaction.commit();
Using spring we can do declarative transaction management too.
Get vs load?
If value is not found, get returns null while load throws exception.
Get fetches the value immediately while load does lazy loading.
If value is not found, get returns null while load throws exception.
Get fetches the value immediately while load does lazy loading.
HQL vs SQL?
Save vs saveOrUpdate vs persist vs merge?
save- can be used without transaction, does this mean this data might not have been committed?
How to use second level cache? How to put objects in second level cache?
get vs load?
session.flush()?
flush- forces hibernate to execute commands on DB, doesn't mean commands are committed
commit = flush+commit
*******************************************************************
Q: What is Hibernate Framework ?
A: Hibernate is an ORM (Object Relation Mapping) framework. It is used to solve object-relational impedance problem which is the problem of inconsistency between an OOP(Object Oriented Programming) language and relational/SQL language/database.
Q: Can you elaborate on object-relational impedance problem ?
A: When we use a relational database and thus SQL with an OOP language such as Java then there are several problems. In OOP we deal with objects , everything is an object , an object has properties and behaviour. But when we query database , we don't get objects , we get a bunch of rows and columns. It's difficult to work with them.
Q: Ok , so how do you start working with Hibernate ? Where does it fit into your application ?
A: Working with hibernate is quite easy. I am using Maven for building project which makes it even easier. After setting up the dependencies in pom.xml , we can create a singleton to get the SessionFactory for hibernate which will be our source for all the sessions. In hibernate 3 , we can create sessionfactory like this :
- Create a configuration file for hibernate , name it as hibernate.cfg.xml. In this file we will fill the details of driver name , database , username and password.
2. Code to create sessionFactory
new Configuration.configure.createSessionFactory();
After creating sessionFactory , we can obtain session from it and start working. But first we need to map our tables to objects. For that , we will create some simple POJOs containing variables and getters and setters and map them to the tables via xml files or annotations.
3. Create a POJO file having some properties and getters and setters.
4. Now create a xml file which will map these properties to the corresponding columns in the corresponding table.
5. This mapping will be mentioned in the hibernate configuration file created in first step.
Now we are ready to start working with our hibernate framework. Instead of creating xml files for mapping we can annotate our POJOs with ceratain annotations and that will work fine too. In fact, that is the preferred approach nowadays.
Q: So , we are ready with hibernate and we have been using it for some time , but suddenly project requirements forces us to switch to some other database. What will happen in that situation ?
A: Hibernate implements JPA (Java Persistence API) which is a standard for persistence framework. Of course , Hibernate provides it's own sets of functionalites too. So , if we are using JPA specific annotations and methods , our code will be portable otherwise we will have to rewrite the code. So , it's recommended always to use JPA specific annotations.
Q: What is this JPA ?
A: JPA stands for Java Persistence API , which is a standard set by Java Community Process , it's like an interface for persistent framework. So , if an application uses JPA , it can switch seamlessly among those framework which implements JPA such as hibernate , toplink.
Q: How do we decide when to use hibernate ?
A: Hiberante is a framework , and just like any other framework , it assists a developer to develop applications easily , quickly and improves performance. In case , the application is not so huge , in that case we can go with JDBC.
Q:
*********************************NEXT**************************
9. What's the architecture of hibernate?
*****************
One to one mappingLet's say, Employee has address and address has employee(Use better example)
Just one line in each hbm files:
For address: <one-to-one name="employee" class="kumar.HibernateBasic.Employee"></one-to-one>
and similarly for employee:
<one-to-one name="address" class="kumar.HibernateBasic.Address" cascade="all"></one-to-one>
Here we will be saving employee and adddress will be saved automatically
Just one more thing to observe, in address hbm generator will be 'foreign' and it will use employee
<id name="id" type="int">
<column name="ID" />
<generator class="foreign" >
<param name="property">employee</param>
</generator>
</id>
***********************************************************
Save:
After save flush is required if you aren't committing transaction.
Flush forces hibernate to be in sync with db, all queries are run although not committed.
Then what does save guarantee? that sooner or later they will be inserted
Also in save, cascading won't work. It will only work when in transaction and transaction is committed.
If I am flushing, cascading is happening.
It will return id immediately
If there are any changes to the object after save, they won't be persisted.
Will fall back to update if not a new object
Persist:
Returns void, we have to use persisted object to get identifier value
Can be used only with transaction boundary
Thus, cascading will also happen
Adds the entity object to persistent context. If object is changed later, that will also be updated, (before transaction is committed)
SaveOrUpdate:
returns void
Same as save except like persist it adds the object to persistentce context
Same as save can be used without transaction, even primary is not updated without flush
Will update if required
so saveOrUpdate = save + persist, also used to update object
Update:
same as saveOrUpdate except it's used only for updating
Merge:
it's used to bring object from detached state to persistent
given transient object new data will be updated to db and it will be also be copied to returned object which will be in persistence context.
Refresh:
update an object and sync it with db
Get vs Load
Get - returns object immediately
if not found return null
Load - lazy load
if not found throws exception
Syntax: session.get(Employee.class,1);
Open session vs current session
Current Session
<property name="hibernate.current_session_context_class">thread</property>
needs to be configured to use current session otherwise it won't work, exception will come
No need to close, will be closed automatically when sessionFactory is closed
Stateless Session
No first level cache, no second level
No collections or cascading
Nothing
Behaves like normal jdbc operation
Second level cache
4 types of caching strategies:
1. Read - only read, fast
2. ReadWrite - will work only if updated through Hibernate API
3. Nonrestricted ReadWrite - if occasional read write
4. Transactional - Full
Using Ehcache:
Two jars are required: ehcache-xxx.jar, hibernate-ehcache
If this exception comes:
java.lang.NoSuchMethodError: net.sf.ehcache.config.CacheConfiguration.isTerracottaClustered()
Many To Many
Each class contains a set of other class objects
Follow journaldev
Don't set set of each class, only one of them, the primary one
A join table will be used
Each hbm will have usual setting and for set, inside set there will be manytomany tag
which will have some settings
<set name="addresses" table="Employee_Address" fetch="select" cascade="all">
<key column="employee_id" />
<many-to-many class="kumar.HibernateBasic.Address" column="address_id"></many-to-many>
</set>
Remember to use full name of class
HQL:
Query query = session.createQuery("from Employee");
List<Employee> employees= query.list();
Query query = session.createQuery("from Employee where id=?");
query.setInteger(0,1);
Employee e = query.uniqueResult();
Query query = session.createQuery("from Employee where id=:id");
query.setInteger("id",1);
Employee e = query.uniqueResult();
Won't work without transaction.
Hibernate vs JDBC
1. No boilerplate code
2. Object Oriented way to access db
3. HQL, OO query language
4. Joins, collections, mapping
5. Hibernate Validation
6. Database independent
7. If JPA annotations followed, ORM independent
8. Improved performance because of cache and lazy loading
Annotated class can be added to hibernate.cfg.xml
<mapping class="kumar.HibernateBasic.Person" />
Hibernate.cfg.xml can also be replaced by a class, code only
**************************
No comments:
Post a Comment