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

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
 

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)

PPTX
Java J2EE Interview Question Part 2
Mindsmapped Consulting
 
PPTX
Java J2EE Interview Questions Part 2
javatrainingonline
 
PDF
Hibernate interview questions
venkata52
 
PDF
Hibernate reference1
chandra mouli
 
PDF
Spring 2
Aruvi Thottlan
 
PPT
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
PPT
Spring, web service, web server, eclipse by a introduction sandesh sharma
Sandesh Sharma
 
DOCX
Spring Fa Qs
jbashask
 
PPT
Spring introduction
AnilKumar Etagowni
 
PDF
Hibernate 3
Rajiv Gupta
 
PDF
Manual tutorial-spring-java
sagicar
 
PDF
Spring Reference
asas
 
PPTX
Hibernate tutorial
Mumbai Academisc
 
PDF
Spring Reference
Syed Shahul
 
PPTX
Introduction to Spring Framework
Dineesha Suraweera
 
PPTX
Hibernate in XPages
Toby Samples
 
PDF
Spring db-access mod03
Guo Albert
 
PPT
Spring talk111204
ealio
 
PPT
Spring training
shah_d_p
 
PDF
Hibernate complete notes_by_sekhar_sir_javabynatara_j
Satya Johnny
 
Java J2EE Interview Question Part 2
Mindsmapped Consulting
 
Java J2EE Interview Questions Part 2
javatrainingonline
 
Hibernate interview questions
venkata52
 
Hibernate reference1
chandra mouli
 
Spring 2
Aruvi Thottlan
 
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
Spring, web service, web server, eclipse by a introduction sandesh sharma
Sandesh Sharma
 
Spring Fa Qs
jbashask
 
Spring introduction
AnilKumar Etagowni
 
Hibernate 3
Rajiv Gupta
 
Manual tutorial-spring-java
sagicar
 
Spring Reference
asas
 
Hibernate tutorial
Mumbai Academisc
 
Spring Reference
Syed Shahul
 
Introduction to Spring Framework
Dineesha Suraweera
 
Hibernate in XPages
Toby Samples
 
Spring db-access mod03
Guo Albert
 
Spring talk111204
ealio
 
Spring training
shah_d_p
 
Hibernate complete notes_by_sekhar_sir_javabynatara_j
Satya Johnny
 
Ad

Recently uploaded (20)

PPTX
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
PDF
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
PDF
Strategic Plan New and Completed Templeted
alvi932317
 
PDF
AI security AI security AI security AI security
elite44
 
PPTX
Academic Debate: Creation vs Evolution.pptx
JOHNPATRICKMARTINEZ5
 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PDF
The Hidden Benefits of Outsourcing IT Hardware Procurement for Small Businesses
Carley Cramer
 
PPTX
Meloniusk_Communication_Template_best.pptx
howesix147
 
PDF
The Internet - By the numbers, presented at npNOG 11
APNIC
 
PPTX
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
PDF
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
PDF
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
ssuser73bdb11
 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
PDF
FutureCon Seattle 2025 Presentation Slides - You Had One Job
Suzanne Aldrich
 
PPTX
Networking_Essentials_version_3.0_-_Module_5.pptx
ryan622010
 
PPTX
原版一样(LHU毕业证书)英国利物浦希望大学毕业证办理方法
Taqyea
 
PDF
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
PDF
web application development company in bangalore.pdf
https://dkpractice.co.in/seo.html tech
 
PPTX
西班牙巴利阿里群岛大学电子版毕业证{UIBLetterUIB文凭证书}文凭复刻
Taqyea
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
Strategic Plan New and Completed Templeted
alvi932317
 
AI security AI security AI security AI security
elite44
 
Academic Debate: Creation vs Evolution.pptx
JOHNPATRICKMARTINEZ5
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
The Hidden Benefits of Outsourcing IT Hardware Procurement for Small Businesses
Carley Cramer
 
Meloniusk_Communication_Template_best.pptx
howesix147
 
The Internet - By the numbers, presented at npNOG 11
APNIC
 
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
ssuser73bdb11
 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
FutureCon Seattle 2025 Presentation Slides - You Had One Job
Suzanne Aldrich
 
Networking_Essentials_version_3.0_-_Module_5.pptx
ryan622010
 
原版一样(LHU毕业证书)英国利物浦希望大学毕业证办理方法
Taqyea
 
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
web application development company in bangalore.pdf
https://dkpractice.co.in/seo.html tech
 
西班牙巴利阿里群岛大学电子版毕业证{UIBLetterUIB文凭证书}文凭复刻
Taqyea
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 

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.