Saturday, 7 September 2013

Spring MVC Flow Description

About Spring MVC






Figure Description:- A registration request is sent by DispatchServlet to the RegsitrationController(as figure out or directed by BeanNameUrlHandlerMapping). As a result, InternalResourceViewResolver directs the request to reg.jsp to render the page output.

Spring MVC flow steps:-
  • DispatcherServlet receives a request whose URL pattern is /reg.htm. This is the first stop in the request’s travels. This works on the Front Controller design pattern. It is a common web-application pattern where a servlet delegates responsibility for a request to other components of an application to perform the actual processing. Here the DispatcherServlet job is to send the request on to a spring MVC controller. A controller is nothing but a spring component that processes the request. But an application contains multiple controllers and then DispatcherServlet needs help to decide which controller can able to serve the coming request.
  • DispatcherServlet consults BeanNameUrlHandlerMapping(as per the above case) to find the corresponding controller whose bean name is /reg.htm and it finds the RegistrationController bean.
  • DispatcherServlet dispatches the request to RegistrationController for processing.
  • The logic performed by a controller often results in some required information that needs to be carried back to the client/user and displayed in the browser. This information is reffered to as the model. But sending the raw information is not the sufficient and correct way. It needs to be formatted in a user-friendly format. So the last thing that the controller will do is packaging the model data and the name of a view into a ModelAndView object. RegistrationController then returns a ModelAndView object with a logical view name that is reg.jsp. As the name implies, ModelAndView object containsboth the model data as well as a hint to what view should be returned to render the screen.
  • The ModelAndView object does not contain the actual JSP, it only carries a logical name that will be used to look up the actual view. So once the ModelAndView object is delivered to the DispatcherServlet then the DispatcherServlet take helps of ViewResolver to find the actual JSP. The DispatcherServlet consults its view resolver(configured as InternalResourceViewResolver in the above case) to find a view whose logical name is reg. InternalResourceViewResolver returns the path to /WEB-INF/jsp/reg.jsp.
  • Now the DispatcherServlet knows which view will render the results, so the final stop is at the view implementation where it delivers the model data. Now the view will use the model data to render a page that will be carried back to the client by the response object. In the above scenario, DispatcherServlet forwards the request to the JSP at /WEB-INF/jsp/reg.jsp to render the user page as the response.
 
More on WebServices                                                                                                More on Spring Core

Hibernate Interview Questions

Interview Questions



Question: - What is Session in Hibernate?

Answer: - Session is an interface in hibernate. We can get Session objects using SessionFactory references. Session is a wrapper for “java.sql.Connection”.It performs manipulation on DB entities. This is the basic interface for hibernate framework. Session object is light weight and can be created and destroyed without expensive process. It is short lived object and not thread safe. It works as a factory for “org.hibernate.Transaction”.It maintains the first level cache by default and this can be used while searching for the objects using identifier.

Question: - What session.refresh() method will do?

Answer: - session.refresh():- During the bulk update to the DB with hibernate, the changes made are not replicated to the entities stored in the current session. So calling session.refresh will load the modifications to session entities.

Question: - What session.flush () method will do?

Answer: - session.flush ():- This tells Hibernate to execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in the session-level cache. session.flush ()call will save the object instances to the database.

Question: - What session.clear () method will do?

Answer: - session.clear():- session.clear() method call can be used to clear the persistance context. It completely clears the session. This method call evicts all the objects from the session.

Question: - What session.evict (Object obj) method will do?

Answer: - session.evict(Object object): This method call will remove the instance that is passed as an argument in the evict method from the session cache and make a persistent object as a detached object.

Question: - What session.save() method will do?

Answer: - session.save() :This method call does an insert and will fail if the primary key is already available.

Question: - What session.saveOrUpdate()method will do?

Answer: - session.saveOrUpdate() :This method call does a select first to determine if it needs to do an insert or an update. Insert data if primary key is not already available in database otherwise do update data.

Question: - What session.persist () method will do?

Answer: - session.persist() :This method call does the same like session.save().
But session.save() returns Serializable object but session.persist() returns void.
session.save() returns the generated identifier (Serializable object) and session.persist() doesn’t.

Question: - What session.delete()method will do?

Answer: - session.delete(Object obj):- This method call will remove a persistent instance from the datastore.

Question: - What are the Fetching Strategies in hibernate?
Answer: -Fetching Strategies

Below are the fetching strategies.

1. fetch-”join” = this disable the lazy loading, always load all the collections and entities.
2. fetch-”select” (default) = this will lazily load all the collections and entities.
3. fetch-”subselect” = this will group its collection into a sub select statement.

Note: - These stretegies we can use in FetchMode.

Question: - What is Lazy and Eager loading strategies?

Answer: - The EAGER strategy is a hint given to the persistence provider that at runtime the data must be eagerly fetched (fetch in one query).
The LAZY strategy is a hint given to the persistence provider that at runtime the data should be fetched lazily when it is first accessed (fetch when needed as sub-queries).
  •  EAGER Fetch — get results in one query ( parent and child both ) 
  • LAZY Fetch – get results as sub-query.
For Example:
Suppose we have an entity called Student and another entity called Department.
The Student entity might have some basic properties such as id, name etc. as well as a property called Department.
Now Using Eager Loading, when we load a Student from the database, Hibernate will load student id, name fields and it also loads related Department details using the getDepartment() method -This is called  eager loading.
When a Student is associated with many Departments then it is not efficient to load its entire Department because it will create overhead on performance as they are not needed. So in such cases, we can declare that we want Department to be loaded when they are actually needed. This is called lazy loading.


Question: - what is the difference between fetch = FetchType.LAZY and FetchMode.SELECT.

Answer: -
FetchType:- There are two FetchType categories:-
LAZY and EAGER
Fetch type  refers to when Hibernate will fetch the association, whether in advance when it fetches the entity (eager), or whether it waits for the code to ask for the association (lazy).
Fetch mode refers to howHibernate will fetch the association, i.e. does it use an extra SELECT statement, or does it use a join. For example:-
@Fetch(FetchMode.SELECT)

      @OneToOne(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

      privateCustomerAddress customerAddress;

About Hibernate SessionFactory!

Fact about hibernate SessionFactory


Questions: - What is SessionFactory in hibernate?


Answer: - In Hibernate, SessionFactory is an interface, which is available in “org.hibernate” package. The delivery of session objects to hibernate applications is done by this interface. The SessionFactory object should be instantiated once during the application initialization.
  •  Session factory is long lived and thread safe object, so it can be shared in multithreaded environment.
  •  Generally only one SessionFactory is enough for an application but if application is interacting with more than one database then one SessionFactory should be created for one database.

Configuration cfg=new Configuration();   // This statement will create an empty object.
cfg=cfg.configure();


when we called  configure()  method then It looks for hibernate.cfg.xml configuration file and it also looks for Hibernate mapping(.hbm) file.

 SessionFactory sessionfactory = cfg.buildSessionFactory();
  • SessionFactory object will be created once and will be used by multiple users. It’s a single data store point and it is thread safe. Many threads can access this concurrently.
  • Session Factory object is the factory for session objects and it must be built only once at startup.

  • SessionFactory acts as a client of  “org.hibernate.connection.ConnectionProvider”.

  • SessionFactory maintains a second level cache of data that is reusable between transactions at a process or cluster level.

If we are using two databases like mysql and oracle in our hibernate application then we need to build two SessionFactory objects like below:-
Configuration configuration =new Configuration ();
Configuration cfg1= configuration.configure(“hibernate-mysql.cfg.xml”);
SessionFactory sessionfactory1=cfg1.buildSessionFactory ();

Configuration cfg2= configuration.configure(“hibernate-oracle.cfg.xml”);
SessionFactory sessionfactory2=cfg2.buildSessionFactory ();

In an application, to get the SessionFactory objects we should create a utility class and using their methods we should get the SessionFactory object. Below is the example of HibernateUtility Class.

package com.gaurav.common.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtility {
                privatestatic final SessionFactory sessionFactory = createSessionFactory();

                privatestatic SessionFactory createSessionFactory() {
                                try{
                                                returnnew Configuration().configure().buildSessionFactory();
                                } catch (Exception ex) {
                                                System.err.println("SessionFactory creation failed");
                                                thrownew ExceptionInInitializerError(ex);
                                }
                }

                /**
                 * @return the sessionfactory
                 */
                publicstatic SessionFactory getSessionfactory() {
                                returnsessionFactory;
                }

}

So, if we are using the above utility then we can use below code to get the session objects.



SessionFactory sf = HibernateUtility.getSessionfactory();

                                Session session = sf.openSession();