Friday, December 25, 2009

Hibernate

The ORM levels are:
• Pure relational (stored procedure.)
• Light objects mapping (JDBC)
• Medium object mapping
• Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration file

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:


Core interfaces are of Hibernate framework
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces

Session interface play in Hibernate?

It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession()

SessionFactory interface play in Hibernate?
The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization.

SessionFactory sessionFactory = configuration.buildSessionFactory();

The general flow of Hibernate communication with RDBMS is :
• 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
HQL?
The Hibernate query Language (HQL), is an object-oriented extension to SQL.

Following are the important tags of hibernate.cfg.xml:


How do you map Java Objects with Database tables?
• First we need to write Java domain objects (beans with setter and getter).
• Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :


name="userName" not-null="true" type="java.lang.String"/>
name="userPassword" not-null="true" type="java.lang.String"/>



load() vs. get() :-
load() get()
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods.
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get() will hit the database immediately.




What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

What do you mean by Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:


SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name


Invoke Named Query :
List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();

How do you invoke Stored Procedures?







{ ? = call selectAllEmployees() }


What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
o HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
o Common functions are simplified to single method calls.
o Sessions are automatically closed.
o Exceptions are automatically caught and converted to runtime exceptions.








Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();

sorted collection vs. order collection :-
sorted collection order collection
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .

What are the types of Hibernate instance states ?
Three types of instance states:
• Transient -The instance is not associated with any persistence context
• Persistent -The instance is associated with a persistence context
• Detached -The instance was associated with a persistence context which has been closed – currently not associated
Configuration conf=new Configuration();
conf.addFile(“hibernate.cfg.xml”);
SessionFactory factory=conf.configure().buildSessionFactory();
Customer cus=new Customer();
Session ses=factory.openSession();
Transaction tx=ses.begintransaction();
ses.save(cus);
tx,commit();













Usually update() or saveOrUpdate() are used in the following scenario:
o the application loads an object in the first session
o the object is passed up to the UI tier
o some modifications are made to the object
o the object is passed back down to the business logic tier
o the application persists these modifications by calling update() in a second session
saveOrUpdate() does the following:
o if the object is already persistent in this session, do nothing
o if another object associated with the session has the same identifier, throw an exception
o if the object has no identifier property, save() it
o if the object's identifier has the value assigned to a newly instantiated object, save() it
o if the object is versioned by a or , and the version property value is the same value assigned to a newly instantiated object, save() it
o otherwise update() the object
and merge() is very different:
o if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
o if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
o the persistent instance is returned
o the given instance does not become associated with the session, it remains detached





























Core interfaces are of hibernate framework:
i. Session Interface – This is the primary interface used by hibernate applications. The instances of thisinterface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
ii. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all theapplication threads.
iii. Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of thisinterface is used by the application in order to specify the location of hibernate specific mapping documents.
iv. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
v. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.
Criteria queries
HQL is extremely powerful, but some developers prefer to build queries dynamically using an object-oriented API, rather than building query strings. Hibernate provides an intuitive Criteria query API for these cases:
Criteria crit = session.createCriteria(Cat.class);
crit.add( Restrictions.eq( "color", eg.Color.BLACK ) );
crit.setMaxResults(10);
List cats = crit.list();
Connection pools are a common way to improve application performance. Rather than opening a separate connection to the database for each request, the connection pool maintains a collection of open database
connections that are reused

How to Config c3p0 connection pool?
hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc: postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50

First-level cache:
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
Second-level cache:
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.

Cache Implementations.
• EHCache.
• OSCache.
• SwarmCache.
• JBoss TreeCache.
Caching Strategies:
• Read-only.
• Read-Write.
• Nonstriict read-write.
• Transactional.
Cache Read-only Nonstrict Read/write Read/write Transactional
EHCache Yes Yes Yes No
OSCache Yes Yes Yes No
SwarmCache Yes Yes No No
JBoss TreeCache Yes No No Yes

Four levels defined for ORM quality:
i. Pure relational
ii. Light object mapping
iii. Medium object mapping
iv. Full object mapping
Pure Relational ORM:
The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

Light Object Mapping:
The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

Medium Object Mapping:
The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

Full Object Mapping:
Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application

Benefits of ORM and Hibernate:
i. Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
ii. Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.
iii. Performance – Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing theperformance. If it is automated persistence then it still increases the performance.
iv. Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application
Method chaining:
Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code
SessionFactory sessions = new Configuration()
.addResource("myinstance/MyConfig.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();

Extension Interfaces
Hibernate offers a range of optional extension interfaces you can implement to customize the behavior of your persistence layer
Extension interfaces that are there in hibernate:
• ProxyFactory interface - used to create proxies
• ConnectionProvider interface – used for JDBC connection management
• TransactionFactory interface – Used for transaction management
• Transaction interface – Used for transaction management
• TransactionManagementLookup interface – Used in transaction management.
• Cahce interface – provides caching techniques and strategies
• CacheProvider interface – same as Cache interface
• ClassPersister interface – provides ORM strategies
• IdentifierGenerator interface – used for primary key generation
Fetching Strategy?
● A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the
application needs to navigate the association.
● Fetching strategy will have performance impact
● Fetch strategies may be declared in the mapping files, or over-ridden by a particular
HQL or Criteria query.

How fetching is done
– Join
– Select (default)
– Subselect
– Batch

● When fetching is done
– immediate
– lazy (default)

Hibernate retrieves the associated instance or collection in the same SELECT, using an
OUTER JOIN

Join Fetching in HQL:
String hql = "from Product p join fetch p.supplier as s";
Query query = session.createQuery(hql);
List results = query.list();

Join Fetching in Criteria API:
Criteria crit = session.createCriteria(Product.class);
crit.setFetchMode("supplier", FetchMode.JOIN);
List results = crit.list();

Generator class:
The optional child element names a Java class used to generate unique identifiers for instances of the persistent class.
Ex;increment ,identity, sequence, hilo, seqhilo, uuid, guid, Native,Assigned, select, foreign, sequence-identity
Three basic inheritance mapping strategies:
o table per class hierarchy
o table per subclass
o table per concrete class

Pagination
If you need to specify bounds upon your result set, that is, the maximum number of rows you want to retrieve and/or the first row you want to retrieve, you can use methods of the Query interface:
Query q = sess.createQuery("from DomesticCat cat");
q.setFirstResult(20);
q.setMaxResults(10);
List cats = q.list();


Many-to-one associations use foreign keys to maintain
the association between two persistent classes

Cascade
cascade="none", the default, tells Hibernate to ignore the association.
all—All operations are passed to child entities: save, update, and delete.
save-update—Save and update (INSERT and UPDATE, respectively) are passed to child entities.
delete—Deletion operations are passed to child entities.
delete-orphan—All operations are passed to child entities, and objects no longer associated with the parent object are deleted.
all-delete-orphan" means the same as cascade="all" but, in addition, Hibernate deletes any persistent entity instance that has been removed (dereferenced) from the association

Transactions group many operations into a single unit of work. If any operation in the batch fails, all of the previous operations are rolled back, and the unit of work stops.

Components allow you to take several columns and group them into a single object

























EHCache (Easy Hibernate Cache) (org.hibernate.cache.EhCacheProvider)
• It is fast.
• lightweight.
• Easy-to-use.
• Supports read-only and read/write caching.
• Supports memory-based and disk-based caching.
• Does not support clustering.
OSCache (Open Symphony Cache) (org.hibernate.cache.OSCacheProvider)
• It is a powerful .
• flexible package
• supports read-only and read/write caching.
• Supports memory- based and disk-based caching.
• Provides basic support for clustering via either JavaGroups or JMS.
SwarmCache (org.hibernate.cache.SwarmCacheProvider)
• is a cluster-based caching.
• supports read-only or nonstrict read/write caching .
• appropriate for applications those have more read operations than write operations.
JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)
• is a powerful replicated and transactional cache.
• useful when we need a true transaction-capable caching architecture .
Caching Stringategies
Important thing to remembered while studying this one is none of the cache providers support all of the cache concurrency strategies.
3.1) Read-only
• Useful for data that is read frequently but never updated.
• It is Simple .
• Best performer among the all.
Advantage if this one is, It is safe for using in a cluster. Here is an example for using the read-only cache strategy.



....

3.2) Read-Write
• Used when our data needs to be updated.
• It’s having more overhead than read-only caches.
• When Session.close() or Session.disconnect() is called the transaction should be completed in an environment where JTA is no used.
• It is never used if serializable transaction isolation level is required.
• In a JTA environment, for obtaining the JTA TransactionManager we must specify the propertyhibernate.transaction.manager_lookup_class.
• To use it in a cluster the cache implementation must support locking.
Here is an example for using the read-write cache stringategy.



….


….


3.3) Nonstrict read-write
• Needed if the application needs to update data rarely.
• we must specify hibernate.transaction.manager_lookup_class to use this in a JTA environment .
• The transaction is completed when Session.close() or Session.disconnect() is called In other environments (except JTA) .
Here is an example for using the nonstrict read-write cache stringategy.



….

3.4) Transactional
• It supports only transactional cache providers such as JBoss TreeCache.
• only used in JTA environment.

1 comment:

  1. Ehcache has a super fast and coherent clustering layer built on Terracotta.

    ReplyDelete