Archive for March 2014

Hibernate Interview Questions and Answers


Hibernate Interview Questions and Answers


What is Hibernate?



Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users <span class="ilad">to develop</span> persistent classes following object-oriented principles such as association, inheritance, polymorphism, <span class="ilad">composition</span>, and collections.


What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java <span class="ilad">application</span> in to the tables of a relational database using the metadata that
describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

Why hibernate is advantageous over Entity Beans and JDBC?

An entity bean always works under the EJB container, which allows reusing of the object external to the container. An object can not be detached in entity beans and in hibernate detached objects are supported.<br />Hibernate is not database dependent where as JDBC is database dependent. Query tuning is not needed for hibernate as JDBC is needed. Data can be placed in multiple cache which is supported by
hibernate, whereas in JDBC the cache is to be implemented.&nbsp;


What are the different levels of ORM quality?

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. <br />
<br />
" 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. <br />
<br />
" 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.


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.


Define HibernateTemplate?

<i>org.springframework.orm.hibernate.HibernateTemplate</i> is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.


What are the benefits does HibernateTemplate provide?


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.


How will you configure Hibernate?

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.


Difference between get and load in Hibernate?


get vs load is one of the most frequently asked Hibernate Interview question, since correct understanding of both get() and load() is require to effectively using Hibernate. Main difference between get and load is that, get will hit the database if object is not found in the cache and returned completely initialized object, which may involve several database call while load() method can return proxy, if object is not found in cache and only hit database if any method other thangetId() is called. This can save lot of performance in some cases. You can also see difference between get and load in Hibernate for more differences and detailed discussion on this question.



Difference between save, persist and saveOrUpdate methods in Hibernate?


After get vs load, this is another Hibernate Interview question which appears quite often. All three methods i.e. save(), saveOrUpdate() and persist() is used to save objects into database, but has subtle differences e.g. save() can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records. Also, return type of save() is a Serializable object, while return type of persist() method is void. You can also check save vs persist vs saveOrUpdatefor complete differences between them in hibernate.


What is named SQL query in Hibernate?


This Hibernate Interview question is related to query functionality provided by Hibernate. Named queries are SQL queries which are defined in mapping document using <sql-query> tag and called using Session.getNamedQuery() method. Named query allows you to refer a particular query by the name you provided, by the way you can define named query in hibernate either by using annotations or xml mapping file, as I said above. @NameQuery is used to define single named query and @NameQueries is used to define multiple named query in hibernate.



What is SessionFactory in Hibernate? is SessionFactory thread-safe?


Another common Interview questions related to Hibernate framework. SessionFactory as name suggest is a factory to create hibernate Session objects. SessionFactory is often built during start-up and used by application code to get session object. It acts as single data store and its also thread-safe so that multiple thread can use same SessionFactory. Usually a Java JEE application has just one SessionFactory, and individual threads, which are servicing client’s request obtain hibernate Session instances from this factory, that’s why any implementation of SessionFactory interface must be thread-safe. Also internal state of SessionFactory, which contains all meta data about Object/Relational mapping is Immutable and can not be changed once created.


What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate?


This is usually asked as follow-up question of previous Hibernate Interview question. After SessionFactory its time for Session. Session represent a small unit of work in Hibernate, they maintain connection with database and they are not thread-safe, it means you can not share Hibernate Session between multiple threads. Though Session obtains database connection lazily it's good to close session as soon as you are done with it.


What is difference between sorted and ordered collection in hibernate?


This is one of the easy Hibernate interview question you ever face. A sorted collection is sorted in memory by using Java Comparator, while a ordered collection uses database's order by clause for ordering. For large data set it's better to use ordered collection to avoid any OutOfMemoryError in Java, by trying to sort them in memory.


What is difference between transient, persistent and detached object in Hibernate?


In Hibernate, Object can remain in three state transient, persistent or detached. 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. On the other hand if an object which is earlier associated with Session, 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. Just remember, here transient doesn’t represent transient keyword in Java, which is altogether different thing.


What does Session lock() method do in Hibernate?


This one is one of the tricky Hibernate Interview question, because Session's lock() method reattach object without synchronizing or updating with database. So you need to be very careful while using lock() method. By the way you can always use Session's update() method to sync with database during reattachment. Some time this Hibernate question is also asked as what is difference between Session's lock() and update() method. You can use this key point to answer that question as well.

What is Second level Cache in Hibernate?


This is one of the first interview question related to caching in Hibernate, you can expect few more. Second level Cache is maintained at SessionFactory level and can improve performance by saving few database round trip. Another worth noting point is that second level cache is available to whole application rather than any particular session.

What is query cache in Hibernate ?


This question, Some times asked as a follow-up of last Hibernate Interview question, QueryCache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. Hibernate support various open source caching solution to implement Query cache e.g. EhCache.


Why it's important to provide no argument constructor in Hibernate Entities?


Every Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API, by calling Class.newInstance() method. This method will throw InstantiationException if it doesn't found no argument constructor inside Entity class.


Can we make an Hibernate Entity Class final?

Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn't allow extension of final class, thus limiting your performance improvement options. Though, you can avoid this penalty, if your persistent class is an implementation of interface, which declares all public methods defined in Entity class.



What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the most important one.

  • Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
  • SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
  • Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
  • Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
  • Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.

What are Callback interfaces?

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.



What are Extension interfaces?

When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.



What are the Extension interfaces that are there in hibernate?

There are many extension interfaces provided by hibernate.

  • ProxyFactory interface – used to create proxies
  • ConnectionProvider interface – used for JDBC connection management
  • TransactionFactory interface – Used for transaction management
  • Transaction interface – Used for transaction management
  • TransactionManagementLookup interface – Used in transaction management.
  • Cahce interface – provides caching techniques and strategies
  • CacheProvider interface – same as Cache interface
  • ClassPersister interface – provides ORM strategies
  • IdentifierGenerator interface – used for primary key generation
  • Dialect abstract class – provides SQL support


What are different environments to configure hibernate?

There are mainly two types of environments in which the configuration of hibernate application differs.
  1. Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere.
  2. Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.



What is meant by Method chaining?

Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining.


1SessionFactory sessions = new Configuration()
2 .addResource("myinstance/MyConfig.hbm.xml")
3  .setProperties( System.getProperties() )
4 .buildSessionFactory();



What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.


What are the different methods of identifying an object?

  • There are three methods by which an object can be identified.
  • Object identity – Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator.
  • Object equality – Objects are equal if they have the same value, as defined by the equals( ) method. Classes that don’t explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity.
  • Database identity – Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value.

What are the different approaches to represent an inheritance hierarchy?
  • Table per concrete class.
  • Table per class hierarchy.
  • Table per subclass.

What are managed associations and hibernate associations?

Associations that are related to container management persistence are called managed associations. These are bi-directional associations. Coming to hibernate associations, these are unidirectional.


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?


How do you invoke Stored Procedures?

{ ? = call selectAllEmployees() }


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();


What are the benefits does HibernateTemplate provide?


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

If you want to see the Hibernate generated SQL statements on console, what should we do?

In Hibernate configuration file set as follows:
set show_sql property to true in configuration file.


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.

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.

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. You can update object in database by using session.flush() method.
  • Detached -The instance was associated with a persistence context which has been closed – currently not associated. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session.

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.



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;


What is Second level Cache and QueryCache in Hibernate?

Second level Cache is maintained at SessionFactory level and It improves performance by saving few database round trip. Another worth noting point is that second level cache is available to whole application rather than any particular session.

QueryCache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. Hibernate support various open source caching solution to implement Query cache e.g. EhCache.

Spring Interview Questions Answers J2EE



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 (in the case of the Spring framework, the IOC 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. 

What are the different types of IOC (dependency injection) ? 

There are three types of dependency injection:
  • Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
  • Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection (e.g. Avalon): Injection is done through an interface.

  • Note: Spring supports only Constructor and Setter Injection

What are the benefits of IOC (Dependency Injection)?

Benefits of IOC (Dependency Injection) are as follows:

Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
  • Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
  • Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
  • IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

What is Spring ?

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.

What are the advantages of Spring framework?

The advantages of Spring are as follows:
  • Spring has layered architecture. Use what you need and leave you don't need now.
  • Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
  • Dependency Injection and Inversion of Control Simplifies JDBC
  • Open source and no vendor lock-in.

What are features of Spring ?

  • spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
  • Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
  • Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
  • Spring contains and manages the life cycle and configuration of application objects.
  • Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
  • Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
  • The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

What are the types of Dependency Injection Spring supports?>

  • Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

  • Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.

What is the difference between Bean Factory and Application Context ?  

On the surface, an application context is same as a bean factory. But application context offers much more..
  • 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.

  • Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.

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

  • MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable

What is Application Context?

A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
  • A means for resolving text messages, including support for internationalization.
  • A generic way to load file resources.
  • Events to beans that are registered as listeners.

What is Bean Factory ?

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.

How many modules are there in Spring? What are they?
(Roll over to view the Image )
Spring Framework Modules
       Spring comprises of seven modules. They are..
  • The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.

  • The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.

  • The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

  • The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

  • The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.

  • The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.

  • The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.

What are the common implementations of the Application Context ?

   The three commonly used implementation of 'Application Context' are
  • ClassPathXmlApplicationContext : 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 .

  • ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
  • FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .

  • ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
  • XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

How is a typical spring implementation look like ?

   For a typical Spring Application we need the following files:
  • An interface that defines the functions.
  • An Implementation that contains properties, its setter and getter methods, functions etc.,
  • Spring AOP (Aspect Oriented Programming)
  • A XML file called Spring configuration file.
  • Client program that uses the function.

What is the typical Bean life cycle in Spring Bean Factory Container ?

   Bean life cycle in Spring Bean Factory Container is as follows:
  • 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.

What do you mean by Bean wiring ? 

The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring.

What do you mean by Auto Wiring?

   The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.
  • no
  • byName
  • byType
  • constructor
  • autodirect

What is DelegatingVariableResolver?

       Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This variable resolver is called as DelegatingVariableResolver

How to integrate your Struts application with Spring?  

To integrate your Struts application with Spring, we have two options:
  • Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.

  • Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.


What is IOC or inversion of control?


Answer: This Spring interview question is first step towards Spring framework and many interviewer starts Spring interview from this question. As the name implies Inversion of control means now we have inverted the control of creating the object from our own using new operator to container or framework. Now it’s the responsibility of container to create object as required. We maintain one xml file where we configure our components, services, all the classes and their property. We just need to mention which service is needed by which component and container will create the object for us. This concept is known as dependency injection because all object dependency (resources) is injected into it by framework.

Example:
  <bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont">
        <property name="newBid"/>
  </bean>
In this example CreateNewStockAccont class contain getter and setter for newBid and container will instantiate newBid and set the value automatically when it is used. This whole process is also called wiring in Spring and by using annotation it can be done automatically by Spring, refereed as auto-wiring of bean in Spring.


Explain Bean-LifeCycle. 


Ans: Spring framework is based on IOC so we call it as IOC container also So Spring beans reside inside the IOC container. Spring beans are nothing but Plain old java object (POJO).
Following steps explain their life cycle inside container.

1. Container will look the bean definition inside configuration file (e.g. bean.xml).
2 using reflection container will create the object and if any property is defined inside the bean definition then it will also be set.
3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization()methods will be called before the properties for the Bean are set.
6. If an init() method is specified for the bean, it will be called.
7. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.
8. If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.


what is Bean Factory, have you used XMLBeanFactory?

Ans: BeanFactory is factory Pattern which is based on IOC design principles.it is used to make a clear separation between application configuration and dependency from actual code.
XmlBeanFactory is one of the implementation of bean Factory which we have used in our project.
org.springframework.beans.factory.xml.XmlBeanFactory is used to create bean instance defined in our xml file.
BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));
Or
ClassPathResource resorce = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(resorce);


What are the difference between BeanFactory and ApplicationContext in spring?

Answer : This one is very popular spring interview question and often asks in entry level interview. ApplicationContext is preferred way of using spring because of functionality provided by it and interviewer wanted to check whether you are familiar with it or not.

ApplicationContext.

BeanFactory
Here we can have more than one config files possible
In this only one config file or .xml file
Application contexts can publish events to beans that are registered as listeners
Doesn’t support.
Support internationalization (I18N) messages
It’s not
Support application life-cycle events, and validation.
Doesn’t support.
Support  many enterprise services such JNDI access, EJB integration, remoting
Doesn’t support.


What are different modules in spring?

Answer : 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




What is difference between singleton and prototype bean?

Ans: This is another popular spring interview questions and an important concept to understand. Basically a bean has scopes which defines their existence on the application

Singleton: means single bean definition to a single object instance per Spring IOC container.
Prototype: means a single bean definition to any number of object instances.
Whatever beans we defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

  <bean id="createNewStock"     class="springexample.stockMarket.CreateNewStockAccont" singleton=”false”>
        <property name="newBid"/>
  </bean>

What type of transaction Management Spring support?

Ans: This spring interview questions is little difficult as compared to previous questions just because transaction management is a complex concept and not every developer familiar with it. Transaction management is critical in any applications that will interact with the database. The application has to ensure that the data is consistent and the integrity of the data is maintained.  Two type of transaction management is supported by spring

1. Programmatic transaction management
2. Declarative transaction management.


What is AOP?


Answer : The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP is a programming technique that allows developer to modularize crosscutting concerns,  that cuts across the typical divisions of responsibility, such as logging and transaction management. Spring AOP, aspects are implemented using regular classes or regular classes annotated with the @Aspect annotation

Explain Advice?

Answer: It’s an implementation of aspect; advice is inserted into an application at join points. Different types of advice include “around,” “before” and “after” advice

What is joint Point and point cut?

Ans: This is not really a spring interview questions I would say an AOP one.  Similar to Object oriented programming, AOP is another popular programming concept which complements OOPS. Join point is an opportunity within code for which we can apply an aspect. In Spring AOP, a join point always represents a method execution.
Pointcut: a predicate that matches join points. A point cut is something that defines at what join-points an advice should be applied


What is RowCallbackHandler ?

   The RowCallbackHandler interface extracts values from each row of a ResultSet.
  • Has one method – processRow(ResultSet)
  • Called for each row in ResultSet.
  • Typically stateful.

What is SQLProvider ?

   SQLProvider:
  • Has one method – getSql()
  • Typically implemented by PreparedStatementCreator implementers.
  • Useful for debugging.

What is PreparedStatementCreator ?

   PreparedStatementCreator:
  • Is one of the most common used interfaces for writing data to database.
  • Has one method – createPreparedStatement(Connection)
  • Responsible for creating a PreparedStatement.
  • Does not need to handle SQLExceptions.


What is SQLExceptionTranslator ?

SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnosticorg.springframework.dao.DataAccessException.

What are ORM’s Spring supports ? 

   Spring supports the following ORM’s :
  • Hibernate
  • iBatis
  • JPA (Java Persistence API)
  • TopLink
  • JDO (Java Data Objects)
  • OJB

What are the ways to access Hibernate using Spring ?

   There are two approaches to Spring’s Hibernate integration:
  • Inversion of Control with a HibernateTemplate and Callback
  • Extending HibernateDaoSupport and Applying an AOP Interceptor

How to integrate Spring and Hibernate using HibernateDaoSupport?

   Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
  • Configure the Hibernate SessionFactory
  • Extend your DAO Implementation from HibernateDaoSupport
  • Wire in Transaction Support with AOP

What are Bean scopes in Spring Framework ?

   The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). The scopes supported are listed below:

ScopeDescription
singleton
Scopes a single bean definition to a single object instance per Spring IoC container.
prototype
Scopes a single bean definition to any number of object instances.
request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware SpringApplicationContext.

What is AOP?

   Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.


How the AOP used in Spring?

   AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on the Spring Framework's transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP. 


What do you mean by Aspect ?

   A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).


What do you mean by JointPoint?

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.


What do you mean by Advice?

Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point.


What are the types of Advice?

Types of advice:
  • Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

  • After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.

  • After throwing advice: Advice to be executed if a method exits by throwing an exception.

  • After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).

  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception

What are the types of the transaction management Spring supports ?

   Spring Framework supports:
  • Programmatic transaction management.
  • Declarative transaction management.

What are the benefits of the Spring Framework transaction management ?

   The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:
  • Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
  • Supports declarative transaction management.
  • Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
  • Integrates very well with Spring's various data access abstractions.

Why most users of the Spring Framework choose declarative transaction management ?
   Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container.


Explain the similarities and differences between EJB CMT and the Spring Framework's declarative transaction  management ?

   The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to individual method level. It is
    possible to make a setRollbackOnly() call within a transaction context if necessary.
The differences are:
Unlike EJB CMT, which is tied to JTA, the Spring ramework's declarative transaction management works in any environment. It can work with JDBC, JDO, Hibernate or other transactions under the covers, with configuration changes only.

  • The Spring Framework enables declarative transaction management to be applied to any class, not merely special classes such as EJBs.

  • The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided.

  • The Spring Framework gives you an opportunity to customize transactional behavior, using AOP. With EJB CMT, you have no way to influence the container's transaction management other than setRollbackOnly().

  • The Spring Framework does not support propagation of transaction contexts across remote calls, as do high-end application servers.

When to use programmatic and declarative transaction management ?

   Programmatic transaction management is usually a good idea only if you have a small number of transactional operations.
On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure. 

Explain about the Spring DAO support ?

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.


What are the exceptions thrown by the Spring DAO classes ?

Spring DAO classes throw exceptions which are subclasses ofDataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception.



What is Spring's JdbcTemplate

Spring's JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling. 
JdbcTemplate template = new JdbcTemplate(myDataSource);

What are the differences between EJB and Spring ?

   Spring and EJB feature comparison.
FeatureEJBSpring
Transaction management
  • Must use a JTA transaction manager.
  • Supports transactions that span remote method calls.
  • Supports multiple transaction environments through itsPlatformTransactionManager interface, including JTA, Hibernate, JDO, and JDBC.
  • Does not natively support distributed transactions—it must be used with a JTA transaction manager.
Declarative transaction support
  • Can define transactions declaratively through the deployment descriptor.
  • Can define transaction behavior per method or per class by using the wildcard character *.
  • Cannot declaratively define rollback behavior—this must be done programmatically.
  • Can define transactions declaratively through the Spring configuration file or through class metadata.
  • Can define which methods to apply transaction behavior explicitly or by using regular expressions.
  • Can declaratively define rollback behavior per method and per exception type.
PersistenceSupports programmatic bean-managed persistence and declarative container managed persistence.Provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.
Declarative security
  • Supports declarative security through users and roles. The management and implementation of users and roles is container specific.
  • Declarative security is configured in the deployment descriptor.
  • No security implementation out-of-the box.
  • Acegi, an open source security framework built on top of Spring, provides declarative security through the Spring configuration file or class metadata.
Distributed computingProvides container-managed remote method calls.Provides proxying for remote calls via RMI, JAX-RPC, and web services.



About This Site

Howdy! My name is Suersh Rohan and I am the developer and maintainer of this blog. It mainly consists of my thoughts and opinions on the technologies I learn,use and develop with.

Blog Archive

Powered by Blogger.

- Copyright © My Code Snapshots -Metrominimalist- Powered by Blogger - Designed by Suresh Rohan -