SlideShare a Scribd company logo
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:
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
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
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.
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?
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?
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.

More Related Content

PPTX
Spring & hibernate
Santosh Kumar Kar
 
PPTX
Spring dependency injection
srmelody
 
PPTX
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
PDF
Hibernate Interview Questions
Syed Shahul
 
ODP
Dependency Injection in Spring in 10min
Corneil du Plessis
 
ODT
Types of Dependency Injection in Spring
Sunil kumar Mohanty
 
PDF
Hibernate Advance Interview Questions
Rudra Garnaik, PMI-ACP®
 
ODP
Hibernate Developer Reference
Muthuselvam RS
 
Spring & hibernate
Santosh Kumar Kar
 
Spring dependency injection
srmelody
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
Hibernate Interview Questions
Syed Shahul
 
Dependency Injection in Spring in 10min
Corneil du Plessis
 
Types of Dependency Injection in Spring
Sunil kumar Mohanty
 
Hibernate Advance Interview Questions
Rudra Garnaik, PMI-ACP®
 
Hibernate Developer Reference
Muthuselvam RS
 

What's hot (18)

ODP
Different Types of Containers in Spring
Sunil kumar Mohanty
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PPSX
Spring - Part 3 - AOP
Hitesh-Java
 
PDF
Leverage Hibernate and Spring Features Together
Edureka!
 
ODT
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
PDF
Introduction to Spring's Dependency Injection
Richard Paul
 
PPTX
Spring framework
Rajkumar Singh
 
PPT
EJB Clients
Roy Antony Arnold G
 
DOCX
Hibernate notes
Rajeev Uppala
 
PPTX
Hibernate ppt
Aneega
 
DOC
24 collections framework interview questions
Arun Vasanth
 
DOCX
Hibernate3 q&a
Faruk Molla
 
PPTX
Spring (1)
Aneega
 
PDF
Spring Framework -I
People Strategists
 
DOC
Hibernate tutorial for beginners
Rahul Jain
 
DOCX
Spring notes
Rajeev Uppala
 
PDF
Hibernate complete notes_by_sekhar_sir_javabynatara_j
Satya Johnny
 
PPSX
Struts 2 - Hibernate Integration
Hitesh-Java
 
Different Types of Containers in Spring
Sunil kumar Mohanty
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Spring - Part 3 - AOP
Hitesh-Java
 
Leverage Hibernate and Spring Features Together
Edureka!
 
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
Introduction to Spring's Dependency Injection
Richard Paul
 
Spring framework
Rajkumar Singh
 
EJB Clients
Roy Antony Arnold G
 
Hibernate notes
Rajeev Uppala
 
Hibernate ppt
Aneega
 
24 collections framework interview questions
Arun Vasanth
 
Hibernate3 q&a
Faruk Molla
 
Spring (1)
Aneega
 
Spring Framework -I
People Strategists
 
Hibernate tutorial for beginners
Rahul Jain
 
Spring notes
Rajeev Uppala
 
Hibernate complete notes_by_sekhar_sir_javabynatara_j
Satya Johnny
 
Struts 2 - Hibernate Integration
Hitesh-Java
 
Ad

Viewers also liked (17)

PDF
Spring 4 on Java 8 by Juergen Hoeller
ZeroTurnaround
 
PDF
Spring 4 Web App
Rossen Stoyanchev
 
PDF
Spring mvc my Faviourite Slide
Daniel Adenew
 
PDF
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Raghavan Mohan
 
PDF
Spring 3 Annotated Development
kensipe
 
PDF
What's new in Spring 3?
Craig Walls
 
PPTX
Spring @Transactional Explained
Smita Prasad
 
PPT
MVC Pattern. Flex implementation of MVC
Anton Krasnoshchok
 
PPTX
Spring MVC Architecture Tutorial
Java Success Point
 
PDF
Spring annotation
Rajiv Srivastava
 
PDF
Introduction to Spring MVC
Richard Paul
 
PPTX
SpringFramework Overview
zerovirus23
 
PPTX
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
ODP
Spring Mvc,Java, Spring
ifnu bima
 
PDF
Managing user's data with Spring Session
David Gómez García
 
PDF
Spring 4 - A&BP CC
JWORKS powered by Ordina
 
PPT
Spring 3.x - Spring MVC
Guy Nir
 
Spring 4 on Java 8 by Juergen Hoeller
ZeroTurnaround
 
Spring 4 Web App
Rossen Stoyanchev
 
Spring mvc my Faviourite Slide
Daniel Adenew
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Raghavan Mohan
 
Spring 3 Annotated Development
kensipe
 
What's new in Spring 3?
Craig Walls
 
Spring @Transactional Explained
Smita Prasad
 
MVC Pattern. Flex implementation of MVC
Anton Krasnoshchok
 
Spring MVC Architecture Tutorial
Java Success Point
 
Spring annotation
Rajiv Srivastava
 
Introduction to Spring MVC
Richard Paul
 
SpringFramework Overview
zerovirus23
 
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Spring Mvc,Java, Spring
ifnu bima
 
Managing user's data with Spring Session
David Gómez García
 
Spring 4 - A&BP CC
JWORKS powered by Ordina
 
Spring 3.x - Spring MVC
Guy Nir
 
Ad

Similar to 02 java spring-hibernate-experience-questions (20)

PPT
Spring framework
Ajit Koti
 
PDF
Spring
gauravashq
 
PDF
Spring
gauravashq
 
PDF
Spring
gauravashq
 
PPTX
Spring core
Harshit Choudhary
 
DOCX
Spring Fa Qs
jbashask
 
PPTX
Java J2EE Interview Questions Part 2
javatrainingonline
 
PPTX
Java J2EE Interview Question Part 2
Mindsmapped Consulting
 
PDF
Introduction to Spring Framework
Rajind Ruparathna
 
PDF
Ejb - september 2006
achraf_ing
 
PPTX
Spring Basics
ThirupathiReddy Vajjala
 
PPT
Spring talk111204
ealio
 
PPT
Hibernate Session 1
b_kathir
 
PDF
Spring 2
Aruvi Thottlan
 
PDF
Hibernate.pdf
SaadAnsari73
 
PDF
Hibernate 3
Rajiv Gupta
 
PDF
Hibernate Interview Questions | Edureka
Edureka!
 
PPTX
Spring IOC and DAO
AnushaNaidu
 
PPTX
Introduction to Spring Framework
Dineesha Suraweera
 
PPT
Spring talk111204
s4al_com
 
Spring framework
Ajit Koti
 
Spring
gauravashq
 
Spring
gauravashq
 
Spring
gauravashq
 
Spring core
Harshit Choudhary
 
Spring Fa Qs
jbashask
 
Java J2EE Interview Questions Part 2
javatrainingonline
 
Java J2EE Interview Question Part 2
Mindsmapped Consulting
 
Introduction to Spring Framework
Rajind Ruparathna
 
Ejb - september 2006
achraf_ing
 
Spring talk111204
ealio
 
Hibernate Session 1
b_kathir
 
Spring 2
Aruvi Thottlan
 
Hibernate.pdf
SaadAnsari73
 
Hibernate 3
Rajiv Gupta
 
Hibernate Interview Questions | Edureka
Edureka!
 
Spring IOC and DAO
AnushaNaidu
 
Introduction to Spring Framework
Dineesha Suraweera
 
Spring talk111204
s4al_com
 

Recently uploaded (20)

PPTX
原版北不列颠哥伦比亚大学毕业证文凭UNBC成绩单2025年新版在线制作学位证书
e7nw4o4
 
PDF
Data Protection & Resilience in Focus.pdf
AmyPoblete3
 
PPTX
dns domain name system history work.pptx
MUHAMMADKAVISHSHABAN
 
PPTX
ppt lighfrsefsefesfesfsefsefsefsefserrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrt.pptx
atharvawafgaonkar
 
PPTX
Unlocking Hope : How Crypto Recovery Services Can Reclaim Your Lost Funds
lionsgate network
 
PPTX
Perkembangan Perangkat jaringan komputer dan telekomunikasi 3.pptx
Prayudha3
 
PPTX
AI ad its imp i military life read it ag
ShwetaBharti31
 
PDF
PDF document: World Game (s) Great Redesign.pdf
Steven McGee
 
PPTX
Pengenalan perangkat Jaringan komputer pada teknik jaringan komputer dan tele...
Prayudha3
 
PPTX
Crypto Recovery California Services.pptx
lionsgate network
 
PDF
DNSSEC Made Easy, presented at PHNOG 2025
APNIC
 
PPTX
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
PPTX
办理方法西班牙假毕业证蒙德拉贡大学成绩单MULetter文凭样本
xxxihn4u
 
PDF
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
PPTX
B2B_Ecommerce_Internship_Simranpreet.pptx
LipakshiJindal
 
PPTX
Artificial-Intelligence-in-Daily-Life (2).pptx
nidhigoswami335
 
PPTX
LESSON-2-Roles-of-ICT-in-Teaching-for-learning_123922 (1).pptx
renavieramopiquero
 
PPTX
EthicalHack{aksdladlsfsamnookfmnakoasjd}.pptx
dagarabull
 
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
APNIC
 
PDF
BGP Security Best Practices that Matter, presented at PHNOG 2025
APNIC
 
原版北不列颠哥伦比亚大学毕业证文凭UNBC成绩单2025年新版在线制作学位证书
e7nw4o4
 
Data Protection & Resilience in Focus.pdf
AmyPoblete3
 
dns domain name system history work.pptx
MUHAMMADKAVISHSHABAN
 
ppt lighfrsefsefesfesfsefsefsefsefserrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrt.pptx
atharvawafgaonkar
 
Unlocking Hope : How Crypto Recovery Services Can Reclaim Your Lost Funds
lionsgate network
 
Perkembangan Perangkat jaringan komputer dan telekomunikasi 3.pptx
Prayudha3
 
AI ad its imp i military life read it ag
ShwetaBharti31
 
PDF document: World Game (s) Great Redesign.pdf
Steven McGee
 
Pengenalan perangkat Jaringan komputer pada teknik jaringan komputer dan tele...
Prayudha3
 
Crypto Recovery California Services.pptx
lionsgate network
 
DNSSEC Made Easy, presented at PHNOG 2025
APNIC
 
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
办理方法西班牙假毕业证蒙德拉贡大学成绩单MULetter文凭样本
xxxihn4u
 
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
B2B_Ecommerce_Internship_Simranpreet.pptx
LipakshiJindal
 
Artificial-Intelligence-in-Daily-Life (2).pptx
nidhigoswami335
 
LESSON-2-Roles-of-ICT-in-Teaching-for-learning_123922 (1).pptx
renavieramopiquero
 
EthicalHack{aksdladlsfsamnookfmnakoasjd}.pptx
dagarabull
 
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
APNIC
 
BGP Security Best Practices that Matter, presented at PHNOG 2025
APNIC
 

02 java spring-hibernate-experience-questions

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