Select Category 
 

Hibernate Interview Questions Answers

Hibernate Interview Question - 1 : -

How will you configure Hibernate?

Hibernate Interview Answer - 1 : -

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.

 

Hibernate Interview Question - 2 : -

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

Hibernate Interview Answer - 2 : -

Use a UserType.
 

Hibernate Interview Question - 3 : -

Does Hibernate implement its functionality using a minimal number of database queries?

Hibernate Interview Answer - 3 : -

Hibernate can make certain optimizations all the time:

Caching objects. The session is a transaction-level cache of persistent objects. You may also enable a JVM-level/cluster cache to memory and/or local disk.
Executing SQL statements later, when needed. The session never issues an INSERT or UPDATE until it is actually needed. So if an exception occurs and you need to abort the transaction, some statements will never actually be issued. Furthermore, this keeps lock times in the database as short as possible (from the late UPDATE to the transaction end).
Never updating unmodified objects. It is very common in hand-coded JDBC to see the persistent state of an object updated, just in case it changed.....for example, the user pressed the save button but may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work.
Efficient Collection Handling. Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed.
Rolling two updates into one. As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement.
Updating only the modified columns. Hibernate knows exactly which columns need updating and, if you choose, will update only those columns.
Outer join fetching. Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations.
Lazy collection initialization.
Lazy object initialization. Hibernate can use runtime-generated proxies (CGLIB) or interception injected through bytecode instrumentation at build-time.
A few more (optional) features of Hibernate that your handcoded JDBC may or may not currently benefit from

second-level caching of arbitrary query results, from HQL, Criteria, and even native SQL queries
efficient PreparedStatement caching (Hibernate always uses PreparedStatement for calls to the database)
JDBC 2 style batch updates
Pluggable connection pooling
Hopefully you will agree that Hibernate approaches the parsimony of the best hand-coded JDBC object persistence. As a subscript I would add that I have rarely seen JDBC code that approaches the efficiency of the "best possible" code. By co

 

Hibernate Interview Question - 4 : -

How do I use Hibernate in an EJB 2.1 session bean?

Hibernate Interview Answer - 4 : -

1. Look up the SessionFactory in JNDI.
2. Call getCurrentSession() to get a Session for the current transaction.

3. Do your work.

4. Don't commit or close anything, let the container manage the transaction.

 

Hibernate Interview Question - 5 : -

What is Middlegen?

Hibernate Interview Answer - 5 : -

Middlegen is an open source code generation framework that provides a general-purpose database-driven engine using various tools such as JDBC, Velocity, Ant and XDoclet.
 

Hibernate Interview Question - 6 : -

How can I sort / order collection elements?

Hibernate Interview Answer - 6 : -

There are three different approaches:

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

2. Specify an order-by attribute of <set>, <map> or <bag>, 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()

 

 

Hibernate Interview Question - 7 : -

How can I order by the size of a collection?

Hibernate Interview Answer - 7 : -

Use a left join, together with group by

select user from User userleft join user.messages msggroup by user order by count(msg)

 

Hibernate Interview Question - 8 : -

How can I query for entities with empty collections?

Hibernate Interview Answer - 8 : -

from Box boxwhere box.balls is empty
Or, try this:

select boxfrom Box box   left join box.balls ballwhere ball is null

 

Hibernate Interview Question - 9 : -

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

Hibernate Interview Answer - 9 : -

Use a UserType.
 

Hibernate Interview Question - 10 : -

How can I trucate String data?

Hibernate Interview Answer - 10 : -

Use a UserType.
 

Hibernate Interview Question - 11 : -

What is hybernate in Java?

Hibernate Interview Answer - 11 : -

Hibernate is an 'Object-Relational Mapping' library.

Basically it allows you to define objects in Java that map to tables or views (or other structures) of a relational database.

In Java you work with the objects defined, and they provide the service of interacting with the database - CRUD (create/read/update/delete).

 

Hibernate is an Object Relational mapping tool. One of the things it
does is convert data from relational tables to objects. I think what you
are implying is why just Java objects, why not objects in other languages.
For .Net, I believe there is another framework: nhibernate. However, I
have not used nHibernate

 

This is an example of how to handle a major 'impedance mismatch' between two separate worlds. The traditional RDBMS technology precedes Java, and is independent of it. It is oriented toward a storage approach that is not object oriented, although BLOBs and similary binary type content CAN be stored in most mainstream databases now. The Hibernate project does translation between the two worlds.

 

Hibernate Interview Question - 12 : -

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

Hibernate Interview Answer - 12 : -

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.

 

Hibernate Interview Question - 13 : -

Are collections pageable?

Hibernate Interview Answer - 13 : -

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

Hibernate Interview Question - 14 : -

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

Hibernate Interview Answer - 14 : -

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.
 

Hibernate Interview Question - 15 : -

Can I map an inner class?

Hibernate Interview Answer - 15 : -

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