The document contains questions related to Java Spring and Hibernate concepts and implementations. Some key concepts discussed include:
- Dependency injection and inversion of control in Spring
- Differences between Spring BeanFactory and ApplicationContext
- Typical bean lifecycle in Spring container
- Benefits of using an ORM tool like Hibernate
- General flow of communication between Hibernate and a relational database
1. Java Spring+Hibernate Questions
Section A: Conceptual Questions
(Let’s see how good you are at googling. )
1. What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not
create your objects but describe how they should be created. You don't directly connect your components and
services together in code but describe which services are needed by which components in a configuration file.
A container is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that
coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an
inversion of responsibility with regard to how an object obtains references to collaborating objects.
2. What is the difference between Bean Factory and Application Context?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean
Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
BeanFactory is able to create associations between collaborating objects as they are instantiated.
This removes the burden of configuration from bean itself and the beans client.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and
destruction methods.
ApplicationContext is an extension of BeanFactory functionalities with following features
Application contexts provide a means for resolving text messages, including support for i18n of
those messages.
Application contexts provide a generic way to load file resources, such as images.
Application contexts can publish events to beans that are registered as listeners.
ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling
low-level resources. An application context itself is a ResourceLoader, Hence provides an
application with access to deployment-specific Resource instances.
3. What is the typical Bean life cycle in Spring Bean Factory Container?
Bean life cycle in Spring Bean Factory Container is as follows:
2. Java Spring+Hibernate Questions
The spring container finds the bean’s definition from the XML file and instantiates the bean.
Using the dependency injection, spring populates all of the properties as specified in the bean
definition
If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the
bean’s ID.
If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing
an instance of itself.
If there are any BeanPostProcessors associated with the bean, their post-
ProcessBeforeInitialization() methods will be called.
If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated with the bean,
their postProcessAfterInitialization() methods will be called.
4. 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 : A lot less code to write
Improved portability : ORM framework generates database-specific SQL for you
5. What is the general flow of Hibernate communication with RDBMS?
Load the Hibernate configuration file and create configuration object. It will automatically load all
mapping files
Create session factory from configuration object
Get one session from this session factory
3. Java Spring+Hibernate Questions
Create HQL Query
Execute query to get list containing Java objects
Section B: Implementation Questions
(Please do not tell me you have only got training but never worked on project)
6. What are the types of Dependency Injection Spring supports?
Setter Injection: Setter-based DI is realized by calling setter methods on the beans after invoking a
no-argument constructor or no-argument static factory method to instantiate the bean.
Constructor Injection: Constructor-based DI is realized by invoking a constructor with a number of
arguments, each representing a collaborator.
7. What are Bean Scopes supported by Spring Framework?
In Spring Framework, bean scope is used to decide which type of bean instance should be return from Spring
container back to the caller.
5 types of bean scopes supported:
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request. *
session – Return a single bean instance per HTTP session. *
globalSession – Return a single bean instance per global HTTP session. *
8. What are various methods used to integrate Hibernate with Spring?
Local Session Factory: This is spring factory bean class which creates Hibernate Session Factory.
The hibernate configuration properties can be passed within the XML. The configuration properties
include hibernate mapping resources, hibernate properties and a data source.
Annotation Session Factory: This is a subclass of Local Session Factory but supports annotation
based mappings.
Hibernate Template: Spring provides a class that helps in accessing the database via hibernate. One
of its main features is mapping of hibernate exceptions to Data Access Exceptions. Hibernate
Template also takes care of obtaining or releasing sessions The Session Factory is injected into
Hibernate Template. Spring manages the creation and shutting down of the factory. Hibernate
Template provides methods such as find, saveOrUpdate, persist, delete etc that performs the
corresponding function in hibernate but manages sessions and exceptions.
Hibernate Dao Support: This class is a convenience class for hibernate based database access. This is
a wrapper over Hibernate Template. It can be initialized using a Session Factory. It creates the
4. Java Spring+Hibernate Questions
Hibernate Template and subclasses can use the getHibernateTemplate() method to obtain the
Hibernate Template and then perform operations on it.
9. Explain with example declarative inheritance of Beans
A bean definition potentially contains a large amount of configuration information, including container
specific information (for example initialization method, static factory method name, and so forth) and
constructor arguments and property values. A child bean definition is a bean definition that inherits
configuration data from a parent definition. It is then able to override some values, or add others, as needed.
Using parent and child bean definitions potentially helps code reusability.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="beanTeamplate" abstract="true">
<property name="message1" value="Hello World!"/>
<property name="message2" value="Hello Second World!"/>
<property name="message3" value="Namaste India!"/>
</bean>
<bean id="helloIndia" class="com.tutorialspoint.HelloIndia"
parent="beanTeamplate">
<property name="message1" value="Hello India!"/>
<property name="message3" value="Namaste India!"/>
</bean>
</beans>
10.Which types of collections are supported by Spring Bean declarations?
List – <list/>
Set – <set/>
Map – <map/>
Properties – <props/>
11. What are the general considerations or best practices for defining Hibernate
persistent classes?
1. You must have a default no-argument constructor for your persistent classes
2. There should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your
persistable instance variables.
3. 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.
4. It is recommended to implement the Serializable interface. This is potentially useful if you want to
migrate around a multi-processor cluster.
5. Java Spring+Hibernate Questions
5. The persistent class should not be final because if it is final then lazy loading cannot be used by
creating proxy objects.
6. Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are
less verbose than *.hbm.xml files.
12. What is difference between transient, persistent and detached object in Hibernate?
Persistent: An object which is associated with Hibernate session is called persistent object. Any
change in this object will reflect in database based upon your flush strategy i.e. automatic flush
whenever any property of object change or explicit flushing by calling Session.flush() method.
Detached: On the other hand if an object which is earlier associated withSession, but currently not
associated with it are called detached object. You can reattach detached object to any other session
by calling either update() or saveOrUpdate() method on that session.
Transient: Objects are newly created instance of persistence class, which is never associated with
any Hibernate Session. Similarly you can call persist() or save() methods to make transient object
persistent.
13. What features does Hibernate support using Criteria?
Restrictions: You can use add() method available for Criteria object to add restriction for a criteria
query. Using Criterion we can also create and/or logical expressions. Various restrictions supported
are equals, greater than ,less than , between , greater than or equal to, etc.
Pagination: Using setFirstResult and setMaxResults methods we can implement pagination.
Sorting: The Criteria API provides the Order class to sort your result set in either ascending or
descending order, according to one of object's properties.
Projections (Aggregations): Projections class is provided which can be used to get average,
maximum or minimum property values.
14.What are the Collection types in Hibernate?
Bag
Set
List
Array
Map
15. What are the different fetching strategies in Hibernate?
6. Java Spring+Hibernate Questions
Hibernate3 defines the following fetching strategies:
Join fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using
an OUTER JOIN.
Select fetching: a second SELECT is used to retrieve the associated entity or collection. Unless you
explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed
when you actually access the association.
Subselect fetching: a second SELECT is used to retrieve the associated collections for all entities
retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying
lazy="false", this second select will only be executed when you actually access the association.
Batch fetching: Hibernate retrieves a batch of entity instances or collections in a single SELECT, by
specifying a list of primary keys or foreign keys.
16. What is the difference between sorted and ordered collection in Hibernate?
Sorted collection
o A sorted collection is sorting a collection by utilizing the sorting features provided by the
Java collections. The sorting occurs in the memory of JVM which running Hibernate, after
the data being read from database using java comparator.
o If your collection is not large, it will be more efficient way to sort it.
o As it happens in jvm memory, it can throw Out of Memory error.
Order collection
o Order collection is sorting a collection by specifying the order-by clause in query for sorting
this collection when retrieval.
o If your collection is very large, it will be more efficient way to sort it.
Section C: Advance Questions
(Fadu…who is the boss kind of questions)
17. What are the common implementations of the Application Context?
The three commonly used implementation of ‘Application Context’ are
Classpath Xml Application Context: It Loads context definition from an XML file located in the
classpath, treating context definitions as classpath resources. The application context is loaded from
the application’s classpath by using the code .
FileSystem Xml Application Context: It loads context definition from an XML file in the filesystem.
Web Application Context: It loads context definition from an XML file contained within a web
application.
18.What are core modules in Spring Framework?
7. Java Spring+Hibernate Questions
Spring have seven core modules
1. The Core container module
2. Application context module
3. AOP module (Aspect Oriented Programming)
4. JDBC abstraction and DAO module
5. O/R mapping integration module (Object/Relational)
6. Web module
7. MVC framework module
19. Which query language SQL or HQL do Derived fields use in Hibernate?
SQL, because derived or read-only fields can use only actual column names and not property names
like HQL.
20.What are drawbacks of using Hibernate?
Outer Joins: Hibernate does not support outer joins either by Criteria or HQL. The only option
left for developer is using SQL query. There are two major drawbacks of using SQL
1. Hibernate promises independence from underlying database. This is no longer valid once
SQL query is used.
2. ORM is longer consistent as column names in result set of outer join are controlled by
underlying database. A different POJO needs to be created for objects which might work
entirely based on Hibernate Framework if queried individually using HQL or criteria.
Debugging: It is easier to debug prepared statements in direct JDBC than analysing and
debugging generated Hibernate query.
Criteria: This is one of the bitter-sweet aspect of using Hibernate. Criteria easies creation of
filters but it also spreads out entire query in java code as small bits and pieces, with complex
coding for web applications it can become extremely difficult to verify integrity of query.
Optimisation : Query optimization available is limited to framework.