Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts
Tuesday 27 August 2013
Sunday 25 August 2013
Wednesday 21 August 2013
Top Most Difference between get and load in Hibernate
get vs load in Hibernate
Difference between get and load method in Hibernate is a one of the most popular question asked in Hibernate and spring interviews. Hibernate Session class provides two method to access object e.g. session.get() and session.load() both looked quite similar to each other but there are subtle difference between load and get method which can affect performance of application. Main difference between get() vs load method is that get() involves database hit if object doesn't exists in Session Cache and returns a fully initialized object which may involve several database call while load method can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object. This lazy initialization can save couple of database round-trip which result in better performance. By the way there are many articles on interview questions in Java, you can use search button on top left to find them. Some of them like 20 design pattern interview questions and 10 Singleton pattern questions are my favorites, you may also like. Coming back to article, you can find more difference between load and get in rest of this article in point format but this is the one which really makes difference while comparing both of them. If you look at how get and load gets called its pretty identical.
Labels:
core java interview question,
Hibernate
Wednesday 14 August 2013
Top Most Difference between save vs persist and saveOrUpdate in Hibernate
Save vs saveOrUpdate vs persist in Hibernate
What is difference between save and saveOrUpdate or Difference between save and persist are common interview question in any Hibernate interview, much like Difference between get and load method in Hibernate. Hibernate Session class provides couple of ways to save object into database by methods like save, saveOrUpdate and persist. You can use either save(), saveOrUpdate() or persist() based upon your requirement for persisting object into Database. Along with Spring framework Interview questions, Hibernate questions are also quite popular on J2EE interviews because of its status as leading ORM. It’s good to prepare some questions from Hibernate before appearing in any J2EE interviews. One of them is Difference between save , saveOrUpdate and persist, which we will see in this Hibernate article.
Labels:
Hibernate,
interview questions,
J2EE,
Java
Monday 12 August 2013
Top Most Hibernate Interview Preparation Question and Their Answers.
I have compile from internet So if you problem regarding answers then please go through Hibernate documentation.
1) Adv/Disadvantages of Hibernate:
a) Object – Relational mapping
b) The developer doesn’t have to take into account the type of database he is coding for. The type of database can be changed by changing the dialect line in the configuration file.
c) Hibernate has caching.
d) Need to write less complex queries.
e) One has the choice as to how he wants the related objects of the object he wants to be loaded. (Fetching and join strategy)
f) Connection Pooling can be done by editing a few lines in the hibernate-cfg.xml file ..
c3p0 :- connection pool built in with Hibernate
hibernate.connection.driver_class=com.mysql.jdbc.Driverhibernate.connection.url=jdbc:mysql://localhost/hibernatehibernate.connection.username=roothibernate.connection.password= hibernate.dialect=net.sf.hibernate.dialect.MySQLDialecthibernate.show_sql=false
hibernate.c3p0.max_size=1hibernate.c3p0.min_size=0hibernate.c3p0.timeout=5000hibernate.c3p0.max_statements=100hibernate.c3p0.idle_test_period=300hibernate.c3p0.acquire_increment=2
Disadvantages:
slower in processing the queries than if the queries are used directly
adding the xml would cause portability problems
2) Explain Session Factory?
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
3) Explain different type of fetch statements?
Fetching strategy is used by hibernate to retrieve associated objects if the Hibernate needs to go through to the association.
There are 4 types of fetching strategies:
fetch = join
Using the same ‘select’ statement the Hibernate will fetch the associated instance/ collection using outer join.
fetch = select
This is the default option. If there are ‘n’ associated objects to the one you requested then there would be ‘n+1′ select statements executed. If the lazy=true then these would executed only when the association is required.
fetch = subselect
A second select statement would be used to get all the related objects. If the lazy=true then this second select statement would be executed only when the association is called.
fetch=batch
It is an optimization strategy for fetch=select , where in using a list of primary or foreign keys one would pull out all instances/collection in a single select.
4) Explain lazy loading?
5) Explain object states?
Transient
Persistent
Detached:
Detached objects have a representation in database but changes done to the object won’t be reflected to the database. A detached objects can be created by closing the session or by using the evict method of the session on the object. In order to reflect the changes in the object to the database the load,refresh,merge,update or save method on the object in any session.
6) Performance metrics in Hibernate?
sessionFactory.getStatistics
7) 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
8) Explain caching in Hibernate
Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. This article focuses on second-level cache. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.
In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects.
Each cache provides different capacities in terms of performance, memory use, and configuration possibilities:
• EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
• OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
• SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
• JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Another cache implementation worth mentioning is the commercial Tangosol Coherence cache.
Caching Strategies
Once you have chosen your cache implementation, you need to specify your access strategies. The following four caching strategies are available:
• Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
• Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
• Nonstrict read/write: This strategy does not guarantee that two transactions won’t simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
• Transactional: This is a fully transactional cache that may be used only in a JTA environment.
9) Proxy pattern in Hibernate:
When an object contains another object and the loading is lazy then when the main object is created then it contains only a refernce to the object it contains. This reference is the proxy of the object it contains and this pattern is called proxy patters.
10) Interfaces in Hibernate:
Configuration,Session,Transaction and SessionFactory
11) Light weight ,Medium Weight and Heavy Weight mapping:
There are four levels of Hibernate Quality:
Pure: Stored Procedures
Light: JDBC
Medium:
Heavy:composition,inheritance, polymorphism, persistence by reachability
12) Difference between Hibernate and Ibatis:
In Ibatis Results of the SQL queries are mapped to the Objects where as in Hibernate the table is mapped to the object. Ibatis would be faster as it making use of the queries directly and is useful when you personally don’t have much knowledge about the database.
13) What is NHibernate?
NHibernate is an Object Relational Mapping (ORM) solution for .Net.
14) Integrating Hibernate and Spring
A) Configure the SessionFactory in the ‘spring.xml’
<util:list id=”abc.MappingResources”>
<value>abcde/a.hbm.xml</value>
<value>abcde/b.hbm.xml</value>
</util:list>
<bean id=”core.commons.adm.SessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”
p:dataSource-ref=”data.source.DataSource”
p:mappingResources-ref=”abc.MappingResources”
p:hibernateProperties-ref=”abc.HibernateProperties”>
<property name=”jtaTransactionManager”>
<bean class=”org.springframework.jndi.JndiObjectFactoryBean”>
<property name=”jndiName”>
<value>javax.transaction.TransactionManager</value>
</property>
</bean>
</property>
</bean>
B) Configure the DataSource in the ‘spring.xml’
<bean id=“dataSource”
class=“org.springframework.jdbc.datasource.DriverManagerDataSource”>
<property name=“driverClassName”>
<value>org.hsqldb.jdbcDriver</value>
</property>
<property name=“url”>
<value>jdbc:hsqldb:mem:widgets</value>
</property>
<property name=“username”><value>sa</value></property>
<property name=“password”><value></value></property>
</bean>
C) Extend your DAO Implementation from HibernateDaoSupport
Spring can simplify your Hibernate application. Spring’s Hibernate integration uses the same generic transaction infrastructure and DAO exception hierarchy that it uses for JDBC, JDO, iBATIS, and TopLink, making it easy to mix and match persistence methodologies if necessary.
There are two approaches to Spring’s Hibernate integration:
1. Inversion of Control with a HibernateTemplate and Callback
2. Extending HibernateDaoSupport and Applying an AOP Interceptor
The IoC/HibernateTemplate methodology feels a lot like the JdbcTemplate methodology described in the last section. For this example, I will show the HibernateDaoSupport/AOP Interceptor approach.
After you have written your standard Hibernate mappings, there basically three things that you need to do to use Spring’s HibernateDaoSupport to implement a DAO:
1. Configure the Hibernate SessionFactory
2. Extend your DAO Implementation from HibernateDaoSupport
3. Wire in Transaction Support with AOP
So let’s do another implementation of the WidgetDAO using Hibernate. First of all, here is our Hibernate XML mapping for the Widget class:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zabada.springrecipes.model">
<class name="Widget" table="WIDGETS">
<id name="id" column="WIDGET_ID" type="long">
<generator class="native"/>
</id>
<property name="name" column="NAME" type="string"/>
<property name="size" column="SIZE" type="int"/>
</class>
</hibernate-mapping>
If you’ve used Hibernate before, there should be nothing tricky here since Widget is a trivial class (there are no collections or other classes to associate to). So now we can wire up the Hibernate SessionFactory
Configuring the Hibernate SessionFactory in Spring
Here is an example Hibernate SessionFactory configured in Spring. You will be using this instead of the typical hibernate-config.xml. All we are doing here is telling Hibernate/Spring what our Hibernate mapping files are:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>com/zabada/springrecipes/base/Widget.hbm.xml</value>
</list>
</property>
</bean>
If you have a hibernate.properties in your classpath, the Spring LocalSessionFactoryBean will use that file to configure the database connections, dialect and pooling. Alternatively, you can define a DataSource in Spring (any class that implements javax.sql.DataSource) and explicity set all of your Hibernate properties in the LocalSessionFactoryBean:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>com/zabada/springrecipes/base/Widget.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.HSQLDialect
</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>org.hsqldb.jdbcDriver</value>
</property>
<property name="url">
<value>jdbc:hsqldb:mem:widgets</value>
</property>
<property name="username"><value>sa</value></property>
<property name="password"><value></value></property>
</bean>
Extending HibernateDaoSupport for the Actual DAO Implementation
The Spring HibernateDaoSupport class provides all kinds of convenience methods for working with Hibernate. Most of these are accessible via the HibernateTemplate object that this class exposes.
Please note that Hibernate 2 throws checked HibernateExceptions and Hibernate 3 throws runtime exceptions. I am using Hibernate 3 and am blowing off runtime exceptions that might be thrown, but it might be more appropriate to deal with these exceptions here (this is just a example, not prduction code!)
Anyway, here is our WidgetDAO implemented by extending HibernateDaoSupport:
public class WidgetDAOHibernateImpl
extends HibernateDaoSupport
implements WidgetDAO
{
/**
* Returns a java.util.List of all Widgets in the system.
* @return
*/
public Collection getWidgets()
{
return getHibernateTemplate().loadAll(Widget.class);
}
/**
* Get a Widget Object given the id
* @param id
* @return
*/
public Widget getWidgetById(Long id)
{
return (Widget)
getHibernateTemplate().load(Widget.class, id);
}
/**
* Save a Widget Object, if the given Widget
* is not in the data store,it should insert it,
* if it is in the data store, it should update it.
* @param widget
*/
public Widget saveWidget(Widget widget)
{
getHibernateTemplate().saveOrUpdate(widget);
return widget;
}
}
Using AOP to Wire Up the DAO and Transaction Management
Now we wire up our DAO and weave in the HibernateInterceptor. This interceptor binds a new Hibernate Session to the thread before a method call, closing and removing it afterwards in case of any method outcome. If there already is a pre-bound Session, the interceptor simply participates in it. Note that the actual “widgetDAO” bean is defined as a proxy bean that really points to a bean called “widgetDaoTarget” which is where we wire up our actual implementation.
<!-- THE HIBERNATE INTERCEPTOR -->
<bean id="hibernateInterceptor"
class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="widgetDaoTarget"
class="com.zabada.springrecipes.hibernate.WidgetDAOHibernateImpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="widgetDAO"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.zabada.springrecipes.base.WidgetDAO</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
<value>widgetDaoTarget</value>
</list>
</property>
</bean>
Hibernate isn't just a popular kid on the block, however; it is actually a very powerful, consistent, and reliable database mapping tool. Mapping between objects in Java to relational databases has many facets that you must be aware of. Hibernate does a particularly good job of making the process simple to start, and providing the facilities to allow it to scale well and meet exceedingly complex mapping demands.
One of the primary concerns of mappings between a database and your Java application is performance. One of the common concerns of people who haven't spent much time working with Hibernate in particular, is that O/R mapping tools will limit your ability to make performance-enhancing changes to particular queries and retrievals. Today I want to discuss two facets of the Hibernate infrastructure that are implemented to handle certain performance concerns - the second-level cache and the query cache.
The Second Level Cache
The second-level cache is called 'second-level' because there is already a cache operating for you in Hibernate for the duration you have a session open. From the Hibernate documentation:
A Hibernate Session is a transaction-level cache of persistent data. It is possible to configure a cluster or JVM-level (SessionFactory-level) cache on a class-by-class and collection-by-collection basis. You may even plug in a clustered cache. Be careful. Caches are never aware of changes made to the persistent store by another application (though they may be configured to regularly expire cached data).
As implied above, this 'second-level' cache exists as long as the session factory is alive. The second-level cache holds on to the 'data' for all properties and associations (and collections if requested) for individual entities that are marked to be cached.
I'm not here to re-hash the details provided clearly by the Hibernate documentation, so for detailed information about selecting a cache provider and configuring Hibernate to use it, look at Section 20.2 of the Hibernate documentation .
Suffice it to say, the important part is the 'cache' element which you add to your mapping file:
<cache usage="transactional|read-write|nonstrict-read-write|read-only" />
For most readers, what I'm describing here is probably nothing new. Bear with me, I'll get to the goodies in a minute.
The Query Cache
The other cache that is available is the query cache. The query cache effectively holds on to the identifiers for an individual query. As described in the documentation:
Note that the query cache does not cache the state of the actual entities in the result set; it caches only identifier values and results of value type. So the query cache should always be used in conjunction with the second-level cache.
Configuration of the query cache is described in Section 20.4 of the Hibernate Documentation .
Once enabled via the configuration of Hibernate, it is simply a matter of calling setCacheable(true) on your Query or Criteria object.
Now, on to the inner workings.
How The Second-Level Cache Works
One of the keys to understanding how the caches can help you is to understand how they work internally (at least conceputally). The second-level cache is typically the more important to understand, particularly when dealing with large, complex object graphs that may be queried and loaded often. The first thing to realize about the second-level cache is that it doesn't cache instances of the object type being cached; instead it caches the individual values for the properties of that object. So, conceptually, for an object like this:
public class Person {
private Person parent;
private Set<Person> children;
public void setParent(Person p) { parent = p; }
public void setChildren(Set<Person> set) { children = set; }
public Set<Person> getChildren() { return children; }
public Person getParent() { return parent; }
}
...with a mapping like this:
<class name="org.javalobby.tnt.hibernate.Person">
<cache usage="read-write"/>
<id name="id" column="id" type="long">
<generator class="identity"/>
</id>
<property name="firstName" type="string"/>
<property name="middleInitial" type="string"/>
<property name="lastName" type="string"/>
<many-to-one name="parent" column="parent_id" class="Person"/>
<set name="children">
<key column="parent_id"/>
<one-to-many class="Person"/>
</set>
</class>
Hibernate will hold on to records for this class conceptually like this:
*-----------------------------------------*
| Person Data Cache |
|-----------------------------------------|
| 1 -> [ "John" , "Q" , "Public" , null ] |
| 2 -> [ "Joey" , "D" , "Public" , 1 ] |
| 3 -> [ "Sara" , "N" , "Public" , 1 ] |
*-----------------------------------------*
So, in this case, Hibernate is holding on to 3 strings, and one serializable identifier for the 'many-to-one' parent relationship. Let me reiterate that Hibernate is *not* holding on to actual instances of the objects. Why is this important? Two reasons. One, Hibernate doesn't have to worry that client code (i.e. your code) will manipulate the objects in a way that will disrupt the cache, and two, the relationships and associations do not become 'stale', and are easy to keep up to date as they are simply identifiers. The cache is not a tree of objects, and can instead just be a conceptual map of arrays. I continually use the word conceptual, because Hibernate does much more behind the scenes with this cache but, unless you plan on implementing your own provider, you don't need to worry about it. Hibernate calls this state that the objects are in 'dehydrated', as it is all the important bits of the object, but in a more controllable form for Hibernate. I'll use the terms 'dehydrate' and 'hydrate' to describe the process of converting between this broken apart data into an object of your domain (hydrating being the process of creating an instance of your domain and populating it with this data, dehydrating being the inverse).
Now, the astute of you may have noticed that I have omitted the 'children' association all-together from the cache. This was intentional. Hibernate adds the granularity to allow you to decide which associations should be cached, and which associations should be re-determined during the hydration of an object of the cached type from the second-level cache. This provides control for when associations can potentially be altered by another class that doesn't explicitly cascade the change to the cached class.
This is a very powerful construct to have. The default setting is to not cache associations; and if you are not aware of this, and simply turn on caching quickly without really reading into how caching works in Hibernate, you will add the overhead of managing the cache without adding much of the benefits. After all, the primary benefit of caching is to have complex associations available without having to do subsequent database selects - as I have mentioned before, n+1 database queries can quickly become a serious performance bottleneck.
In this case we're dealing just with our person class, and we know that the association will be managed properly - so let's update our mapping to reflect that we want the 'children' association to be cached.
<set name="children">
<cache usage="read-write"/>
<key column="parent_id"/>
<one-to-many class="Person"/>
Now, here is an updated version of our person data cache:
*-----------------------------------------------------*
| Person Data Cache |
|-----------------------------------------------------|
| 1 -> [ "John" , "Q" , "Public" , null , [ 2 , 3 ] ] |
| 2 -> [ "Joey" , "D" , "Public" , 1 , [] ] |
| 3 -> [ "Sara" , "N" , "Public" , 1 , [] ] |
*-----------------------------------------------------*
Once again let me point out that all we are caching is the ID of the relative parts.
So, if we were to load the person with ID '1' from the database (ignoring any joining for the time being) without the cache, we would have these selects issued:
select * from Person where id=1 ; load the person with id 1
select * from Person where parent_id=1 ; load the children of 1 (will return 2, 3)
select * from Person where parent_id=2 ; load any potential children of 2 (will return none)
select * from Person where parent_id=3 ; load any potential children of 3 (will return none)
*With* the cache (assuming it was fully loaded), a direct load will actually issue NO select statements, because it can simply look up based on an identifier. If, however we didn't have the associations cached, we'd have these SQL statements invoked for us:
select * from Person where parent_id=1 ; load the children of 1 (will return 2, 3)
select * from Person where parent_id=2 ; load any potential children of 2 (will return none)
select * from Person where parent_id=3 ; load any potential children of 3 (will return none)
That's nearly the same number of SQL statements as when we didn't use the cache at all! This is why it's important to cache associations whenever possible.
Let's say that we wanted to lookup entries based on a more complex query than directly by ID, such as by name. In this case, Hibernate must still issue an SQL statement to get the base data-set for the query. So, for instance, this code:
Query query = session.createQuery("from Person as p where p.firstName=?");
query.setString(0, "John");
List l = query.list();
... would invoke a single select (assuming our associations were cached).
select * from Person where firstName='John'
This single select will then return '1', and then the cache will be used for all other lookups as we have everything cached. This mandatory single select is where the query cache comes in.
How the Query Cache Works
The query cache is actually much like the association caching described above; it's really little more than a list of identifiers for a particular type (although again, it is much more complex internally). Let's say we performed a query like this:
Query query = session.createQuery("from Person as p where p.parent.id=? and p.firstName=?");
query.setInt(0, Integer.valueOf(1));
query.setString(1, "Joey");
query.setCacheable(true);
List l = query.list();
The query cache works something like this:
*----------------------------------------------------------------------------------------*
| Query Cache |
|----------------------------------------------------------------------------------------|
| ["from Person as p where p.parent.id=? and p.firstName=?", [ 1 , "Joey"] ] -> [ 2 ] ] |
*----------------------------------------------------------------------------------------*
The combination of the query and the values provided as parameters to that query is used as a key, and the value is the list of identifiers for that query. Note that this becomes more complex from an internal perspective as you begin to consider that a query can have an effect of altering associations to objects returned that query; not to mention the fact that a query may not return whole objects, but may in fact only return scalar values (when you have supplied a select clause for instance). That being said, this is a sound and reliable way to think of the query cache conceptually.
If the second-level cache is enabled (which it should be for objects returned via a query cache), then the object of type Person with an id of 2 will be pulled from the cache (if available in the cache), it will then be hydradated, as well as any associations.
I hope that this quick glance into how Hibernate holds on to values gives you some idea as to how information can be cached by Hibernate, and will give you some insight into how you can manage your mappings so that you can squeeze the maximum performance possible out of your application.
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.
Q) What are the most common methods of Hibernate configuration?
A) The most common methods of Hibernate configuration are:
* Programmatic configuration
* XML configuration (hibernate.cfg.xml)
Q) What are the important tags of hibernate.cfg.xml?
Q) What role does the Session interface play in Hibernate?
A) The Session interface is the primary interface used by Hibernate applications. 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();
Session interface role:
* Wraps a JDBC connection
* Factory for Transaction
* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier
Q) What role does the SessionFactory interface play in Hibernate?
A) The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();
Q) What is the general flow of Hibernate communication with RDBMS?
A) 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
Q) What is Hibernate Query Language (HQL)?
A) Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.
Q) How do you map Java Objects with Database tables?
A)
* First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.
* Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :
<hibernate-mapping>
<class name=”com.test.User” table=”user”>
<property column=”USER_NAME” length=”255″
name=”userName” not-null=”true” type=”java.lang.String”/>
<property column=”USER_PASSWORD” length=”255″
name=”userPassword” not-null=”true” type=”java.lang.String”/>
</class>
</hibernate-mapping>
Q) What Does Hibernate Simplify?
A) Hibernate simplifies:
* Saving and retrieving your domain objects
* Making database column and table name changes
* Centralizing pre save and post retrieve logic
* Complex joins for retrieving related items
* Schema creation from object model
Q) What’s the difference between load() and get()?
A) load() vs. get()
load() :-
Only use the load() method if you are sure that the object exists.
load() method will throw an exception 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():-
If you are not sure that the object exists, then use one of the get() methods.
get() method will return null if the unique id is not found in the database.
get() will hit the database immediately.
Q) What is the difference between and merge and update ?
A)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.
Q) How do you define sequence generated primary key in hibernate?
A) Using <generator> tag.
Example:-
<id column=”USER_ID” name=”id” type=”java.lang.Long”>
<generator class=”sequence”>
<param name=”table”>SEQUENCE_NAME</param>
<generator>
</id>
Q) Define cascade and inverse option in one-many mapping?
A) cascade – enable operations to cascade to child entities.
cascade=”all|none|save-update|delete|all-delete-orphan”
inverse – mark this collection as the “inverse” end of a bidirectional association.
inverse=”true|false”
Essentially “inverse” indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
Q) What does it mean to be inverse?
A) It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created.
Q) What do you mean by Named – SQL query?
A) Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = “empdetails”>
<return alias=”emp” class=”com.test.Employee”/>
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
</sql-query>
Invoke Named Query :
List people = session.getNamedQuery(“empdetails”)
.setString(“TomBrady”, name)
.setMaxResults(50)
.list();
Q) How do you invoke Stored Procedures?
A) <sql-query name=”selectAllEmployees_SP” callable=”true”>
<return alias=”emp” class=”employee”>
<return-property name=”empid” column=”EMP_ID”/>
<return-property name=”name” column=”EMP_NAME”/>
<return-property name=”address” column=”EMP_ADDRESS”/>
{ ? = call selectAllEmployees() }
</return>
</sql-query>
Q) Explain Criteria API
A) 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();
Q) Define HibernateTemplate?
A) org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
Q) What are the benefits does HibernateTemplate provide?
A) The benefits of HibernateTemplate are :
* HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
* Common functions are simplified to single method calls.
* Sessions are automatically closed.
* Exceptions are automatically caught and converted to runtime exceptions.
Q) How do you switch between relational databases without code changes?
A) Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
Q) If you want to see the Hibernate generated SQL statements on console, what should we do?
A) In Hibernate configuration file set as follows:
<property name=”show_sql”>true</property>
Q) What are derived properties?
A) 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.
People who read this also read:
Core Java Questions
Spring Questions
SCJP 6.0 Certification
EJB Interview Questions
Servlets Questions
Q) What is component mapping in Hibernate?
A)
* A component is an object saved as a value, not as a reference
* A component can be saved directly without needing to declare interfaces or identifier properties
* Required to define an empty constructor
* Shared references not supported
Q) What is the difference between sorted and ordered collection in hibernate?
A) sorted collection vs. order collection
sorted 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.
If your collection is not large, it will be more efficient way to sort it.
order collection :-
Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is very large, it will be more efficient way to sort it .
1.
What are the types of inheritence models and describe how they work like vertical inheritenceand horizontal ?
Ans. (a)There are three types of inheritance mapping in hibernate1. Table per concrete class with unions2. Table per class hierarchy3. Table per subclassExample:Let us take the simple example of 3 java classes.Class Manager and Worker are inherited from Employee Abstract class.1. Table per concrete class with unionsIn this case there will be 2 tablesTables: Manager, Worker [all common attributes will be duplicated]2. Table per class hierarchySingle Table can be mapped to a class hierarchyThere will be only one table in database called 'Employee' that will represent all the attributes required for all3 classes.But it needs some discriminating column to differentiate between Manager and worker;3. Table per subclassIn this case there will be 3 tables represent Employee, Manager and Worker Ans. (b). Table per concrete class using implicit polymorphism can also be added as inheritance mapping in hibernate2.
Q) What is lazy fetching in hibernate ?
Ans 1) Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this settingrespective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazyloading of the child objects is true. This make sure that the child objects are not loaded unless they areexplicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues afresh database call to load the child when getChild() is actully called on the Parent object.But in some casesyou do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will loadthe child when parent is loaded from the database.Exampleslazy=true (default)Address child of User classcan be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.Ans 2Lazy fetching is related to loading of the Child objects for its parent ( In the terms of databse its primary key-foreign key relationship). In hbm.xml file you have to specify whether you want to load the child objectswhile loading the parent. By default hibernate doesn't load the whole child objects (lazy="true").
But Sometimes it doesn't work properly, it doesn't load the child objects for the parent.and second problem is that if you have condition like ....Employee Table -1-----n-> Emp_Dept Table<-n------1- Department TableAnd you have many to many relationship between them, then by specifying lazy="false" for boththe parent object(Employee And Department) hibernate try to get all the child for this parent and for thischild. Now this child becomes the parent and hibernate will try to get all the child for this parent. This process may continue.This results in performance issue.So U have to take care while writing the mapping files in case of many-to-many relationships.Ans 3Simply saying: It maintains the relactionship between two tables.Ans 4.There are two types of Loading in application. Eager loading and Lazyloading. In eager loading we will fetch all the values from the Persistent storageand cache it. It will make serious performance issues. There we use lazyloading to avoid that scenario.Some times we don't need to load the childtable values, In that case we have to us lazy = true in .hbm file. so hibernatewill fetch only parent table values. Internally it will load the wrapper class but it does not cache all the values till we perform operation.MainAdvantage: It will avoid caching unnecessary values and improve performances.3.
How JPA and hibernate are related as per EJB 3 specifications?
Ans 1. JPA is a persistence API by Sun. As per sun, JPA takes best ideas from persistence frameworks likeHibernate, TopLink2.Ans 2. JPA Is Java Persistance API , it will give the most pefect api from the Persistanc Frame work like,Top-link, Hibernate , OracleDAO. This was not there with ejb2.1 . The main feature of EJB3.0 is the favour of JPA so that programers can use the entity bean much easier and simpler.Ans. 3. Java Persistence API is implemented as per EJB3 specification and having more features of Hibernate. JPA is framed by adding few features of kodo which is a ORM tool.Ans. 4. JPA is official acceptance from SUN about its failure on EJB. It has to abandon its EJB model to goto ORM model. Finally, Sun should provide developers some tools to migrate Java programs to .net easilywith out pain
Q).Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
• Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
• Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
• Improved maintainability
o A lot less code to write
• Improved portability
o ORM framework generates database-specific SQL for you
Q).What Does Hibernate Simplify?
Hibernate simplifies:
• Saving and retrieving your domain objects
• Making database column and table name changes
• Centralizing pre save and post retrieve logic
• Complex joins for retrieving related items
• Schema creation from object model
Q)What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:
Q).What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
• Programmatic configuration
• XML configuration (hibernate.cfg.xml)
Q).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 :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>
Q).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.
Q).How do you define sequence generated primary key in hibernate?
Using <generator> tag.
Example:-
<id column="USER_ID" name="id" type="java.lang.Long">
<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>
Q).Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
Q).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();
Q).What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. 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 .
Q).What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
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.
Q).What are the Collection types in Hibernate ?
• Bag
• Set
• List
• Array
• Map
Q).What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
• An implicit association join
• An ordinary join in the FROM clause
• A fetch join in the FROM clause.
• A theta-style join in the WHERE clause.
Q).How can Hibernate be configured to access an instance variable directly and not through a setter method ?
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.
Q).How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.
Q).What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
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.
• dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
• dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
Q.What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
Q.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
Q.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.
Q).What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.
Q).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
Q)What are the differences between EJB 3.0 & Hibernate ?
Hibernate Vs EJB 3.0 :-
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
Q)What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
• Table per class hierarchy
• Table per subclass
• Table per concrete class
1) Adv/Disadvantages of Hibernate:
a) Object – Relational mapping
b) The developer doesn’t have to take into account the type of database he is coding for. The type of database can be changed by changing the dialect line in the configuration file.
c) Hibernate has caching.
d) Need to write less complex queries.
e) One has the choice as to how he wants the related objects of the object he wants to be loaded. (Fetching and join strategy)
f) Connection Pooling can be done by editing a few lines in the hibernate-cfg.xml file ..
c3p0 :- connection pool built in with Hibernate
hibernate.connection.driver_class=com.mysql.jdbc.Driverhibernate.connection.url=jdbc:mysql://localhost/hibernatehibernate.connection.username=roothibernate.connection.password= hibernate.dialect=net.sf.hibernate.dialect.MySQLDialecthibernate.show_sql=false
hibernate.c3p0.max_size=1hibernate.c3p0.min_size=0hibernate.c3p0.timeout=5000hibernate.c3p0.max_statements=100hibernate.c3p0.idle_test_period=300hibernate.c3p0.acquire_increment=2
Disadvantages:
slower in processing the queries than if the queries are used directly
adding the xml would cause portability problems
2) Explain Session Factory?
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
3) Explain different type of fetch statements?
Fetching strategy is used by hibernate to retrieve associated objects if the Hibernate needs to go through to the association.
There are 4 types of fetching strategies:
fetch = join
Using the same ‘select’ statement the Hibernate will fetch the associated instance/ collection using outer join.
fetch = select
This is the default option. If there are ‘n’ associated objects to the one you requested then there would be ‘n+1′ select statements executed. If the lazy=true then these would executed only when the association is required.
fetch = subselect
A second select statement would be used to get all the related objects. If the lazy=true then this second select statement would be executed only when the association is called.
fetch=batch
It is an optimization strategy for fetch=select , where in using a list of primary or foreign keys one would pull out all instances/collection in a single select.
4) Explain lazy loading?
5) Explain object states?
Transient
Persistent
Detached:
Detached objects have a representation in database but changes done to the object won’t be reflected to the database. A detached objects can be created by closing the session or by using the evict method of the session on the object. In order to reflect the changes in the object to the database the load,refresh,merge,update or save method on the object in any session.
6) Performance metrics in Hibernate?
sessionFactory.getStatistics
7) 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
8) Explain caching in Hibernate
Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. This article focuses on second-level cache. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.
In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects.
Each cache provides different capacities in terms of performance, memory use, and configuration possibilities:
• EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
• OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
• SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
• JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Another cache implementation worth mentioning is the commercial Tangosol Coherence cache.
Caching Strategies
Once you have chosen your cache implementation, you need to specify your access strategies. The following four caching strategies are available:
• Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
• Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
• Nonstrict read/write: This strategy does not guarantee that two transactions won’t simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
• Transactional: This is a fully transactional cache that may be used only in a JTA environment.
9) Proxy pattern in Hibernate:
When an object contains another object and the loading is lazy then when the main object is created then it contains only a refernce to the object it contains. This reference is the proxy of the object it contains and this pattern is called proxy patters.
10) Interfaces in Hibernate:
Configuration,Session,Transaction and SessionFactory
11) Light weight ,Medium Weight and Heavy Weight mapping:
There are four levels of Hibernate Quality:
Pure: Stored Procedures
Light: JDBC
Medium:
Heavy:composition,inheritance, polymorphism, persistence by reachability
12) Difference between Hibernate and Ibatis:
In Ibatis Results of the SQL queries are mapped to the Objects where as in Hibernate the table is mapped to the object. Ibatis would be faster as it making use of the queries directly and is useful when you personally don’t have much knowledge about the database.
13) What is NHibernate?
NHibernate is an Object Relational Mapping (ORM) solution for .Net.
14) Integrating Hibernate and Spring
A) Configure the SessionFactory in the ‘spring.xml’
<util:list id=”abc.MappingResources”>
<value>abcde/a.hbm.xml</value>
<value>abcde/b.hbm.xml</value>
</util:list>
<bean id=”core.commons.adm.SessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”
p:dataSource-ref=”data.source.DataSource”
p:mappingResources-ref=”abc.MappingResources”
p:hibernateProperties-ref=”abc.HibernateProperties”>
<property name=”jtaTransactionManager”>
<bean class=”org.springframework.jndi.JndiObjectFactoryBean”>
<property name=”jndiName”>
<value>javax.transaction.TransactionManager</value>
</property>
</bean>
</property>
</bean>
B) Configure the DataSource in the ‘spring.xml’
<bean id=“dataSource”
class=“org.springframework.jdbc.datasource.DriverManagerDataSource”>
<property name=“driverClassName”>
<value>org.hsqldb.jdbcDriver</value>
</property>
<property name=“url”>
<value>jdbc:hsqldb:mem:widgets</value>
</property>
<property name=“username”><value>sa</value></property>
<property name=“password”><value></value></property>
</bean>
C) Extend your DAO Implementation from HibernateDaoSupport
Spring can simplify your Hibernate application. Spring’s Hibernate integration uses the same generic transaction infrastructure and DAO exception hierarchy that it uses for JDBC, JDO, iBATIS, and TopLink, making it easy to mix and match persistence methodologies if necessary.
There are two approaches to Spring’s Hibernate integration:
1. Inversion of Control with a HibernateTemplate and Callback
2. Extending HibernateDaoSupport and Applying an AOP Interceptor
The IoC/HibernateTemplate methodology feels a lot like the JdbcTemplate methodology described in the last section. For this example, I will show the HibernateDaoSupport/AOP Interceptor approach.
After you have written your standard Hibernate mappings, there basically three things that you need to do to use Spring’s HibernateDaoSupport to implement a DAO:
1. Configure the Hibernate SessionFactory
2. Extend your DAO Implementation from HibernateDaoSupport
3. Wire in Transaction Support with AOP
So let’s do another implementation of the WidgetDAO using Hibernate. First of all, here is our Hibernate XML mapping for the Widget class:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zabada.springrecipes.model">
<class name="Widget" table="WIDGETS">
<id name="id" column="WIDGET_ID" type="long">
<generator class="native"/>
</id>
<property name="name" column="NAME" type="string"/>
<property name="size" column="SIZE" type="int"/>
</class>
</hibernate-mapping>
If you’ve used Hibernate before, there should be nothing tricky here since Widget is a trivial class (there are no collections or other classes to associate to). So now we can wire up the Hibernate SessionFactory
Configuring the Hibernate SessionFactory in Spring
Here is an example Hibernate SessionFactory configured in Spring. You will be using this instead of the typical hibernate-config.xml. All we are doing here is telling Hibernate/Spring what our Hibernate mapping files are:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>com/zabada/springrecipes/base/Widget.hbm.xml</value>
</list>
</property>
</bean>
If you have a hibernate.properties in your classpath, the Spring LocalSessionFactoryBean will use that file to configure the database connections, dialect and pooling. Alternatively, you can define a DataSource in Spring (any class that implements javax.sql.DataSource) and explicity set all of your Hibernate properties in the LocalSessionFactoryBean:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>com/zabada/springrecipes/base/Widget.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.HSQLDialect
</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>org.hsqldb.jdbcDriver</value>
</property>
<property name="url">
<value>jdbc:hsqldb:mem:widgets</value>
</property>
<property name="username"><value>sa</value></property>
<property name="password"><value></value></property>
</bean>
Extending HibernateDaoSupport for the Actual DAO Implementation
The Spring HibernateDaoSupport class provides all kinds of convenience methods for working with Hibernate. Most of these are accessible via the HibernateTemplate object that this class exposes.
Please note that Hibernate 2 throws checked HibernateExceptions and Hibernate 3 throws runtime exceptions. I am using Hibernate 3 and am blowing off runtime exceptions that might be thrown, but it might be more appropriate to deal with these exceptions here (this is just a example, not prduction code!)
Anyway, here is our WidgetDAO implemented by extending HibernateDaoSupport:
public class WidgetDAOHibernateImpl
extends HibernateDaoSupport
implements WidgetDAO
{
/**
* Returns a java.util.List of all Widgets in the system.
* @return
*/
public Collection getWidgets()
{
return getHibernateTemplate().loadAll(Widget.class);
}
/**
* Get a Widget Object given the id
* @param id
* @return
*/
public Widget getWidgetById(Long id)
{
return (Widget)
getHibernateTemplate().load(Widget.class, id);
}
/**
* Save a Widget Object, if the given Widget
* is not in the data store,it should insert it,
* if it is in the data store, it should update it.
* @param widget
*/
public Widget saveWidget(Widget widget)
{
getHibernateTemplate().saveOrUpdate(widget);
return widget;
}
}
Using AOP to Wire Up the DAO and Transaction Management
Now we wire up our DAO and weave in the HibernateInterceptor. This interceptor binds a new Hibernate Session to the thread before a method call, closing and removing it afterwards in case of any method outcome. If there already is a pre-bound Session, the interceptor simply participates in it. Note that the actual “widgetDAO” bean is defined as a proxy bean that really points to a bean called “widgetDaoTarget” which is where we wire up our actual implementation.
<!-- THE HIBERNATE INTERCEPTOR -->
<bean id="hibernateInterceptor"
class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="widgetDaoTarget"
class="com.zabada.springrecipes.hibernate.WidgetDAOHibernateImpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="widgetDAO"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.zabada.springrecipes.base.WidgetDAO</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
<value>widgetDaoTarget</value>
</list>
</property>
</bean>
Hibernate isn't just a popular kid on the block, however; it is actually a very powerful, consistent, and reliable database mapping tool. Mapping between objects in Java to relational databases has many facets that you must be aware of. Hibernate does a particularly good job of making the process simple to start, and providing the facilities to allow it to scale well and meet exceedingly complex mapping demands.
One of the primary concerns of mappings between a database and your Java application is performance. One of the common concerns of people who haven't spent much time working with Hibernate in particular, is that O/R mapping tools will limit your ability to make performance-enhancing changes to particular queries and retrievals. Today I want to discuss two facets of the Hibernate infrastructure that are implemented to handle certain performance concerns - the second-level cache and the query cache.
The Second Level Cache
The second-level cache is called 'second-level' because there is already a cache operating for you in Hibernate for the duration you have a session open. From the Hibernate documentation:
A Hibernate Session is a transaction-level cache of persistent data. It is possible to configure a cluster or JVM-level (SessionFactory-level) cache on a class-by-class and collection-by-collection basis. You may even plug in a clustered cache. Be careful. Caches are never aware of changes made to the persistent store by another application (though they may be configured to regularly expire cached data).
As implied above, this 'second-level' cache exists as long as the session factory is alive. The second-level cache holds on to the 'data' for all properties and associations (and collections if requested) for individual entities that are marked to be cached.
I'm not here to re-hash the details provided clearly by the Hibernate documentation, so for detailed information about selecting a cache provider and configuring Hibernate to use it, look at Section 20.2 of the Hibernate documentation .
Suffice it to say, the important part is the 'cache' element which you add to your mapping file:
<cache usage="transactional|read-write|nonstrict-read-write|read-only" />
For most readers, what I'm describing here is probably nothing new. Bear with me, I'll get to the goodies in a minute.
The Query Cache
The other cache that is available is the query cache. The query cache effectively holds on to the identifiers for an individual query. As described in the documentation:
Note that the query cache does not cache the state of the actual entities in the result set; it caches only identifier values and results of value type. So the query cache should always be used in conjunction with the second-level cache.
Configuration of the query cache is described in Section 20.4 of the Hibernate Documentation .
Once enabled via the configuration of Hibernate, it is simply a matter of calling setCacheable(true) on your Query or Criteria object.
Now, on to the inner workings.
How The Second-Level Cache Works
One of the keys to understanding how the caches can help you is to understand how they work internally (at least conceputally). The second-level cache is typically the more important to understand, particularly when dealing with large, complex object graphs that may be queried and loaded often. The first thing to realize about the second-level cache is that it doesn't cache instances of the object type being cached; instead it caches the individual values for the properties of that object. So, conceptually, for an object like this:
public class Person {
private Person parent;
private Set<Person> children;
public void setParent(Person p) { parent = p; }
public void setChildren(Set<Person> set) { children = set; }
public Set<Person> getChildren() { return children; }
public Person getParent() { return parent; }
}
...with a mapping like this:
<class name="org.javalobby.tnt.hibernate.Person">
<cache usage="read-write"/>
<id name="id" column="id" type="long">
<generator class="identity"/>
</id>
<property name="firstName" type="string"/>
<property name="middleInitial" type="string"/>
<property name="lastName" type="string"/>
<many-to-one name="parent" column="parent_id" class="Person"/>
<set name="children">
<key column="parent_id"/>
<one-to-many class="Person"/>
</set>
</class>
Hibernate will hold on to records for this class conceptually like this:
*-----------------------------------------*
| Person Data Cache |
|-----------------------------------------|
| 1 -> [ "John" , "Q" , "Public" , null ] |
| 2 -> [ "Joey" , "D" , "Public" , 1 ] |
| 3 -> [ "Sara" , "N" , "Public" , 1 ] |
*-----------------------------------------*
So, in this case, Hibernate is holding on to 3 strings, and one serializable identifier for the 'many-to-one' parent relationship. Let me reiterate that Hibernate is *not* holding on to actual instances of the objects. Why is this important? Two reasons. One, Hibernate doesn't have to worry that client code (i.e. your code) will manipulate the objects in a way that will disrupt the cache, and two, the relationships and associations do not become 'stale', and are easy to keep up to date as they are simply identifiers. The cache is not a tree of objects, and can instead just be a conceptual map of arrays. I continually use the word conceptual, because Hibernate does much more behind the scenes with this cache but, unless you plan on implementing your own provider, you don't need to worry about it. Hibernate calls this state that the objects are in 'dehydrated', as it is all the important bits of the object, but in a more controllable form for Hibernate. I'll use the terms 'dehydrate' and 'hydrate' to describe the process of converting between this broken apart data into an object of your domain (hydrating being the process of creating an instance of your domain and populating it with this data, dehydrating being the inverse).
Now, the astute of you may have noticed that I have omitted the 'children' association all-together from the cache. This was intentional. Hibernate adds the granularity to allow you to decide which associations should be cached, and which associations should be re-determined during the hydration of an object of the cached type from the second-level cache. This provides control for when associations can potentially be altered by another class that doesn't explicitly cascade the change to the cached class.
This is a very powerful construct to have. The default setting is to not cache associations; and if you are not aware of this, and simply turn on caching quickly without really reading into how caching works in Hibernate, you will add the overhead of managing the cache without adding much of the benefits. After all, the primary benefit of caching is to have complex associations available without having to do subsequent database selects - as I have mentioned before, n+1 database queries can quickly become a serious performance bottleneck.
In this case we're dealing just with our person class, and we know that the association will be managed properly - so let's update our mapping to reflect that we want the 'children' association to be cached.
<set name="children">
<cache usage="read-write"/>
<key column="parent_id"/>
<one-to-many class="Person"/>
Now, here is an updated version of our person data cache:
*-----------------------------------------------------*
| Person Data Cache |
|-----------------------------------------------------|
| 1 -> [ "John" , "Q" , "Public" , null , [ 2 , 3 ] ] |
| 2 -> [ "Joey" , "D" , "Public" , 1 , [] ] |
| 3 -> [ "Sara" , "N" , "Public" , 1 , [] ] |
*-----------------------------------------------------*
Once again let me point out that all we are caching is the ID of the relative parts.
So, if we were to load the person with ID '1' from the database (ignoring any joining for the time being) without the cache, we would have these selects issued:
select * from Person where id=1 ; load the person with id 1
select * from Person where parent_id=1 ; load the children of 1 (will return 2, 3)
select * from Person where parent_id=2 ; load any potential children of 2 (will return none)
select * from Person where parent_id=3 ; load any potential children of 3 (will return none)
*With* the cache (assuming it was fully loaded), a direct load will actually issue NO select statements, because it can simply look up based on an identifier. If, however we didn't have the associations cached, we'd have these SQL statements invoked for us:
select * from Person where parent_id=1 ; load the children of 1 (will return 2, 3)
select * from Person where parent_id=2 ; load any potential children of 2 (will return none)
select * from Person where parent_id=3 ; load any potential children of 3 (will return none)
That's nearly the same number of SQL statements as when we didn't use the cache at all! This is why it's important to cache associations whenever possible.
Let's say that we wanted to lookup entries based on a more complex query than directly by ID, such as by name. In this case, Hibernate must still issue an SQL statement to get the base data-set for the query. So, for instance, this code:
Query query = session.createQuery("from Person as p where p.firstName=?");
query.setString(0, "John");
List l = query.list();
... would invoke a single select (assuming our associations were cached).
select * from Person where firstName='John'
This single select will then return '1', and then the cache will be used for all other lookups as we have everything cached. This mandatory single select is where the query cache comes in.
How the Query Cache Works
The query cache is actually much like the association caching described above; it's really little more than a list of identifiers for a particular type (although again, it is much more complex internally). Let's say we performed a query like this:
Query query = session.createQuery("from Person as p where p.parent.id=? and p.firstName=?");
query.setInt(0, Integer.valueOf(1));
query.setString(1, "Joey");
query.setCacheable(true);
List l = query.list();
The query cache works something like this:
*----------------------------------------------------------------------------------------*
| Query Cache |
|----------------------------------------------------------------------------------------|
| ["from Person as p where p.parent.id=? and p.firstName=?", [ 1 , "Joey"] ] -> [ 2 ] ] |
*----------------------------------------------------------------------------------------*
The combination of the query and the values provided as parameters to that query is used as a key, and the value is the list of identifiers for that query. Note that this becomes more complex from an internal perspective as you begin to consider that a query can have an effect of altering associations to objects returned that query; not to mention the fact that a query may not return whole objects, but may in fact only return scalar values (when you have supplied a select clause for instance). That being said, this is a sound and reliable way to think of the query cache conceptually.
If the second-level cache is enabled (which it should be for objects returned via a query cache), then the object of type Person with an id of 2 will be pulled from the cache (if available in the cache), it will then be hydradated, as well as any associations.
I hope that this quick glance into how Hibernate holds on to values gives you some idea as to how information can be cached by Hibernate, and will give you some insight into how you can manage your mappings so that you can squeeze the maximum performance possible out of your application.
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.
Q) What are the most common methods of Hibernate configuration?
A) The most common methods of Hibernate configuration are:
* Programmatic configuration
* XML configuration (hibernate.cfg.xml)
Q) What are the important tags of hibernate.cfg.xml?
Q) What role does the Session interface play in Hibernate?
A) The Session interface is the primary interface used by Hibernate applications. 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();
Session interface role:
* Wraps a JDBC connection
* Factory for Transaction
* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier
Q) What role does the SessionFactory interface play in Hibernate?
A) The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();
Q) What is the general flow of Hibernate communication with RDBMS?
A) 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
Q) What is Hibernate Query Language (HQL)?
A) Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.
Q) How do you map Java Objects with Database tables?
A)
* First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.
* Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :
<hibernate-mapping>
<class name=”com.test.User” table=”user”>
<property column=”USER_NAME” length=”255″
name=”userName” not-null=”true” type=”java.lang.String”/>
<property column=”USER_PASSWORD” length=”255″
name=”userPassword” not-null=”true” type=”java.lang.String”/>
</class>
</hibernate-mapping>
Q) What Does Hibernate Simplify?
A) Hibernate simplifies:
* Saving and retrieving your domain objects
* Making database column and table name changes
* Centralizing pre save and post retrieve logic
* Complex joins for retrieving related items
* Schema creation from object model
Q) What’s the difference between load() and get()?
A) load() vs. get()
load() :-
Only use the load() method if you are sure that the object exists.
load() method will throw an exception 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():-
If you are not sure that the object exists, then use one of the get() methods.
get() method will return null if the unique id is not found in the database.
get() will hit the database immediately.
Q) What is the difference between and merge and update ?
A)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.
Q) How do you define sequence generated primary key in hibernate?
A) Using <generator> tag.
Example:-
<id column=”USER_ID” name=”id” type=”java.lang.Long”>
<generator class=”sequence”>
<param name=”table”>SEQUENCE_NAME</param>
<generator>
</id>
Q) Define cascade and inverse option in one-many mapping?
A) cascade – enable operations to cascade to child entities.
cascade=”all|none|save-update|delete|all-delete-orphan”
inverse – mark this collection as the “inverse” end of a bidirectional association.
inverse=”true|false”
Essentially “inverse” indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
Q) What does it mean to be inverse?
A) It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created.
Q) What do you mean by Named – SQL query?
A) Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = “empdetails”>
<return alias=”emp” class=”com.test.Employee”/>
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
</sql-query>
Invoke Named Query :
List people = session.getNamedQuery(“empdetails”)
.setString(“TomBrady”, name)
.setMaxResults(50)
.list();
Q) How do you invoke Stored Procedures?
A) <sql-query name=”selectAllEmployees_SP” callable=”true”>
<return alias=”emp” class=”employee”>
<return-property name=”empid” column=”EMP_ID”/>
<return-property name=”name” column=”EMP_NAME”/>
<return-property name=”address” column=”EMP_ADDRESS”/>
{ ? = call selectAllEmployees() }
</return>
</sql-query>
Q) Explain Criteria API
A) 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();
Q) Define HibernateTemplate?
A) org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
Q) What are the benefits does HibernateTemplate provide?
A) The benefits of HibernateTemplate are :
* HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
* Common functions are simplified to single method calls.
* Sessions are automatically closed.
* Exceptions are automatically caught and converted to runtime exceptions.
Q) How do you switch between relational databases without code changes?
A) Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
Q) If you want to see the Hibernate generated SQL statements on console, what should we do?
A) In Hibernate configuration file set as follows:
<property name=”show_sql”>true</property>
Q) What are derived properties?
A) 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.
People who read this also read:
Core Java Questions
Spring Questions
SCJP 6.0 Certification
EJB Interview Questions
Servlets Questions
Q) What is component mapping in Hibernate?
A)
* A component is an object saved as a value, not as a reference
* A component can be saved directly without needing to declare interfaces or identifier properties
* Required to define an empty constructor
* Shared references not supported
Q) What is the difference between sorted and ordered collection in hibernate?
A) sorted collection vs. order collection
sorted 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.
If your collection is not large, it will be more efficient way to sort it.
order collection :-
Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is very large, it will be more efficient way to sort it .
1.
What are the types of inheritence models and describe how they work like vertical inheritenceand horizontal ?
Ans. (a)There are three types of inheritance mapping in hibernate1. Table per concrete class with unions2. Table per class hierarchy3. Table per subclassExample:Let us take the simple example of 3 java classes.Class Manager and Worker are inherited from Employee Abstract class.1. Table per concrete class with unionsIn this case there will be 2 tablesTables: Manager, Worker [all common attributes will be duplicated]2. Table per class hierarchySingle Table can be mapped to a class hierarchyThere will be only one table in database called 'Employee' that will represent all the attributes required for all3 classes.But it needs some discriminating column to differentiate between Manager and worker;3. Table per subclassIn this case there will be 3 tables represent Employee, Manager and Worker Ans. (b). Table per concrete class using implicit polymorphism can also be added as inheritance mapping in hibernate2.
Q) What is lazy fetching in hibernate ?
Ans 1) Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this settingrespective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazyloading of the child objects is true. This make sure that the child objects are not loaded unless they areexplicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues afresh database call to load the child when getChild() is actully called on the Parent object.But in some casesyou do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will loadthe child when parent is loaded from the database.Exampleslazy=true (default)Address child of User classcan be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.Ans 2Lazy fetching is related to loading of the Child objects for its parent ( In the terms of databse its primary key-foreign key relationship). In hbm.xml file you have to specify whether you want to load the child objectswhile loading the parent. By default hibernate doesn't load the whole child objects (lazy="true").
But Sometimes it doesn't work properly, it doesn't load the child objects for the parent.and second problem is that if you have condition like ....Employee Table -1-----n-> Emp_Dept Table<-n------1- Department TableAnd you have many to many relationship between them, then by specifying lazy="false" for boththe parent object(Employee And Department) hibernate try to get all the child for this parent and for thischild. Now this child becomes the parent and hibernate will try to get all the child for this parent. This process may continue.This results in performance issue.So U have to take care while writing the mapping files in case of many-to-many relationships.Ans 3Simply saying: It maintains the relactionship between two tables.Ans 4.There are two types of Loading in application. Eager loading and Lazyloading. In eager loading we will fetch all the values from the Persistent storageand cache it. It will make serious performance issues. There we use lazyloading to avoid that scenario.Some times we don't need to load the childtable values, In that case we have to us lazy = true in .hbm file. so hibernatewill fetch only parent table values. Internally it will load the wrapper class but it does not cache all the values till we perform operation.MainAdvantage: It will avoid caching unnecessary values and improve performances.3.
How JPA and hibernate are related as per EJB 3 specifications?
Ans 1. JPA is a persistence API by Sun. As per sun, JPA takes best ideas from persistence frameworks likeHibernate, TopLink2.Ans 2. JPA Is Java Persistance API , it will give the most pefect api from the Persistanc Frame work like,Top-link, Hibernate , OracleDAO. This was not there with ejb2.1 . The main feature of EJB3.0 is the favour of JPA so that programers can use the entity bean much easier and simpler.Ans. 3. Java Persistence API is implemented as per EJB3 specification and having more features of Hibernate. JPA is framed by adding few features of kodo which is a ORM tool.Ans. 4. JPA is official acceptance from SUN about its failure on EJB. It has to abandon its EJB model to goto ORM model. Finally, Sun should provide developers some tools to migrate Java programs to .net easilywith out pain
Q).Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
• Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
• Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
• Improved maintainability
o A lot less code to write
• Improved portability
o ORM framework generates database-specific SQL for you
Q).What Does Hibernate Simplify?
Hibernate simplifies:
• Saving and retrieving your domain objects
• Making database column and table name changes
• Centralizing pre save and post retrieve logic
• Complex joins for retrieving related items
• Schema creation from object model
Q)What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:
Q).What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
• Programmatic configuration
• XML configuration (hibernate.cfg.xml)
Q).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 :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>
Q).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.
Q).How do you define sequence generated primary key in hibernate?
Using <generator> tag.
Example:-
<id column="USER_ID" name="id" type="java.lang.Long">
<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>
Q).Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
Q).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();
Q).What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. 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 .
Q).What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
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.
Q).What are the Collection types in Hibernate ?
• Bag
• Set
• List
• Array
• Map
Q).What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
• An implicit association join
• An ordinary join in the FROM clause
• A fetch join in the FROM clause.
• A theta-style join in the WHERE clause.
Q).How can Hibernate be configured to access an instance variable directly and not through a setter method ?
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.
Q).How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.
Q).What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
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.
• dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
• dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
Q.What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
Q.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
Q.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.
Q).What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.
Q).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
Q)What are the differences between EJB 3.0 & Hibernate ?
Hibernate Vs EJB 3.0 :-
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
Q)What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
• Table per class hierarchy
• Table per subclass
• Table per concrete class
Wednesday 7 August 2013
Top Most Hibernate Interview questions
Hibernate is most popular ORM tool with Java. It helps developer to more focus on building business logic. Java is made to build applications more quickly and in more standard ways. This tool helps to communicate the java application with various RBDMS systems. It works as layer between java application and database. If application decide to change database then ideally it should be only configuration change in hibernate property file.
Performance is another big plus with hibernate where you can easily add caching using various tools which avoid doing database base lookup in each entity look up. Below are basic hibernate interviews questions.
1. What is benefit of using ORM tools?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
- Improved productivity
- High-level object-oriented API
- Less Java code to write
- No SQL to write
- Improved performance
- Sophisticated caching
- Lazy loading / Eager loading
- Improved maintainability
- A lot less code to write
- Improved portability
ORM framework generates database-specific SQL for you.
2. What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
- Programmatic configuration
- XML configuration (hibernate.cfg.xml)
3. What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.
4. What are the Core interfaces are of Hibernate framework?
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
- Session interface
- SessionFactory interface
- Configuration interface
- Transaction interface
- Query and Criteria interface
5. What role does the Session interface play in Hibernate?
The Session interface is the primary interface used by Hibernate applications. 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();
Session interface role:
- Wraps a JDBC connection
- Factory for Transaction
- Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier
6. What role does the SessionFactory interface play in Hibernate?
Application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole applicationÃ¥¹¼reated during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();
7. What is the general flow of Hibernate communication with RDBMS?
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
8. What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.
9. 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 :
10. What’s the difference between load() and get()?
load() vs. get() :-
load()
- Only use the load() method if you are sure that the object exists.
- load() method will throw an exception 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()
- If you are not sure that the object exists, then use one of the get() methods.
- get() method will return null if the unique id is not found in the database.
- get() will hit the database immediately.
11. 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.
12. How do you define sequence generated primary key in hibernate?
Using tag.
Example:-
SEQUENCE_NAME
13. Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
14. 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();
15. How do you invoke Stored Procedures?
{ ? = call selectAllEmployees() }
16. 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();
17. Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
18. What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
Common functions are simplified to single method calls.
Sessions are automatically closed.
Exceptions are automatically caught and converted to runtime exceptions.
19. If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
20. What are derived properties?
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.
21. What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-
Sorted 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.
- If your collection is not large, it will be more efficient way to sort it.
Order collection
- Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
- If your collection is very large, it will be more efficient way to sort it.
22. What are the Collection types in Hibernate ?
- Bag
- Set
- List
- Array
- Map
23. What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.
24. How can Hibernate be configured to access an instance variable directly and not through a setter method ?
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.
25. How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.
26. How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.
27. What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
- Table per class hierarchy
- Table per subclass
- Table per concrete class
28. 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
29. What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
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.
- dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
- dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
30. What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
31. What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
32. What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind
33. What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.
34. Sample of Hibernate transaction management?
A org.hibernate.Session is designed to represent a single unit of work (a single atmoic piece of work to be performed.
Sample code of handling transaction from hibernate session.
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();
35. How to implement Optimistic locking in Database?
You can implement optimistic locks in your DB table in this way (This is how optimistic locking is done in Hibernate):
- Add integer "version" column to your table.
- Increase value of this column with each update of corresponding row.
- To obtain lock, just read "version" value of row.
- Add "version = obtained_version" condition to where clause of your update statement.
- Verify number of affected rows after update. If no rows were affected - someone has already modified your entry.
Your update should look like
UPDATE mytable SET name = 'Andy', version = 3 WHERE id = 1 and version = 2;
Subscribe to:
Posts (Atom)
Labels
Core Java
programming
core java interview question
Core Java Faq's
Servlets
coding
database
jsp-servlet
spring
Java
linux
unix
interview questions
java investment bank
Web Services
Interview
investment bank
mysql
Senior java developer interviews
best practices
java collection tutorial
RMI
SQL
Eclipse
FIX protocol tutorial
tibco
J2EE
groovy
java questions
SCJP
grails
java 5 tutorial
jdbc
beginner
error and exception
Design Patterns
Java Programming Tutorials
fundamentals
general
object oriented programming
xml
Java Programs
Hibernate
Examples
Flex
JAMon
Java xml tutorial
logging
Jsp
Struts 2.0
Sybase and SQL Server
debugging
java interviews
performance
FIX Protocol interview questions
JUnit testing
WebSphere
date and time tutorial
experienced
java IO tutorial
java concurrency
thread
Ejb
Freshers Papers
IT Management
Java Exapmle
Java Script
SQL and database tutorial examples
Scwcd
ant tutorials
concurrency example and tutorial
future state
homework
java changes
java threading
tricky
Agile
Business of IT
Development
JSTL
Java JSON tutorial
Java multithreading Tutorials
PM
Scrum
data structure and algorithm
java puzzles
java tips
testing
tips
windows 8
5 way to create Singleton Object
Architect Interview Questions and Answers
Architecture
Architecure
Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device.
C Programming
CIO
Callable Statement in Java
Circular dependency of Objects in Java
Comparable Example in Collection
Custom annotation in Java
Developer Interview
Divide and rule example in java
Drupal
Example of Singleton Pattern
FIX protocol
ForkJoin Example in Java 7
Get data from dynamic table with Java Script
Git
HTML and JavaScript
Health
Hello World TCP Client Server Networking Program
Hibernate Basics
Hibernate Interview Question Answer
J2EE Interview Question And Answers
J2ME GUI Program
JEE Interview QA
JMS interview question
Java J2EE Hibernate Spring Struts Interview Question
Java System Property
Java Threads
Manager
Portlets
Provident Fund
Read data from any file in same location and give the required result.
Reading Properties File in Java
Redpoint
Rest WebService Client
Rest Webservice Test
SAL join with ven diagram
SCP UNIX COMMAND
SSL
Singleton Pattern in Java
Spring Bean Initialization methods and their order
Spring Interview Questions
Struts
Struts 2.0 Basics
Struts 2.0 Design Pattern
Submit Html Form With Java Script On The Fly
Unix executable For Java Program
XOM DOM SAX
XP
books
computers
core java;
core java; object oriented programming
data structure; java investment bank;
design pattern
dtd
duplicate rows in table
get browser name with jquery
grails podcast
inner class
java beginners tutorial
java cache
java networking tutorial
java spring
java util; java collections; java questions
java.java1.5
linked list
mailto function with all browser
oracle database
oracle duplicate rows
orm
schema
social
spring mvc questions
struts
transaction
tricks
tweet
windows
xslt