Java Spring MVC Interview Questions – Part2

By | January 2, 2017

This Technical Interview Questions post is part2 of Java Spring MVC Interview Questions that will extend the initial FAQs list and add more Interview Questions on Spring MVC Framework. If you haven’t gone through the previous list of Spring MVC Interview Questions, I’ll strongly recommend to go through it.

Also, we have covered another comprehensive list of Interview Questions related to Microsoft ASP.NET MVC that you can follow here.

You can find latest Java Developer Jobs at the end of this Java Spring MVC tutorial.

Java Spring MVC Interview Questions List

What is bean wiring and @AutoWired annotation? Explain different modes of auto wiring? What are the limitations with Auto wiring?

Bean wiring, as names suggests, is wire a bean with a bean. Sounds a bit complex, lets put it in simple words. Lets go back to Dependency Injection, IoC container, where in to set property in a bean there are two ways, one is using Constructor , that is use <constructor-arg> and other one is use setter method, that is to use <property> tag. So using both these ways we can inject some to a bean, that can be some primitive, some properties or they can be another bean as well. When we inject a bean within a bean it is called wiring of beans.

Now come to Autowiring, what is autowiring? We can wire bean automatically using autowiring feature of spring and this autowiring can be done by two ways:

  • By Xml tags
  • By Annotations

Autowiring By Xml Tags:

In order to achieve auto wiring using xml tags, we just need add the autowire attribute in <bean> bean tag. For example:

And that’s all we need to do to autowire a bean. We will dig a more into an example, but before that lets talk about the types of autowiring supported by Spring:

There are 5 modes of autowiring supported:

  • Default or no : Default or no mode in autowiring suggests, that there is no autowiring and beans will be wired using ‘ref’. That mean we need to explicitly wire the bean.  When we write default or no as autowire mode, no autowiring will be done by spring container. Example is:
  • ByName : In this autowiring mode the autowiring is performed on the name of property.  If the name of bean is same as, name of a property of a bean, that is ofcourse different, then the bean will be autowired. The ByName of autowiring is applied to setter methods. In the example below DI will same as AutowireTutorial property and there will be a setter method in AutowireTutorialClass named setDI(DI di), with which the bean will be autowired. Lets look at the bean tag:
  • ByType : In this autowiring mode, autowiring is performed on the type of property. That means the container looks for the type of the property in the config file. Containter will go through the config file and looks for the same class type of bean and if found will autowire it. As the case with ByName, this property is also applicable to setter methods. In the example below DI will same as type in AutowireTutorial bean  and there will be a setter method in AutowireTutorialClass named setDI(DI di), with which the bean will be autowired. Lets look at the bean tag:
  • Constructor: It is same as ByType  autowiring mode with the only difference, that is mode is applicable to constructor instead of setter methods. Unlike above example of ByType , there will be a constructor as public AutowireTutorial(DI di){//} .
  • Autodetect : The autodetect wiring mode, as the name suggests  autowires with one of either constructor or ByType. When constructor mode is not able to detect dependencies then ByType mode is selected and beans are autowired accordingly.

This is all about the autowiring using xml tags. Now Lets come to another important aspect of autowiring that is autowiring using annotation.

Autowiring using Annotation:

As we discussed in above section how autowiring can be done using xml and bean tag. Now lets come to more powerful way to achieve autowiring that is using annotation. Spring provides @Autowired annotation, with help of this, autowiring can be achieved. The best part is that the annotation needs to directly placed over the property in class we need to autowire and rest all will be done by container, interesting isn’t it. The @Autowired  annotation can applied on Construtor, Setter methods, Properties etc. There is one attribute that is required once set to true, container will complain and throw exception in case when the dependency is not getting resolved. Lets look at an example.

Lets say we have a CellPhone class and it has some properties like brand, color, type. Lets suppose Type is a bean that we need to autowire with the CellPhone class using @Autowired annotation. Below are the steps how we will achieve this:

Type class:

CellPhone class will now have the autowired annotation on setter method, lets see how to write the same:

As we can see the setType method has the @Autowired annotation, which will make the Type bean to wire with CellPhone bean.

Now quickly look at the bean config file and see how it will look like:

As we can clearly see, there is no autowire property with bean tag now and whole thing will be controlled by annotation. As we have seen the beauty of autowiring using annotations and there is no need to explicitly write any thing in config file and java code is handling all these. One more thing about @Autowired annotation is that it can be applied with SetterMethods like we talked in the example, as well with Constructors, Parameters etc. There are some limitations as well that comes with @Autowired. Lets have a look at the limitations:

  • Constructor-arg tags and Property tag will always override the dependences. That is major limitation, since the dependencies will be open to overridden using these tags.
  • If you have lot of dependencies in your code, its been hard to find and more error prone if not written carefully.
  • We always have to define property tag or constructor-arg tags for primitive data types since these can not be autowired.
  • There will a possible miss to documentation if there is autowiring in your code.

Back to top

What is a Controller in Spring MVC? Further what is the difference between @Component, @Controller, @Repository and @Service annotation in Spring?

If we talk about Spring MVC or a normal MVC pattern, that is Model, View, Controller design pattern. There are clear abstractions of model, view and controller. Now not to dig more into MVC model, just stick to Controller. What is controller, what is the role of Controller in Spring MVC.

Controller is something that takes responsibility to process the requests, executes the business logic to create Model that corresponds to the request and passes it to view. It is a core part of MVC framework or we can say heart of MVC framework.

In Spring if we talk about then there is DispatcherServlet, that handles all the requests and based on HandlerMapping, it passes the request to appropriate controller. Now controller comes into picture, which executes the business logic and creates a view that it passes again to DispatcherServlet.

Lets see with an example, how to define controller in Spring.

@Controller annotation is used to define controller in spring. There will be particular request mapping based on which controller will redirect the request to service method, and in service method there will be code to form the model by executing the business logic.

Lets understand the code , to start with there is a @Controller annotation, that makes this java class as controller. Based the value of RequestMapping, the matching request will be landed to it. There must be some business logic and based on the business logic the model will be created. In the example above, a model is created with attribute aopContent. The method can return the value as the logical name of the view.

Difference between @Component, @Controller, @Repository and @Service:

These are some annotations for which spring container does not require any configuration to be defined, like in case of @Autowired annotation. Spring container does automatic scan of these annotations.

@Component annotation makes the java class such that the spring container’s component scanner mechanism picks it and puts it in the application context. @Component annotation can be placed on anywhere inside application, where ever we want class to make bean and  want to put that class in the application context by spring container. It is a generic annotation.

@Service : The service annotation is a specialized version of @Component annotation. This is best suited for the classes which are defined as service or in other words in an application which have service layer. The service layer should be annotated by @Service annotation.

@Repository : Yet another specialized version of @Component. This is best suited annotation for DAO layer. The @Repository annotation should be used prior to @Component, in case of Database layer. It also makes the exception thrown from DAO layer methods (Unchecked Exceptions) to be translated to spring DataAccessException.

@Controller : Yet another power stereotype, which is best suited for web-based framework. Moreover the web applications that are having MVC design pattern in place.

Back to top

How to create a RESTful Web Service in Spring MVC returning JSON response? Explain with an example.

REST, it is an acronym for Representational State Transfer, an architectural style used in developing web services. Spring MVC provides a good api to develop web services. We will be going through step by step creating a web service using Spring MVC.

Once we setup the project and we have dependencies in place, we can start developing our first web service.

Let’s suppose a scenario where in we need to create a web service for book store, and the book store web service should display all the books available in the store with their ids and name.  Lets start with creating a simple model class, BookStoreModel.java.

Now lets code for controller, where in we will provide a method which will return the list of available books in the BookStore.

And that’s it, we are ready with our first web service(http://localhost:8080/bookstore/books) that returns the list of books available in book store in a json format. The snippet we will get will be:

RESTful Services in Java

Back to top

How to achieve localization in an application using Spring MVC Framework?

Localization is a concept in which an application that can adapt to a specific locale. Localization give an application the look and feel of having been created in locale irrespective of any locale language, culture, or location. Spring provides easy way to achieve localization like other frameworks. There are interceptors, resource bundles provided in spring framework with which we can achieve localization.

Let’s look how we can achieve Localization using Spring MVC Framework:

First of first thing we need to do is to having all required dependencies in place while creating a project , that will be done using either of maven or gradle, etc. Depends on what we are using in our project as build tool.

Once project is up to date with dependencies, next step we need to add locale specific message properties, that is key part.

Our application is such as a bookstore, where the book specific details(Like book isbn, book name, author) are displayed to users in different regions, in our example we will take a simple example of displaying a Welcome message to bookstore, in different locales.

Let’s suppose our application will run in two locales, and two different languages we need to support, that are German and English.

To achieve this we will create two properties files with name message_en.properties and message_de.properties as:

message_de.properties:

welcome.message = Bookstore online ist Ihr Platz für java Bücher. Kaufen oder verkaufen gebrauchte und neue Java-Bücher alle online. Erfahren Sie mehr über unseren Shop ausgezeichneter Service hier.

message_en.properties :

welcome.message = Bookstore online is your place for java books. Buy or sell used and new java books all online. Learn more about our store excellent service here.

Both these files will be placed under the resources folder, below is the screen shot.localization in Spring MVC Framework

Now we have created out locale files and placed, now question arises how spring container will come to know that there are such files and I need to read them. Here spring configuration comes into picture. Let’s see how:

ReloadableResourceBundleMessageSource class will be used to define the resources that is packaged under org.springframework.context.support package of spring framework.

In the example we have configured a messageSource bean that will enable localization in out application. To provide the location of resource bundles basename property will be used. classpath:message means that resource bundles are located in the classpath. To define the default encoding used for the messages defaultEncoding property will be used.

CookieLocaleResolver class, that is packaged under org.springframework.web.servlet.i18n package, will be used to set the cookie in the requests, so once we have set the cookie the upcoming request can be easily recognized based on cookie.

Next thing we need to set is to set the LocalChangeInterceptor, this interceptor is used to used to intercept the user request and check the user locale based on request parameter.

Like in the example above, we have set the parameter name as lang, so the interceptor will search for the parameter lang in the request, and based on the parameter it will append the value to the message_{}, and try to search in the resource bundle. Once find it will load the bundle and get the values that it needs based on the locale.

These all configurations we need to add in the dispatcher config file for an application.

Lets quickly create a jsp page that will welcome message of our book store:

And that’s it, we are all set to render this view to German and English locale. This is all we need to do to achieve localization using spring mvc.

Back to top

How is event handling done in Spring Framework? Explain the concept with help of a diagram. Describe some of the standard Spring events in details.

Let’s first talk about Event Handling, what is event handling ? Event handling is a mechanism in software programming which gives us a capability to perform certain action on a certain point that will be event. Like a simple scenario, on receiving money in my mobile wallet, lets suppose I am working on mobile wallet application and on receiving money in wallet I need to notify user that your account has been credited with this much money. What I will do, once credit has been done successfully in wallet of user, I will set an event, and what that event will do is, it will call a handler who will handle this event and perform certain task, like in the example above handler will be responsible for notify the user  by mail or by text.

Let’s understand this with an diagram:Event Handling in Spring MVC

As we discussed in above example, there are two users UserA and UserB, once UserA sends money and as soon as the account of UserB has been credited, an event has been raised and it is handled by event handler, which further sends notification to UserB, that account has been credited.

Now Let’s talk about event handling in spring:

Event handling in spring can be achieved by ApplicaitonEvent class and ApplicationListener interface provided by framework. If we talk about the core of spring that is ApplicationContext, which is responsible for managing the life cycle of beans, ApplicationContext publishes certain types of events on context start and stop. Such as ContextStartEvent is published when context is started and ContextStopEvent is published when context is stopped.

In spring if we not talk about the build in event handling for now, then to handle the custom events, responsible classes, Event  needs to extend ApplicationEvent class and Listener needs to implement ApplicaitonListener interface.

There are certain built in events in Spring, below is the list of them:

  • ContextRefreshedEvent
  • RequestHandledEvent
  • ContextStartedEvent
  • ContextStoppedEvent
  • ContextClosedEvent

ContextRefreshedEvent :

Whenever context is refreshed or initialized, this event is published. Alternately the same can also be published on refresh() method of ConfigurableApplicationContext interface, which is packaged in org.springframework.context package.

RequestHandledEvent :

This event is intended for web framework, to be more precise for spring-mvc, where we deal with HTTP requests. This event is published when a HTTP request is completed. This interface is available in org.springframework.web.context.support package.

ContextStartedEvent :

Whenever application context is started using the start() method, that is available in ConfigurableApplicationContext interface, which is packaged in org.springframework.context package, this event is published. Any init work like starting of services such as Database fingerprint check service can be started on this event.

ContextStoppedEvent :

Whenever application context is stopped using the stop() method, that is available in ConfigurableApplicationContext interface, which is packaged in org.springframework.context package, this event is published. With this event we can do the cleanup tasks of application.

ContextClosedEvent :

Whenever application context is closed using the close() method, that is available in ConfigurableApplicationContext interface, which is packaged in org.springframework.context package, this event is published. This is the end point of context , after which no start or refresh is possible of application context.

Back to top

More Advanced Spring MVC Interview Questions and Answers:

What is Spring Configuration File? Can we have multiple configuration files in Spring? What is annotation-based container configuration? How to turn ON annotation wiring?

Spring beans are defined in a configuration file, that are managed by container. Spring beans are managed by container, we provide meta data to spring container using config files. With use of the meta data provided in the config files, spring container manages beans.

These beans are defined using <bean> tag and spring properties are applied within the tag. Configuration file have the meta data like dependencies, bean’s details etc. Apart of beans, configuration files container locale specific data, interceptors details etc. Typically a bean file looks like :

In the example above, we have created a very simple configuration file, that provides a bean information. These configuration files are xml files, and are loaded by container. Container reads the information provided in the configuration file and loads bean in the application context. Let’s see how these beans are loaded, and what makes container to load these files.  Below is the simple example code that loades the example file beans.xml.

The above piece of code will load the beans.xml file from classpath and loads the bean defination defined in it in the application context.

Now what if we have more then one  configuration files to load. Does spring framework allow this to be done or we can load only one config file. Lets find out in next section.

Loading Multiple Config files in Spring

In previous section we talked about the spring config files to load a simple spring config file. Now what if a spring application have multiple configuraiton files, that is very likely, as different config files for different modules. Does spring have a capablity of loading multiple files ?

The answer is Yes, yes one can have multiple config files in spring and these all can be loaded by container. Lets find out how ?

One very simple way is to keep all config files in the classpath and load the files, below is the code for the same:

Lets assume we have 3 modules in our application, and the files are named as beans_moduleA.xml, beans_moduleB.xml, beans_moduleC.xml.

This way we can load multiple config files, but this is not the preffered approch and the same to lead to errors.

There is one more approch, with which we can load the multiple config files. This approch says to have all config files in a single file. Lets see how:

In the example above we have referenced all modules bean files into a common file. This makes code more organized and modular.

Now lets see how to load this, let suppose the xml config files containing all these files is named as beans_all.xml:

And we are done. This is all we need to do to load multiple configuration files.

From spring 2.5 it is possible to configure the dependencies using annotations. So instead of writing bean files one can have the annotation in application to manage dependencies. One more important aspect of using annotations is, annotations are injected in container before xml files. So while xml files are loaded, they can override the dependencies. Another important aspect of annotation wiring is, annotation wiring is not enabled by default. We need to add configure this in configuration file. Lets see with an example how we can achieve this:

Once <context:annotation-config> is added to config files, it gives message the container to turn on the annotation based wiring. Having this config in place, spring container will have the capability to manages beans based on annotations.

Back to top

How to handle Exceptions in Spring MVC? Explain with the help of an example.

Exceptions, exceptions are most unwanted thing any programmer, that any developer wish to have in application. Exception runs parallel with your application, where and whenever it will get chance it will occur. To handle such things in java we provide try/catch or throws kind of thing. But what if one missed to put the try/catch block, application will misbehave. In Spring MVC whenever a webpage loads either it will load fine or there might be chances that there will be exceptions. In case of unhandled exceptions your application will misbehave and there are chances that web page will print the full stack trace of the error, which is very very bad for any application.

Lets suppose we have a web application of book store, within which there is form addbook.html, that is responsible for adding book to our bookstore application. In an normal scenario, when I send a hit to webpage it works fine and controller loads the corresponding the web page, user enters the data and add the book to our bookstore. Lets check the controller that is responsible for loading the page.

The above is the code example of controller which loads a simple add book page. In normal scenario will load the page and our application runs file.Exception Handling in Spring MVC Framework

And we can see the page is loaded. Now lets create some error scenario.  Consider that our application is throwing some exception from controller. Below is the snippet.

In the above code snippet, what we have done is, we have manually thrown an exception. What will happen next, when controller tries to load the page, it will throw an exception and there is nothing in out code that handles the exception thrown. What will happen is the now  is the complete stack trace will be shown to explorer and which is not good. Below is the screenshot for the same, when I tried to load the page again, instead of the form what we got is the error stacktrace.

Status 500 Exception in Spring MVC

And why this happened, because there is no handler to handle this exception and the same is propagated from controller to view, which is the result.

Spring mvc provides a very convenient way to deal with such scenarios, which is add @ExceptionHandler annotation and create a method to handle the exception. Below is the code snippet how to add this handler.

This code snippet we need to add in the controller class which is throwing the exception. We are half way around now to handle exception. Now after this all we need to do is to add a simple page what we need to display in case of exception. And that’s it, we are done with handling the exception.Custom Exception in Spring MVC Framework

And we can see now that even if there is an exception thrown, there is no stack trace is shown to the use, instead of that a proper error message is shown.

Similarly, if there are some more exceptions all we need to do is to add the @ExceptionHandler and a web page with proper error message. What happened behind the scene is when an exception is been thrown, Spring MVC tries to find ExceptionHandler for corresponding exception and finds the exception page to display.

One limitation with this approach is that we need to add these handlers to all controllers . What if we need to have a common handler for all controllers? Let’s see how we can achieve this :

Spring provides one more annotation that is @ControllerAdvice, which will allow us to deal with these scenerios, where an application has more then one controller. With this code is place we don’t have to individually add exception in each and every controller class. Below is the code snippet for the same.

All we have done is to move the ExceptionHandler from controller and add to a common handler which has the @ControllerAdvice annotation. And that’s all. Now whenever and exception is thrown out of any of the controller class , spring mvc tries to find the appropriate handler for this and exception handler page(this is mapped for exception)  will be displayed.

Now one more concept, that spring mvc provides is, Instead of having the java class, the same can be done using xml file as well. That’s the beauty of spring, if there are more than one exceptions then our java class will be big. Let’s see how we can achieve the same:

By having this mapping in place we don’t need to write any java code for handling exceptions. We can add as many exceptions as we want in this.

Back to top

How to handle Form validation Spring MVC Framework? Give proper example.

Form validations are performed at client as well as server side. Server side validations are always preferred and always must have for any application, since client side validations may fail in case of java script disabled. Spring mvc also provides validation of beans using JSR-303 in place with the framework. Java Bean Validation(JSR-303) is a framework that defines metadata model for java bean validations.

Let’s now move to a simple form example, in which a bookstore application has a add book feature, and there are two fields on the page which are book name and book author. A simple validation that needs to be done is book name and book author name cannot be empty while submitting and book author name should not exceed 20 characters and should be minimum 5 characters. For this to be done, we will have a Book class that will act as a model and this model will bind to controller. Let’s find out how to achieve this in spring mvc:

Below is the code snippet of Controller class:

Let’s quickly find out what we have done in this controller class. A model is bind to controller class, also one more thing to notice is the second parameter that is BindingResult. While submitting the form if there will be any error, these will be captured in the bindingresult object.

One more thing that I missed intestinally, is one annotation that is @Valid.

But before talking about this annotation, lets see how our model class looks like.

Now I have placed some annotations in the model that will be validated while submitting the form. But who provides these annotations, Spring Framework ?  No, these are provided by some libraries like hibernate-validator.  These are third party libs that we need to include in our project in order to have validations in place.

Now in order to make these annotations work one more extra thing we need to done at the controller class, and that is to add @Valid interface. Now let’s check with @valid annotation in place how controller class looks like:

Now our method has @Valid annotation, which says spring framework is, whenever the form is submitted, you need to process the validation annotations. And that’s is we are good to go.Validations in Java Spring MVC

And this is what we got while submitting the page. Our annotations are working fine. One thing, is the error message that I got. What I am thinking now is, if I can check the error message to some more meaningful message. Will I able to do this using framework ? And answer is yes, yes we can have our own custom message, instead of this standard error message. Lets see how we can do this, in our Model class that is Book.java, we need to add a property as message with the @Size annotation. Below is the code snippet.

Let’s test and find out if our custom message works or not:Validations in Spring MVC Framework

Yes, our custom message works fine and now we are getting more meaningful error message that we wanted to. Now what if I don’t want my java class to be messy and I want to have a common place for validations like a property file. Spring framework also provides support for having a custom property file for all validation messages, all we need to do is make spring framework aware that there is such a file present in the system and you need to read the error messages from this property file.

This is what required to be added to dispatcher servlet config file. Here it indicates that the message source will be a properties file, that is present on the given path with error-message name and error messages should be read from the properties file. Having this in place we doesnot need to have the message property with annotation. All error messages will be kept at one place in the properties file.

Reloading the page with faulty data we will get the same error message.Spring MVC Interview Questions

Back to top

How to do transaction Management in Spring MVC? Give an example.

Transaction management is the most integral part of any application. No matter what if your application has a architectural beauty or has a mind-blowing interface, if application fails in managing the transactions then it all goes in vain.  Now let’s quickly understand what transaction management is and why it is so important of an application.

Transaction is set of actions in which each action must perform or none of them should perform. If we take a simple example of a book store, which has a capability of selling books online. Let’s suppose whenever a user purchases a book, a count deducted from Book_Store table and amount is credited to book store account, and bookstore account table BookStore_Account will be updated accordingly. Now let’s suppose someone did a transaction to purchase a book from our site and by some faulty code, what happened is, a count is deducted from Book_Store table and amount is not reflected in the BookStore_Account table, yet transaction was successful. And it all went well, happy customer and happy site admins. Now at end of day at the time of reconciliation we found out that, Oh ! there was something wrong with our code, count of Book_Store table and amount that should be in the table doesnot match and here we need to do all the manual work to find out which book table has a count mismatch. Now consider a scenario in which whenever a transaction is happening either Book_Store and account tables are updated or none of them if anything goes wrong in-between. This is what we called transaction management.

Each transaction must follow ACID properties. Which are Atomicity, Consistency, Isolation, and Durability. In any application these all properties needs to be followed, failing in any of them will cause application to misbehave and in data will be in incorrect state.

Spring provides two types of transaction management support, these are:

  • Programmatic Transaction Management
  • Declarative Transaction Management

Programmatic Transaction Management : In Programmatic transaction management approach, transaction is managed by programming. Writing code we manage the transaction.

Declarative Transaction Management:  In Declarative Transaction management approach, transaction is managed with the help of annotations, which separates the business logic code from transaction management.

Declarative transactions are more preferred over Programmatic Transactions, even though these are less flexible over the managing the transactions by writing code.

Spring provides transaction management api that is PlatformTransactionManager that is under org.springframework.transaction package. This interface provides the following methods:

Let’s go through some code example now, how to manage transactions in spring.

Lets create a simple BookStore class:

Our BookStoreAccount class will look like:

Please note for keeping the example simple I have created beans with very minimal parameters, In actual application there will be way more things to handle.

Typically there will be a controller in a mvc application, who will be responsible for calling a manager class which will have all the code to handle the transaction. In this example I am skipping the controller code since it will only call the manager code. The main crux lies in manager code. Prior to writing manager code, we will also need to write the configurations for transaction manager and we are also required to set the data source. Let’s look at both of them one by one:

Config.xml

As you can see in config we have set the data source specific setting, in this example I have added db-connection settings for oracle database. One we are done with datasource settings, next step we need to do is to set the TransactionManager, transaction mnager requires datasource, hence first datasource needs to be in place. Once we are done with both of these we are good to go to set these in our bean, that is BookStoreManager.

Once this config part is done, next part we need to do is to write java class for BookStoreManager. Below is the code for the same:

As you can see , in the example above transaction is being committed in one go, if there is any error, whole transaction will be rolled back.

This was an example of writing code in spring for programming transaction management. In declarative transaction management, AOP will be used and aspect will be used to handle transactions. In declarative transaction management approach, we are required to write transaction propagation. Transaction propagation has the following modes:

REQUIRED: This mode suggests that the current method execution must run within the same transaction, if there is no transaction then a new transaction will be created and the method will be executed within it.

REQUIRES_NEW: This mode suggests that the current method execution must start a new transaction and run within it.

MANDATORY: This mode suggests that current method execution must run within the transaction, if there is no transaction then throw an exception.

SUPPORTS: This mode suggests that the current method can run in the transaction if there is any, but if not then it is not mandatory to run within a transaction

NOT_SUPPORTED: This mode suggests that the current method execution should not run in the transaction.

Back to top

How we can integrate Spring MVC with hibernate framework? Briefly explain the steps with source code.

Before going into the integration steps of Spring and Hibernate, lets quickly talk about hibernate. What is hibernate? Hibernate is ORM(Object Relational Mapping) tool lives between application and database. Having hibernate with application there is no need for application to depend on low level database calls, hibernate manages it all. If we look at the application where hibernate is used, we can see that the hibernate objects are scattered all over our application code, here Spring comes into the picture and manages these objects using container.

Let’s now go through how to integrate Spring with Hibernate.

  • Create datasource:

 First we need to create a spring configuration file. Here we need to first create a data source that will be database connectivity mapping using URL, driver, username and password.

As we can see here we have created a datasource to connect with oracle database. Here we have defined URL, driver, username and password to be connected with oracle database.

  • Create SessionFactory :

Once we are done with creating the datasource, next thing we need to create a session factory. Lets quickly understand what is session factory. Session factory is responsible for creating session and transactions in hibernate.

Here we have defined yet another bean and created session factory. Assuming that we already have hibernate mapping file (hbm.xml) for database objects. Using messageResources property we have loaded the bookstore.hbm.xml file and we already have datasource created in previous step, so all we need to do s to map the datasource in the factory bean definition. In the next tag we have created the properties for hibernate like show_sql and hibernate dialect.

  • Create HibernateTemplate :

The next thing that we need to do is to crate HibernateTemplate. HibernateTemplate is responsible for low level database calls. It contains methods for database CRUD operations.

Here as we can see, there is only one property that we need to define in the hibernate template bean. That is session factory. As we have already created session factory bean, all we need to do is to just refer the bean to the sessionFactory property.

  • Define DAO Bean :

Now next we need to create a dao bean, that will use the hibernate template for CRUD operations. Lets define this:

We are all set with our configurations, now lets create a DAO bean for bookstore that will have all the methods to create, delete, find operations.

And we are good to go with our DAO class, that will save, update, delete, find book from database using hibernate as ORM and spring as framework.

These all steps are needed for a spring application to be integrated with hibernate.

Back to top
Java E-Commerce Store
It’s strongly recommended to prepare well all interview questions discussed in these two parts before appearing for a Java Spring MVC Interview Question.

Top Technical Interview Questions and Answers Series:

 

Java Application Development Jobs

[php snippet=8]