Sunday, January 11, 2009

Hibernate Interview Questions

Q. What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent
perseverance of objects in a Java application in to the tables of a relational database using
the metadata that describes the mapping between the objects and the database. It works
by transforming the data from one representation to another.

Q). What is Hibernate?

Hibernate is a powerful, high performance object/relational persistence and query service.
This lets the users to develop persistent classes following object-oriented principles such
as association, inheritance, polymorphism, composition, and collections.

Q)What object states Hibernate defines and supports ?

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. Transient instances will be destroyed by the garbage collector if the application doesn't hold a reference anymore.

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.

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.

Q)What is lazy fetching in Hibernate?

Lazy fetching decides whether to load child objects while loading the Parent Object.

You need to do this setting respective hibernate mapping file of the parent class.
Lazy = true (means not to load child)
By default the lazy loading of the child objects is true.
This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object
.But in some cases you do need to load the child objects when parent is loaded.
Just make the lazy=false and hibernate will load the child when parent is loaded from the database.

Q)how to create primary key using hibernate?

generator class="increment"

increment :: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
identity :: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence :: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
native :: It picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned :: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no generator element is specified.

Q. How will you configure Hibernate?

The configuration files hibernate.cfg.xml (or 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 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 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?

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 the difference between , session.saveOrUpdate() and session.persist()? : Save does an insert and will fail if the primary key is already persistent.

session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update.
Insert data if primary key not exist otherwise update data.

session.persist() : Does the same like
But return Serializable object but session.persist() return void. returns the generated identifier (Serializable object) and session.persist() doesn't.
Example :

This will print the generated primary key.
Compile time error because session.persist() return void.

Q. What are the benefits of detached objects?

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 Advantages and DisAdvantages of detached objects?

• 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.


• 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. What is the file extension you use for hibernate mapping file?
The name of the file should be like this : filename.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this

Q. How do you create a SessionFactory?
Configuration cfg = new Configuration();
cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();
First, we need to create an instance of Configuration and use that instance to refer to the
location of the configuration file. After configuring this instance is used to create the
SessionFactory by calling the method buildSessionFactory().

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 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.

Q. What are POJOs?

POJO stands for plain old java objects. These are just basic JavaBeans that have defined
setter and getter methods for all the properties that are there in that bean. Besides they
can also have some business logic related to that property. Hibernate applications works
efficiently with POJOs rather then simple java classes.

Q. What is object/relational mapping metadata?

ORM tools require a metadata format for the application to specify the mapping between
classes and tables, properties and columns, associations and foreign keys, Java types and
SQL types. This information is called the object/relational mapping metadata. It defines
the transformation between the different data type systems and relationship

Q. What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to express queries
in its own portable SQL extension and this is called as HQL. It also allows the user to
express in native SQL.

Q. What are managed associations and hibernate associations?
Associations that are related to container management persistence are called managed
associations. These are bi-directional associations. Coming to hibernate associations,
these are unidirectional.

Q. Where should SessionFactory be placed so that it can be easily accessed?
As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI
then it can be easily accessed and shared between different threads and various
components that are hibernate aware. You can set the SessionFactory to a JNDI by
configuring a property hibernate.session_factory_name in the file.

No comments:

Post a Comment

Your Ad Here ]]>