Advantages
1. Generates the SQL on the fly & then automatically executes necessary SQL statements. This saves lot of development & debugging time.
2. Mapping of domain object to relational Database, Now you can concentrate on business logic rather than mapping data in DB.
3. Layered Architecture, You can use components as per your application need.
4. JPA Provider can work as JPA provider in JPA based application.
5. No need to create any connection pool in case of Hibernate. You can use c3p0.
6. In case of JDBC you need to write your own connection pool.
7. In the xml file you can see all the relations between tables in case of Hibernate, easily readable.
8. You can enable lazy loading objects, improves the performance by fetching the required data.
9. Hibernate supports automatic versioning of rows but JDBC Not.
10. Hiberante is not tightly tied with any underlaying database.Where as JDBC is tighlty tield with the underlaying database.
11. Hibernate creates the table structure (create tables) for any database type while loading session factory.
Disadvantages
- Lots of API to learn.
- Debugging & performance tuning becomes difficult.
- Slower than JDBC, generates lots of SQL statements in run time.
- Not suitable for Bacth processing.
- Everything is an object. If you need only a portion of data (say, for a search), you would still have to retrieve the object. However, this is true for any ORM strategy.
- In some cases, you will encounter the (n+1) select problem. That is, Hibernate will execute (n+1) queries for going through a list of records of size n. There are some mechanisms suggested by Hibernate that can be used to mitigate this risk.
- Till Hibernate 3, you cannot map multiple tables to a single class. This has been fixed in Hibernate 3 using the join tag.
- Not that flexible when it comes to mapping composite-ids (although you can do a lot). While this is not a fault of Hibernate as composite-ids are typically used in legacy systems, it can be a pain when attempting to map legacy tables.
------------------------------------------------------------------------------------------------------
What There are three types of inheritance models in Hibernate
- Table per class hierarchy - (subclass & discriminator-value)
- Table per subclass ( joined-subclass or subclass with discriminator & join)
- Table per concrete class (union-subclass & table)
The general flow of Hibernate communication with RDBMS is
Collection types in Hibernate - Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
- Create session factory from configuration object
- Get one session from this session factory
- Create HQL Query
- Execute query to get list containing Java objects
- Bag
- Set
- List
- Array
- Map
Three types of Hibernate instance states
- Transient- an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned.
- Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.
- Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user
- persist() - makes a transient instance persistent. However, it does not guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.
- save() does guarantee to return an identifier. If an INSERT has to be executed to get the identifier ( e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is problematic in a long-running conversation with an extended Session/persistence context.
Modifying detached objects
Session.update() or Session.merge() methods:If the Cat with identifier catId had already been loaded by secondSession when the application - Many applications need to retrieve an object in one transaction, send it to the UI layer formanipulation, then save the changes in a new transaction. Applications that use this kind of approach in a high-concurrency environment usually use versioned data to ensure isolation for the "long" unit of work.
- Hibernate supports this model by providing for reattachment of detached instances using the // in the first session
- Cat cat = (Cat) firstSession.load(Cat.class, catId);
- Cat potentialMate = new Cat();
- firstSession.save(potentialMate);
- // in a higher layer of the application
- cat.setMate(potentialMate);
- // later, in a new session
- secondSession.update(cat); // update cat
- secondSession.update(mate); // update mate
- tried to reattach it, an exception would have been thrown.
Automatic state detection
Hibernate users have requested a general purpose method that either saves a transient instanceby generating a new identifier or updates/reattaches the detached instances associated with its current identifier. The saveOrUpdate() method implements this functionality.
// in the first sessionCat cat = (Cat) firstSession.load(Cat.class, catID);// in a higher tier of the applicationCat mate = new Cat();cat.setMate(mate);// later, in a new sessionsecondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)
There are three standard, or built-in, choices:
org.hibernate.transaction.JDBCTransactionFactory
- delegates to database (JDBC) transactions (default)
org.hibernate.transaction.JTATransactionFactory
- delegates to container-managed transactions if an existing transaction is underway in this context (for example, EJB session bean method). Otherwise, a new transaction is started and bean-managed transactions are used.
org.hibernate.transaction.CMTTransactionFactory
- delegates to container-managed JTA transactions
Hibernate | EJB 3.0 |
---|---|
Session–Cache or collection of loaded objects relating to a single unit of work | Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit |
XDoclet Annotations used to support Attribute Oriented Programming | Java 5.0 Annotations used to support Attribute Oriented Programming |
Defines HQL for expressing queries to the database | Defines EJB QL for expressing queries |
Supports Entity Relationships through mapping files and annotations in JavaDoc | Support Entity Relationships through Java 5.0 annotations |
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API | Provides and Entity Manager Interface for managing CRUD operations for an Entity |
Provides callback support through lifecycle, interceptor, and validatable interfaces | Provides callback support through Entity Listener and Callback methods |
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships | Entity Relationships are bidirectional or unidirectional |
JDBC | Hibernate |
---|---|
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. | Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. |
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. | Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. |
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. | Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application. |
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. | Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties. |
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. | Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost. |
With JDBC, caching is maintained by hand-coding. | Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. |
In JDBC there is no check that always every user has updated data. This check has to be added by the developer. | Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data. |