Thursday, June 19, 2008

Hibernate

What is Hibernate?


Hibernate is a powerful, high performance object/relational persistence and query service.It is an open-source technology which fits well both with Java and .NET technologies.Hibernate lets developers write persistence classes with hibernate query features of HQL within principles of Object Oriented paradigm.It means one can include association,inheritance,polymorphism,composition and collection of these persisting objects to build applications.

Hibernate Architecture

The main objective of Hibernate is to relieve the developers from manual handling of SQLs,JDBC APIs for resultsets handling and it helps in keeping your data portable to various SQL databases,just by switching the delegate and driver details in hibernate.cfg.xml file.
Hibernate offers sophisticated query options, you can write plain SQL, object-oriented HQL (Hibernate Query Language), or create programmatic criteria and example queries. Hibernate can optimize object loading all the time, with various fetching and caching options.
Some snapshots of Hibernate:
-Free open source
-OO Concepts can be implemented.
-A rich variety of mappings for collections and dependent objects
-No extra code generation or bytecode processing steps in your build procedure
-Great performance, has a dual-layer cache architecture, and may be used in a cluster
-Its own query language support
-Efficient transaction handling
-The Java Persistence API is the standard object/relational mapping and persistence management interface of the Java EE 5.0 platform which are implemented with the Hibernate Annotations and Hibernate EntityManager modules, on top of the Hibernate Core.(As part of EJB3.0 spec)

Why Hibernate?


The reasons are plenty,weighing in favor of Hibernate clearly.
-Cost effective.Just imagine when you are using EJBs instead of Hibernate.One has to invest in Application Server(Websphere,Weblogic etc.),learning curve for EJB is slow and requires special training if your developers are not equipped with the EJB know-how.
-The developers get rid of writing complex SQLs and no more need of JDBC APIs for resultset handling.Even less code than JDBC.In fact the OO developers work well when they have to deal with object then writing lousy queries.
-High performance then EJBs(if we go by their industry reputation),which itself a container managed,heavyweight solution.
-Switching to other SQL database requires few changes in Hibernate configuration file and requires least clutter than EJBs.
-EJB itself has modeled itself on Hibernate principle in its latest version i.e. EJB3 because of apparent reasons.

What is ORM ?


Object Relational Mapping(ORM) is a technique/solution that provides an object-based view of data to applications which it can manipulate.The basic purpose of ORM is to allow an application written in an object oriented language to deal with the information it manipulates in terms of objects, rather than in terms of database-specific concepts such as rows, columns and tables.

In the Java world, ORM's first appearance was under the form of entity beans. But entity beans have limited scope in Java EE domain,they can not be exploited for Java SE based applications.The mapping of class lever attributes is done to table columns.For example a String variabe of a class will directly map onto a VARCHAR column. A relationship mapping is the one that you use when you have an attribute of a class that holds a reference to an instance of some other class in your domain model. The most common types of relationship mappings are "one to one", "one to many" or "many to many".

What are core interfaces for Hibernate framework?


Most Hibernate-related application code primarily interacts with four interfaces provided by Hibernate Core:

org.hibernate.Session
org.hibernate.SessionFactory
org.hibernate.Criteria
org.hibernate.Query

The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not thread safe.

The application obtains Session instances from a SessionFactory. SessionFactory instances are not lightweight and typically one instance is created for the whole application. If the application accesses multiple databases, it needs one per database.

The Criteria provides a provision for conditional search over the resultset.One can retrieve entities by composing Criterion objects. The Session is a factory for Criteria.Criterion instances are usually obtained via the factory methods on Restrictions.
Query represents object oriented representation of a Hibernate query. A Query instance is obtained by calling Session.createQuery().

What is dirty checking in Hibernate?


Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. An important note here is, Hibernate will compare objects by value, except for Collections, which are compared by identity. For this reason you should return exactly the same collection instance as Hibernate passed to the setter method to prevent unnecessary database updates.

What are different fetch strategies Hibernate have?


A fetching strategy in Hibernate is used for retrieving associated objects if the application needs to navigate the association. They may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

Hibernate3 defines the following fetching strategies:

Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.

Hibernate also distinguishes between:
Immediate fetching - an association, collection or attribute is fetched immediately, when the owner is loaded.

Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)

"Extra-lazy" collection fetching - individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections)

Proxy fetching - a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object.

"No-proxy" fetching - a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is accessed) but more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.

Lazy attribute fetching - an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.

We use fetch to tune performance. We may use lazy to define a contract for what data is always available in any detached instance of a particular class.

[Source:Hibernate Reference Documentation]

Can you compare JDBC/DAO with Hibernate?


Hibernate and straight SQL through JDBC are different approaches.They both have their specific significance in different scenarios.If your application is not to big and complex,not too many tables and queries involved then it will be better to use JDBC. While Hibernate is a POJO based ORM tool,using JDBC underneath to connect to database, which lets one to get rid of writing SQLs and associated JDBC code to fetch resultset,meaning less LOC but more of configuration work.It will suit better when you have large application involving large volume of data and queries.Moreover lazy loading,caching of data helps in having better performance and you need not call the database every time rather data stays in object form which can be reused.

Explain different inheritance mapping models in Hibernate.


There can be three kinds of inheritance mapping in hibernate

1. Table per concrete class with unions
2. Table per class hierarchy
3. Table per subclass

Example:
We can take an example of three Java classes like Vehicle, which is an abstract class and two subclasses of Vehicle as Car and UtilityVan.

1. Table per concrete class with unions
In this scenario there will be 2 tables
Tables: Car, UtilityVan, here in this case all common attributes will be duplicated.

2. Table per class hierarchy
Single Table can be mapped to a class hierarchy
There will be only one table in database named 'Vehicle' which will represent all attributes required for all three classes.
Here it is be taken care of that discriminating columns to differentiate between Car and UtilityVan

3. Table per subclass
Simply there will be three tables representing Vehicle, Car and UtilityVan
Q. How will you configure Hibernate?

Answer:

The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

• hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

• Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.


Q. What is a SessionFactory? Is it a thread-safe object?

Answer:

SessionFactory is Hibernate’s concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();


Q. What is a Session? Can you share a session object between different theads?

Answer:

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.


public class HibernateUtil {

public static final ThreadLocal local = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
local.set(session);
}
return session;
}
}

It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy.


Q. What are the benefits of detached objects?

Answer:


Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

Q. What are the pros and cons of detached objects?

Answer:

Pros:

• When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.


Cons

• In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.

• Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.


Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?

Answer

• Hibernate uses the “version” property, if there is one.
• If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
• Write your own strategy with Interceptor.isUnsaved().

Q. What is the difference between the session.get() method and the session.load() method?

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(…) returns null.


Q. What is the difference between the session.update() method and the session.lock() method?

Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?

You can use the session.merge() method call.


Q. What are the general considerations or best practices for defining your Hibernate persistent classes?


1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.

2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.


3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.

4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.

5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.


How can I count the number of query results without actually returning them?

Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();

How can I find the size of a collection without initializing it?

Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult();

How can I order by the size of a collection?

Use a left join, together with group by

select user
from User user
left join user.messages msg
group by user
order by count(msg)

How can I place a condition upon a collection size?

If your database supports subselects:

from User user where size(user.messages) >= 1

or:

from User user where exists elements(user.messages)

If not, and in the case of a one-to-many or many-to-many association:

select user
from User user
join user.messages msg
group by user
having count(msg) >= 1

Because of the inner join, this form can't be used to return a User with zero messages, so the following form is also useful

select user
from User as user
left join user.messages as msg
group by user
having count(msg) = 0

How can I query for entities with empty collections?

from Box box
where box.balls is empty

Or, try this:

select box
from Box box
left join box.balls ball
where ball is null

How can I sort / order collection elements?

There are three different approaches:

1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or or . This solution does a sort in memory.

2. Specify an order-by attribute of , or , naming a list of table columns to sort by. This solution works only in JDK 1.4+.

3. Use a filter session.createFilter( collection, "order by ...." ).list()

Are collections pageable?

Query q = s.createFilter( collection, "" ); // the trivial filter
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();

I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bugprone. Is there a better way?


parent

I have a many-to-many association between two tables, but the association table has some extra columns (apart from the foreign keys). What kind of mapping should I use?

Use a composite-element to model the association table. For example, given the following association table:

create table relationship (
fk_of_foo bigint not null,
fk_of_bar bigint not null,
multiplicity smallint,
created date )

you could use this collection mapping (inside the mapping for class Foo):









You may also use an with a surrogate key column for the collection table. This would allow you to have nullable columns.

An alternative approach is to simply map the association table as a normal entity class with two bidirectional one-to-many associations.

In an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them?

One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a servlet filter (another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.

Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds.

How can I bind a dynamic list of values into an in query expression?

Query q = s.createQuery("from foo in class Foo where foo.id in (:id_list)");
q.setParameterList("id_list", fooIdList);
List foos = q.list();

How can I bind properties of a JavaBean to named query parameters?

Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();

Can I map an inner class?

You may persist any static inner class. You should specify the class name using the standard form ie. eg.Foo$Bar

How can I assign a default value to a property when the database column is null?

Use a UserType.

How can I trucate String data?

Use a UserType.

How can I trim spaces from String data persisted to a CHAR column?

Use a UserType.

How can I convert the type of a property to/from the database column type?

Use a UserType.

How can I get access to O/R mapping information such as table and column names at runtime?

This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory.

How can I create an association to an entity without fetching that entity from the database (if I know the identifier)?

If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECT statement:

Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);

How can I retrieve the identifier of an associated object, without fetching the association?

Just do it. The following code does not result in any SELECT statement, even if the item association is lazy.

Long itemId = bid.getItem().getId();

This works if getItem() returns a proxy and if you mapped the identifier property with regular accessor methods. If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This method is then treated like any other business method of the proxy, initialization is required if it is called.

How can I manipulate mappings at runtime?

You can access (and modify) the Hibernate metamodel via the Configuration object, using getClassMapping(), getCollectionMapping(), etc.

Note that the SessionFactory is immutable and does not retain any reference to the Configuration instance, so you must re-build it if you wish to activate the modified mappings.

How can I avoid n+1 SQL SELECT queries when running a Hibernate query?

Follow the best practices guide! Ensure that all and mappings specify lazy="true" in Hibernate2 (this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations you need to be retrieved in the initial SQL SELECT.

A second way to avoid the n+1 selects problem is to use fetch="subselect" in Hibernate3.

If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.

I have a collection with second-level cache enabled, and Hibernate retrieves the collection elements one at a time with a SQL query per element!

Enable second-level cache for the associated entity class. Don't cache collections of uncached entity types.

How can I insert XML data into Oracle using the xmltype() function?

Specify custom SQL INSERT (and UPDATE) statements using and in Hibernate3, or using a custom persister in Hibernate 2.1.

You will also need to write a UserType to perform binding to/from the PreparedStatement.

How can I execute arbitrary SQL using Hibernate?

PreparedStatement ps = session.connection().prepareStatement(sqlString);

Or, if you wish to retrieve managed entity objects, use session.createSQLQuery().

Or, in Hibernate3, override generated SQL using , , and in the mapping document.

I want to call an SQL function from HQL, but the HQL parser does not recognize it!

Subclass your Dialect, and call registerFunction() from the constructor.


More Hibernate Questions



Question: What are common mechanisms of configuring Hibernate?
Answer: 1. By placing hibernate.properties file in the classpath.
2. Including elements in hibernate.cfg.xml in the classpath.

Question:How can you create a primary key using Hibernate?
Answer: The 'id' tag in .hbm file corresponds to primary key of the table:

Here Id ="empid", that will act as primary key of the table "EMPLOYEE".

Question: In how many ways one can map files to be configured in Hibernate?
Answer: 1. Either mapping files are added to configuration in the application code or,
2.hibernate.cfg.xml can be used for configuring in .

Question: How to set Hibernate to log all generated SQL to the console?
Answer: By setting the hibernate.show_sql property to true.

Question: What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?
Answer: The settings of the XML configuration file will override the settings used in the properties.

Question: What methods must the persistent classes implement in Hibernate?
Answer: Since Hibernate instantiates persistent classes using Constructor.newInstance(), it requires a constructor with no arguments for every persistent class. And getter and setter methods for all the instance variables.

Question: How can Hibernate be configured to access an instance variable directly and not through a setter method?
Answer: By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

Question: How to declare mappings for multiple classes in one mapping file?
Answer:Use multiple elements. But, the recommended practice is to use one mapping file per persistent class.

Question: How are the individual properties mapped to different table columns?
Answer: By using multiple elements inside the element.

Question: What are derived properties?
Answer: The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

Question: How can you make a property be read from the database but not modified in anyway (make it immutable)?
Answer: Use insert="false" and update="false" attributes.

Question: How can a whole class be mapped as immutable?
Answer: By using the mutable="false" attribute in the class mapping.

1 comment:

Anonymous said...

I get conflicting answers for the question below, and as I don't know the answer I was wonder if someone could clarify.

Question : How can you make a property be read from the database but not modified in anyway?
Select only one correct option from following options.
(OPTION 1)By using the insert="false" and update="false" attributes.
(OPTION 2)By using the isinsert="false" and isupdate="false" attributes.
(OPTION 3)By using the isinsert="no" and isupdate="no" attributes.
(OPTION 4)ReadOnly database property not supported by hibernate configuration


you guys say (OPTION 1) but my other sources say (OPTION 2)

how confidnent are you about (OPTION 1)?

Topics