Where will you use ArrayList and where will you use LinkedList?
-------------------------------------------------------------------
ArrayList is faster for iteration and LinkedList is faster for insertion and deletion. So if the list will more frequently be read or searched than modifying
it then ArrayList is the better choice and the list will be modified more frequently than reading or searching then LinkedList is a better choice.
What is difference between array and ArrayList?
------------------------------------------------
Array is a fixed length data structure but ArrayList is resizable Collection.
Array elements must be of same type but ArrayList can contain different types of elements.
Array can contain premitive types but ArrayList cannot contain premitive types.
Arrays cannot use Generics but ArrayList can use Generics.
What is fail-fast, fail-tolerant and fail-safe property?
--------------------------------------------------------
Fail-fast property is to immediately respond to operations that might lead to failure or exception.
Fail-tolerant property allows to system to continue in case failures rather than completely stopping the system.
Fail-safe property assumes that the failure is safe for the system.
What is the difference between Iterator and ListIterator?
----------------------------------------------------------
ListIterator interface extends the interface Iterator.
ListIterator can be used only to iterate a List but Iterator can be used to iterate a Set or a List.
Iterator allows only forward traversal but ListIterator allows both forward and backward traversal.
ListIterator provides additional methods like add() , set()
What is the difference between Enumeration and Iterator interface?
--------------------------------------------------------------------
Enumeration was created to traverse through the elements of a Vector and the keys where as Iterator is created to traverse through the elements of a Collection.
Enumeration is faster than Iterator.
Enumeration uses less memory than Iterator.
What is the difference between ArrayList and Vector?
-----------------------------------------------------
All the methods of Vector are synchronized but the methods of ArrayList are not synchronized
he Enumeration returned by Vector’s elements() method is not fail-fast whereas ArraayList have method to return Iterator.
What is the difference between List and Set?
-------------------------------------------
List is an ordered collection which allows duplicate elements but Set is an unordered collection which does not allow duplicate elements.
How a Set prevents inserting duplicate elements?
-------------------------------------------------
Set uses both equals() and hashCode() method to check for the duplicates. The equals() and hashCode() contract must be satisfied to prevent inserting duplicate
elements into a Set.
Which is a better choice in terms of Insertion and Iteration between List and Set?
-----------------------------------------------------------------------------------
In terms of Insertion List is faster than Set because List can directly add an element at the end but Set needs to perform a sequential check for a duplication
before adding. This duplication checking makes Set slower than List.
In terms of Iteration List is faster because it supports indexed access
What is the difference between HashSet and TreeSet?
-----------------------------------------------------
HashSet is not sorted but TreeSet is sorted by the natural ordering defined in the Comparable object’s compareTo() mothod or it can be created using the TreeSet
constructor using a Comparator.
HashSet is faster than TreeSet in case of iteration and insertion.
Can a null element be added to a HashSet or TreeSet?
-------------------------------------------------------
HashSet allows inserting null into it only once. TreeSet allows inserting null into it multiple times or disallows based on the definition of comparing of the
objects in Comparable.compateTo() or Comparator.compare() method.
What is the effect of implementing equals() but not implementing hashCode() in case of a List and Set?
-------------------------------------------------------------------------------------------------------
No impact will be observed in case of insertion and selection for Vector, ArrayList and LinkedList.
Duplicate elements will be inserted into a Set. If we search using the actual object reference that was used to insert only then the object will be found in HashSet
and LinkedHashSet.
If hashCode() is not overridden but equals() is overridden then Set will be able to distinguish duplicates?
-------------------------------------------------------------------------------------------------------------
The default implementation provided by the Object.hashCode()returns distinct integers for distinct objects because it returns the internal address of the object.
Hence if two objects are equal according to the equals() method even then the hashCode of them will be different, which is a violation of the hashCode contract and
the Set will consider them as different objects.
Explain the methods present in Queue interface?
----------------------------------------------------
offer(): Inserts an element if possible, otherwise returns false. This differs from the Collection.add() method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity or “bounded” queues.
remove(): Returns the head of this Queue and if this queue is empty then throws NoSuchElementException. It removes the head of this Queue.
element(): Returns the head of this Queue and if this Queue is empty then throws NoSuchElementException. It does not remove the head of this Queue.
peek(): Returns the head of this Queue and if this Queue is empty then returns null. It does not remove the head of this Queue.
poll(): Returns the head of this Queue and if this Queue is empty then returns null. It removes the head of this Queue.
What is PriorityQueue?
---------------------------
The elements of the priority queue are ordered according to their natural ordering, or by a Comparator. A priority queue does not permit null elements
also does not permit insertion of non-comparable objects
The head of this queue is the least element with respect to the specified ordering.
What is ConcurrentHashMap?
--------------------------------
ConcurrentHashMap is a hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates.
What are the default initial capacities of Vector, ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, Hashtable, HashMap, LinkedHashMap and TreeMap?
---------------------------------------------------------------------------------------------------------------------------------------------------------
The default initial capacity of a Vector is 10 and it increases by 100%.
1
newCapacity = oldCapacity * 2
The default initial capacity of an ArrayList is 10 and it increases by 50%.
1
newCapacity = (oldCapacity * 3)/2 + 1
LinkedList starts with a single LinkedList.Entry reference which is a private static inner class.
The internal data structure of a HashSet is a HashMap whose default initial capacity is 16 with load factor of 0.75.
The internal data structure of a LinkedHashSet is a LinkedHashMap whose default initial capacity is 16 with load factor of 0.75.
The internal data structure of a TreeSet is a TreeMap that starts with a single TreeMap.Entry reference named root.
The default initial capacity of a HashTable is 11 with load factor of 0.75.
1
newCapacity = oldCapacity * 2 + 1
The default initial capacity of a HashMap is 16 with load factor of 0.75.
The default initial capacity of a LinkedHashMap is 16 with load factor of 0.75.
TreeMap starts with a single TreeMap.Entry reference named root.
While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?
----------------------------------------------------------------------------------------------------------------------
Collections.unmodifiableCollection() method returns a read only collection and any attempt to modify the collection throws an
What are different ways to iterate over a list? Which one is faster?
-----------------------------------------------------------------------
There are two ways to iterate over a list. We can use an iterator or we can use a for loop. Iterating using a for loop is faster because ArrayList is
internally an array so it provides indexed access and thus the values will be directly accessed as per the index.UnsupportedOperationException exception.
What are different ways to iterate over a Map? Which one is faster?
-----------------------------------------------------------------------
Map interface provides three different collection views: keySet(), values() and entrySet().
The keyset() method returns a Set of the keys and the get() method can be used to get the value. The values() method returns a Collection of only the values so
keys are not available.
The entrySet() method returns a Set of Map.Entry objects which contains both key and value. We can iterate over these views either by an Iterator or by a For loop.
Collection interface provides toArray() method so Map can be converted to an array and the array can be iterated. It provides three additional ways to iterate.
entrySet() method is the most efficient way to iterate through a Map and the For loop is more cleaner and readable than the Iterator.
Which collection classes provide random access of its elements?
-------------------------------------------------------------------
ArrayList and Vector implements the marker interface java.util.RandomAccess. Hence ArrayList, Vector and Stack provide random access of its elements.
How to avoid ConcurrentModificationException while iterating a collection?
---------------------------------------------------------------------------
We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection. For example we can use CopyOnWriteArrayList
instead of ArrayList.
How can we create a synchronized collection from given collection?
---------------------------------------------------------------------
We can use Collections.synchronizedCollection()
How can ArrayList be synchronized without using Vector?
-------------------------------------------------------
List list = Collections.synchronizedList(new ArrayList());
How can we make HashMap synchronized?
----------------------------------------
Map map = Collections.synchronizedMap(new HashMap());
How to obtain Array from an ArrayList?
-------------------------------------------
ArrayList.toArray() method returns an array
How to convert a String array to ArrayList?
--------------------------------------------
using Arrays.asList() converts an array to a List and ArrayList provides a constructor that constructs an ArrayList from a Collection.
example :
String[] stringArray = { "one", "two", "three" };
List<String> stringList = Arrays.asList(stringArray);
ArrayList<String> stringArrayList = new ArrayList<String>(stringList);
How to reverse a List?
-------------------------
Collections.reverse()
Why String, Integer and other wrapper classes are considered good keys?
----------------------------------------------------------------------
String, Integer and other wrapper classes are final or immutable classes and they have overridden equals() and hashCode() method as per the contract so they are
considered good keys.
Why there is no concrete implementation of Iterator interface?
-------------------------------------------------------------
A concrete implementation of an Iterator must decide between an ordered iteration or an unordered iteration which clearly leads to an iterator either for a List or
for a Set. Iterators of a List must be ordered because ordering is the heart of List whereas Set does not need ordering as an essential property and ordering a Set
makes a very special type of Set. Thus iterators are more specific functionality to specific collection types rather than applicable to all types of Collection.
Hence subclasses of Collection provide iterators that are specific to that collection type.
Why there is no method like Iterator.add() to add elements to the collection?
-----------------------------------------------------------------------------
Adding elements to the collection during the iteration is an unclear functionality and leads to an unordered iteration which is not desirable for ordered
collections
What are common algorithms implemented in Collections Framework?
---------------------------------------------------------------
The common algorithms implemented in Collections Framework are: sorting, searching, shuffling, swaping, min, max, rotate, addAll, replaceAll, etc.
What is Big-O notation?
--------------------------------------------
Big O notation is used to represent the complexity of an algorithm based on the input size. It is useful to choose the best algorithm to solve a problem.
What is the performance of various Java collection implementations/algorithms? What is Big ‘O’ notation for each of them?
----------------------------------------------------------------------------------------------------------------------------
ArrayList: The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding N elements requires O(N) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
LinkedList: Performance of get and remove methods is linear time [ Big O Notation is O(N) ] – Performance of add and Iterator.remove methods is constant-time [ Big O Notation is O(1) ]
HashSet: This class offers constant time performance for the basic operations like add, remove, contains and size assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance’s size that is the number of elements plus the “capacity” of the backing HashMap instance that is the number of buckets. Thus, it’s very important not to set the initial capacity too high or the load factor too low if iteration performance is important.
LinkedHashSet: Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.
A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.
TreeSet: This implementation provides guaranteed log(N) time cost for the basic operations like add, remove and contains.
Hashtable: An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.
HashMap: This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the “capacity” of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
LinkedHashMap: Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.
A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.
TreeMap: This implementation provides guaranteed log(N) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest’s Introduction to Algorithms.
90. What is the difference between sorting performance of Arrays.sort() and Collections.sort()? Which one is faster? Which one to use and when?
Collections.sort() can sort only Lists and Arrays.sort() can sort only arrays. Internally Collections.sort() converts the List to an array and then it calls Arrays.sort() to sort it and then it converts the sorted array into a List whereas Arrays.sort() directly sorts the array.
Hence Arrays.sort() is faster than Collections.sort().
When we have a List we can use Collections.sort() and when we have an array we can use Arrays.sort().
What are best practices related to Java Collections Framework?
---------------------------------------------------------------
1. Choose the right type of collection based on the need.
2. Optimize the initial capacity to avoid rehashing or resizing.
3. Override equals() and hashCode() methods as per the contract.
4. Use polymorphic references to List, Set and Map instead of their concrete implementation.
5. Use Generics for type safety at compile time.
6. Use immutable classes as key in Map.
7. Use Collections utility methods for algorithms like sorting, searching, shuffling, swapping, reversing, synchronizing, read only collections, etc. rather than
writing own implementation.
What is load factor?
--------------------------
Load factor is the ratio of the number of elements of the hash table and the number of buckets.
What is Hashing?
-------------------
Hashing means using some function or algorithm to map object data to some representative integer value.
What is Hash Collision?
---------------------------
If the hash codes of two or more objects are same then it is known as hash collision.
What is Re-hashing?
-----------------------
Rebuilding the internal data structure of the hash table is known as rehashing. When the size of the hash table exceeds the threshold = capacity * load factor,
then all the elements are moved to a new bigger hash table. The hash code is calculated again to determine the bucket number so it is called rehashing.
How does put() and get() method of HashMap work?
-------------------------------------------------
The put() method with key and value is used to insert an element into the HashMap. The hash code of the key is calculated and the bucket is determined from the
hash code. If the bucket is empty then a new HashMap.Entry(hash, key, value, next) element is inserted into the bucket. If the bucket is not empty then all the
keys in the linked list is compared with the equals method to check if an element with the same key is already there or not. If the key is found then the value is
overwritten otherwise a new HashMap.Entry(hash, key, value, next) element is inserted at the end.
The get() method is used to get the value for a given key. The hash code of the key is calculated and the bucket is determined from the hash code. The linked list
present into the bucket is sequentially searched for the key. If the hash code matches and the key passes either == or equals() method then the value stored there
is returned.
What will happen if two different HashMap key objects have same hashcode? How will you retrieve Value object if two Keys will have same hashcode?
-----------------------------------------------------------------------------------------------------------------------------------------------------
Two different HashMap key objects have same hashcode is known as hash collision. HashMap uses a doubly linked list for each bucket to resolve hash collision.
Both the keys will be stored into the same bucket as different nodes of the linked list.
The nodes of this linked list are of type HashMap.Entry(hash, key, value, next). The get() method is used to get the value for a given key. It will perform a
sequential search into the linked list present into the bucket. Since the hash code is same the key will be identified by any of the == or equals() method and
then the value stored into the HashMap.Entry will be returned.
Wednesday, November 6, 2013
J2EE PATTERNS
Presentation Tier:
---------------------
1. Interceptor Pattern : Pluggable filter intercept incoming request and outgoing response
2. Front Controller : Handles requests and manages content retrieval, security, view management,and navigation, delegating to a Dispatcher component to dispatch to a View.
3. View Helper : Generally suggested to view helper for formatting output also use business delegate to access business classes.
4. Composite View : Composite view design pattern is used when multiple subviews are directly embedded to make a single view or layout or template.
5. Dispatch View : Dispatcher view is a combination of a controller and dispatcher with views and view helpers to handle client requests and prepare a dynamic presentation as the response.
6. Service to Worker : This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part.
Business Tier :
----------------
1. Business Delegate : Primary target is to reduce coupling between presentation and business tier by provide a proxy to facade. hiding the underlying implementation details of the service .
2. Session Facade : Main focus of the facade is to split the total system into sub system by hiding the complexity. It helps to reduce network overhead and improve performance.
3. Transfer/Value Object : Used to exchange data across tiers.it also reduce the network overhead by minimizing the number of calls to get data from another tier.
4. Transfer/Value Object Assembler : Transfer Object Assembler combines multiple Transfer Objects from various business components and services, and returns it to the client.
5. Value List Handler : Value list handler is use to cache the results and allow client to search, traverse and select items from the results.
6. Service Locator : The service locator design pattern is used when you to implement and encapsulate service and component lookup.
7. Composite Entity : Use Composite Entity to model, represent, and manage a set of interrelated persistent objects rather than representing them as individual
Integration Tier:
------------------
DAO : Encapsulate all access to persistence store. DAO manages connection with data source to obtain and store data.
Service Activator : Service activator design pattern is use to receive asynchronous requests and invoke one or more business services.
---------------------
1. Interceptor Pattern : Pluggable filter intercept incoming request and outgoing response
2. Front Controller : Handles requests and manages content retrieval, security, view management,and navigation, delegating to a Dispatcher component to dispatch to a View.
3. View Helper : Generally suggested to view helper for formatting output also use business delegate to access business classes.
4. Composite View : Composite view design pattern is used when multiple subviews are directly embedded to make a single view or layout or template.
5. Dispatch View : Dispatcher view is a combination of a controller and dispatcher with views and view helpers to handle client requests and prepare a dynamic presentation as the response.
6. Service to Worker : This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part.
Business Tier :
----------------
1. Business Delegate : Primary target is to reduce coupling between presentation and business tier by provide a proxy to facade. hiding the underlying implementation details of the service .
2. Session Facade : Main focus of the facade is to split the total system into sub system by hiding the complexity. It helps to reduce network overhead and improve performance.
3. Transfer/Value Object : Used to exchange data across tiers.it also reduce the network overhead by minimizing the number of calls to get data from another tier.
4. Transfer/Value Object Assembler : Transfer Object Assembler combines multiple Transfer Objects from various business components and services, and returns it to the client.
5. Value List Handler : Value list handler is use to cache the results and allow client to search, traverse and select items from the results.
6. Service Locator : The service locator design pattern is used when you to implement and encapsulate service and component lookup.
7. Composite Entity : Use Composite Entity to model, represent, and manage a set of interrelated persistent objects rather than representing them as individual
Integration Tier:
------------------
DAO : Encapsulate all access to persistence store. DAO manages connection with data source to obtain and store data.
Service Activator : Service activator design pattern is use to receive asynchronous requests and invoke one or more business services.
Tuesday, November 5, 2013
Spring Related Question and Answer
1. What is Spring?
----------------------
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application,but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
2. what are benefits of using spring?
----------------------------------------------
Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
Inversion of control (IOC): 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.
Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application objects.
MVC Framework: Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
3. What are the different modules in Spring framework?
--------------------------------------------------------------------
1. Core Container Module : This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container
2.Application Context Module : The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise
services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.
3.AOP module (Aspect Oriented Programming) : AOP module is used for developing aspects for Spring-enabled application
4.JDBC abstraction and DAO module
5.ORm integration module (Object/Relational)
6.Web module
7. MVC framework module
4. What is a BeanFactory?
---------------------------------
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.
5. What is XMLBeanFactory?
--------------------------------------
BeanFactory has many implementations in Spring. But one of the most useful one is org. springframework. beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file.
6.What are important ApplicationContext implementations in spring framework?
--------------------------------------------------------------------------------------------------
ClassPathXmlApplicationContext – This context loads a context definition from an XML file located in theclass path, treating context definition files as class path resources.
FileSystemXmlApplicationContext – This context loads a context definition from an XML file in the filesystem.
XmlWebApplicationContext – This context loads the context definitions from an XML file contained within a web application.
7. Explain Bean lifecycle in Spring framework?
-----------------------------------------------------------
1.The spring container finds the bean’s definition from the XML file and instantiates the bean.
2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.
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 aninstance of itself.
5. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.
7 .If an init-method is specified for the bean, it will be called.
8 Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
7. What is bean wiring?
------------------------------
Combining together beans within the Spring container is known as bean wiring or wiring.
8. What are singleton beans and how can you create prototype beans?
-----------------------------------------------------------------------------------
Beans 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.
9. What are the different types of bean injections?
---------------------------------------------------------------
There are two types of bean injections.
By setter
By constructor
10. What is Auto wiring?
------------------------------
we can wire the beans as you wish. But spring framework also does this work for us. It can auto wire the related beans together. All we have to do is
just set the autowire attribute of bean tag to an autowire type.
<bean id="bar" class="com.act.Foo" Autowire=”autowire type”/>
11. What are different types of Autowire types?
---------------------------------------------------------
There are four different types by which auto-wiring can be done.
byName
byType
constructor
autodetect
12. What are the different types of events related to Listeners?
--------------------------------------------------------------------------
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses oforg.springframework.context.
Application-Event. They are
ContextClosedEvent – This is fired when the context is closed.
ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
RequestHandledEvent – This is fired when the web context handles any request.
13. What is an Aspect?
----------------------------
An aspect is the cross-cutting functionality that we are implementing. It is the aspect of our application we are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, we can create a logging aspect and apply it throughout the application using AOP.
14. What is a Jointpoint?
------------------------------
A join point is a point in the execution of the application where an aspect can be plugged in.
15. What is an 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 behaviour 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.
16. What is a Point cut?
----------------------------
A point cut defines at what join points an advice should be applied.
17. What is a Target?
--------------------------
A target is the class that is being advised.
18. What is a Proxy?
-------------------------
A proxy is an object that is created after applying advice to a target object.
19. What is meant by Weaving?
------------------------------------
The process of applying aspects to a target object to create a new proxy object is called as Weaving.
The aspects are woven into the target object at the specified join points.
20 What are the different types of AutoProxying?
-----------------------------------------------------------
BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator
Metadata autoproxying
Different points where weaving can be applied :
Compile Time
Classload Time
Runtime
21. What are the benefits of IOC?
----------------------------------------
The main benefits of IOC or dependency injection are:
1. It minimizes the amount of code in your application.
2. It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.
3. Loose coupling is promoted with minimal effort and least intrusive mechanism.
4. IOC containers support eager instantiation and lazy loading of services.
22. What bean scopes does Spring support? Explain them.
--------------------------------------------------------
Singleton: Scopes a single bean definition to a single object instance per Spring IoC container. Default Scope.
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 Spring ApplicationContext.
23 : How do you turn on annotation wiring?
---------------------------------------------------
A: Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.
24 What is WebApplicationContext ?
-----------------------------------------------
A: The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with
25. Following are some of the advantages of Spring MVC over Struts MVC:
------------------------------------------------------------------------------------------------
Layered architecture that allows you to use what you need while leaving what you don’t need.
Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance.
Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests.
Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface.
In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy.
Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend.
In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality.
With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database.
26. What type of transaction Management Spring support?
--------------------------------------------------------------------------
Two type of transaction management is supported by spring
1. Programmatic transaction management : used preferably when you have a small number of transactional operations
2. Declarative transaction management: In case of large number of transactional operations it is better to use declarative transaction management.
27. List new features for Spring 3.0
------------------------------------------
1: Spring Expression Language : Spring introduces an expression language which is similar to Unified EL
2. IoC enhancements/Java based bean meta-data : Annotation based configuration and Some core features from the JavaConfig project have been added
3. General-purpose type conversion system and field formatting system
4. Object to XML mapping functionality (OXM) moved from Spring Web Services project
5. Comprehensive REST support
6. @MVC additions
7. Declarative model validation
8. Early support for Java EE 6
9. Embedded database support
----------------------
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application,but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
2. what are benefits of using spring?
----------------------------------------------
Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
Inversion of control (IOC): 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.
Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application objects.
MVC Framework: Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
3. What are the different modules in Spring framework?
--------------------------------------------------------------------
1. Core Container Module : This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container
2.Application Context Module : The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise
services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.
3.AOP module (Aspect Oriented Programming) : AOP module is used for developing aspects for Spring-enabled application
4.JDBC abstraction and DAO module
5.ORm integration module (Object/Relational)
6.Web module
7. MVC framework module
4. What is a BeanFactory?
---------------------------------
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.
5. What is XMLBeanFactory?
--------------------------------------
BeanFactory has many implementations in Spring. But one of the most useful one is org. springframework. beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file.
6.What are important ApplicationContext implementations in spring framework?
--------------------------------------------------------------------------------------------------
ClassPathXmlApplicationContext – This context loads a context definition from an XML file located in theclass path, treating context definition files as class path resources.
FileSystemXmlApplicationContext – This context loads a context definition from an XML file in the filesystem.
XmlWebApplicationContext – This context loads the context definitions from an XML file contained within a web application.
7. Explain Bean lifecycle in Spring framework?
-----------------------------------------------------------
1.The spring container finds the bean’s definition from the XML file and instantiates the bean.
2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.
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 aninstance of itself.
5. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.
7 .If an init-method is specified for the bean, it will be called.
8 Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
7. What is bean wiring?
------------------------------
Combining together beans within the Spring container is known as bean wiring or wiring.
8. What are singleton beans and how can you create prototype beans?
-----------------------------------------------------------------------------------
Beans 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.
9. What are the different types of bean injections?
---------------------------------------------------------------
There are two types of bean injections.
By setter
By constructor
10. What is Auto wiring?
------------------------------
we can wire the beans as you wish. But spring framework also does this work for us. It can auto wire the related beans together. All we have to do is
just set the autowire attribute of bean tag to an autowire type.
<bean id="bar" class="com.act.Foo" Autowire=”autowire type”/>
11. What are different types of Autowire types?
---------------------------------------------------------
There are four different types by which auto-wiring can be done.
byName
byType
constructor
autodetect
12. What are the different types of events related to Listeners?
--------------------------------------------------------------------------
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses oforg.springframework.context.
Application-Event. They are
ContextClosedEvent – This is fired when the context is closed.
ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
RequestHandledEvent – This is fired when the web context handles any request.
13. What is an Aspect?
----------------------------
An aspect is the cross-cutting functionality that we are implementing. It is the aspect of our application we are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, we can create a logging aspect and apply it throughout the application using AOP.
14. What is a Jointpoint?
------------------------------
A join point is a point in the execution of the application where an aspect can be plugged in.
15. What is an 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 behaviour 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.
16. What is a Point cut?
----------------------------
A point cut defines at what join points an advice should be applied.
17. What is a Target?
--------------------------
A target is the class that is being advised.
18. What is a Proxy?
-------------------------
A proxy is an object that is created after applying advice to a target object.
19. What is meant by Weaving?
------------------------------------
The process of applying aspects to a target object to create a new proxy object is called as Weaving.
The aspects are woven into the target object at the specified join points.
20 What are the different types of AutoProxying?
-----------------------------------------------------------
BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator
Metadata autoproxying
Different points where weaving can be applied :
Compile Time
Classload Time
Runtime
21. What are the benefits of IOC?
----------------------------------------
The main benefits of IOC or dependency injection are:
1. It minimizes the amount of code in your application.
2. It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.
3. Loose coupling is promoted with minimal effort and least intrusive mechanism.
4. IOC containers support eager instantiation and lazy loading of services.
22. What bean scopes does Spring support? Explain them.
--------------------------------------------------------
Singleton: Scopes a single bean definition to a single object instance per Spring IoC container. Default Scope.
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 Spring ApplicationContext.
23 : How do you turn on annotation wiring?
---------------------------------------------------
A: Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.
24 What is WebApplicationContext ?
-----------------------------------------------
A: The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with
25. Following are some of the advantages of Spring MVC over Struts MVC:
------------------------------------------------------------------------------------------------
Layered architecture that allows you to use what you need while leaving what you don’t need.
Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance.
Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests.
Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface.
In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy.
Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend.
In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality.
With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database.
26. What type of transaction Management Spring support?
--------------------------------------------------------------------------
Two type of transaction management is supported by spring
1. Programmatic transaction management : used preferably when you have a small number of transactional operations
2. Declarative transaction management: In case of large number of transactional operations it is better to use declarative transaction management.
27. List new features for Spring 3.0
------------------------------------------
1: Spring Expression Language : Spring introduces an expression language which is similar to Unified EL
2. IoC enhancements/Java based bean meta-data : Annotation based configuration and Some core features from the JavaConfig project have been added
3. General-purpose type conversion system and field formatting system
4. Object to XML mapping functionality (OXM) moved from Spring Web Services project
5. Comprehensive REST support
6. @MVC additions
7. Declarative model validation
8. Early support for Java EE 6
9. Embedded database support
Struts Related Question and answer
1. What are the main classes which are used in struts application?
------------------------------------------------------------------
Action servlet: it’s a back-bone of web application it’s a controller class responsible for handling the entire request.
Action class: using Action classes where all the business logic implemented.
Action Form: it’s a java bean which represents our forms and associated with action mapping. And it also maintains the session state its object is
automatically populated on the server side with data entered from a form on the client side.
Action Mapping: using this class we do the mapping between object and Action.
ActionForward: this class in Struts is used to forward the result from controller to destination.
2. How exceptions are handled in Struts application?
----------------------------------------------------
There are two ways of handling exception in Struts:
Pro grammatically handling: using try {} catch block in code where exception can come and flow of code is also decided by programmer .its a normal java language
concept.
Declarative Exception Handling: we can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
example:
<global-exception-mappings>
<exception-mapping exception="java.sql.SQLException" result="SQLException"/>
<exception-mapping exception="java.lang.Exception" result="Exception"/>
</global-exception-mappings>
...
<action name="DataAccess" class="com.company.DataAccess">
<exception-mapping exception="com.company.SecurityException" result="login"/>
<result name="SQLException" type="chain">SQLExceptionAction</result>
<result>/DataAccess.jsp</result>
</action>
...
3. How validation is performed in struts application?
------------------------------------------------------
In struts validation is performed using validator framework, Validator Framework in Struts consist of two XML configuration files.
1. validator-rules.xml file: which contains the default struts pluggable validator definitions. You can add new validation rules by adding an entry in this file.
This was the original beauty of struts which makes it highly configurable.
2. Validation.xml files which contain details regarding the validation routines that are applied to the different Form Beans.
4. Dispatch Action , LookupDispatch Action , EventDispatchAction
------------------------------------------------
Dispatch Action:An abstract Action that dispatches to a public method that is named by the request parameter whose name is specified by the parameter property of the corresponding ActionMapping. This Action is useful for developers who prefer to combine many similar actions into a single Action class, in order to simplify their application design.
Example :
<action path="/saveSubscription" type="org.apache.struts.actions.DispatchAction" name="subscriptionForm" scope="request" input="/subscription.jsp" parameter="method"/>
LookupDispatchAction : An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. To configure the use of this action in your struts-config.xml file, create an entry like this:
<action path="/test"
type="org.example.MyAction"
name="MyForm"
scope="request"
input="/test.jsp"
parameter="method"/>
EventDispatchAction: An Action that dispatches to to one of the public methods that are named in the parameter attribute of the corresponding ActionMapping and matches a submission parameter. This is useful for developers who prefer to use many submit buttons, images, or submit links on a single form and whose related actions exist in a single Action class.
<action path="/saveSubscription"
type="org.example.SubscriptionAction"
name="subscriptionForm"
scope="request"
input="/subscription.jsp"
parameter="save,back,recalc=recalculate,default=save"/>
5. How you can retrieve the value which is set in the JSP Page in case of DynaActionForm?
--------------------------------------------------------------------------------------------
DynaActionForm is a popular topic in Struts interview questions. DynaActionForm is subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time.
6. what the Validate () and reset () method does?
----------------------------------------------------
validate() : validate method is Used to validate properties after they have been populated, and this ,method is Called before FormBean is passed to Action.
Returns a collection of ActionError as ActionErrors.
reset() : The purpose of this method is to reset all of the ActionForm's data
7. How you will make available any Message Resources Definitions file to the Struts Framework Environment?
----------------------------------------------------------------------------------------------------------
Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources
Definitions files can be added to the struts-config.xml file through < message-resources / > tag and also using web.xml
8. Explain Struts work Flow?
---------------------------------
1) A request comes in from a Java Server Page into the ActionServlet.
2) The ActionServlet having already read the struts-config.xml file, knows which form bean relates to this JSP, and delegates work to the validate method of that form bean.
3) The form bean performs the validate method to determine if all required fields have been entered, and performs whatever other types of field validations that need to be performed.
4) If any required field has not been entered, or any field does not pass validation, the form bean generates ActionErrors, and after checking all fields returns back to the ActionServlet.
5) The ActionServlet checks the ActionErrors that were returned from the form beans validate method to determine if any errors have occurred. If errors have occurred, it returns to the originating JSP displaying the appropriate errors.
6) If no errors occurred in the validate method of the form bean, the ActionServlet passes control to the appropriate Action class.
7) The Action class performs any necessary business logic, and then forwards to the next appropriate action (probably another JSP).
9. How can I create a wizard work flow?
-------------------------------------------------
The basic idea is a series of actions with next, back, cancel and finish actions with a common bean. Using a LookupDispatchAction is recommended as it fits the design pattern well and can be internationalized easily.
10. How to do 'chain' Actions?
-----------------------------------------
Chaining actions can be done by simply using the proper mapping in your forward entries in the struts-config.xml file.
example :
<forward name="success" path="/xyz.do" />
11. diff detween Struts 1 and Struts 2
---------------------------------------
Action classes :
In struts 1 Action classes extend an abstract base class.
An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom service,Struts 2 provides a base ActionSupport class to implement commonly used interfaces.
Servlet dependency :
Struts 1 is completely dependent on servlet api. where as Struts 2 action is not its execute() method doesn't required Servlet API. can use simple POJO
Threading Model :
Struts 1 Actions are singletons and must be thread-safe.
Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
Validation :
Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator.
Struts 2 supports manual validation via the validate method and the XWork Validation framework.
Type Conversion :
Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion.
Struts 2 uses OGNL for type conversion.
Binding values into views :
Struts 1 uses the standard JSP mechanism for binding objects into the page context for access.
Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering.
Expression Language :
Struts 1 integrates with JSTL, so it uses the JSTL EL.
Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
12. Which design pattern the Interceptors in Struts2 is based on ?
Interceptors in Struts2 are based on Intercepting Filters.
13 : Are Interceptors and Filters different ? , If yes then how ?
---------------------------------------------------------------------------
Interceptors and filters are based on intercepting filter,there are few differences when it comes to Struts2.
Filters:
(1) Based on Servlet Specification
(2) Executes on the pattern matches on the request.
(3) Not configurable method calls
Interceptors:
(1) Based on Struts2.
(2) Executes for all the request qualifies for a front controller( A Servlet filter ).And can be
configured to execute additional interceptor for a particular action execution.
(3)Methods in the Interceptors can be configured whether to execute or not by means of
exclude methods or include Methods.
14. In Struts1, the front-controller was a Servlet but in Struts2, it is a filter. What is the possible reason to change it to a filter ?
-------------------------------------------------------------------------------------------------------------------
There are two possibilities why filter is designated as front controller in Strtus2
1. Servlet madel as front controller needs developer to provide a right value in <load-on-startup> which lets the framework to initialize many important aspects.
Struts2 makes our life easy by providing front-controller as a filter,and by nature the filters in web.xml gets initialized automatically as the container starts
2. The second but important one is , the introduction of Interceptors in Struts2 framework.
14. Which class is the front-controller in Struts2 ?
org.apache.struts2.dispatcher.FilterDispatcher
15. How does Interceptors help achieve Struts2 a better framework than Struts1 ?
--------------------------------------------------------------------------------
> Most of the trivial work are made easier to achieve for example automatic form population.
> Intelligent configuration and defaults for example you can have struts.xml or annotation based configuration and out of box interceptors can provide facilities that a common web application needs
>Now Struts2 can be used anywhere in desktop applications also, with minimal or no change of existing web application,since actions are now POJO.POJO actions are even easier to unit test
>Easier UI and validation in form of themes and well known DOJO framework.
>Highly plugable,Integrate other technologies like Spring,Hibernate etc at ease.
> Ready for next generation RESTFUL services
16. What is the relation between ValueStack and OGNL ?
-------------------------------------------------------
A ValueStack is a place where all the data related to action and the action itself is stored. OGNL is a mean through which the data in the ValueStack is manipulated.
17. What is the difference between empty default namespace and root name space ?
--------------------------------------------------------------------------------
If the namespace attribute is not defined in the package tag or assigned "" value then it is called empty default namespace.While if "/" is assigned as value to the namespace attribute then it is called as root namespace. The root namespace is treated as all other explicit namespaces and must be matched. It’s important to distinguish between the empty default namespace, which can catch all request patterns as long as the action name matches, and the root namespace, which is an actual namespace that must be matched.
18. Which interceptor is responsible for setting action's JavaBean properties ?
--------------------------------------------------------------------------------
com.opensymphony.xwork2.interceptor.ParametersInterceptor is the interceptor class who sets the action's JavaBean properties from request.
19. What is the difference between Action and ActionSupport ?
--------------------------------------------------------------------------------
Action is interface defines some string like SUCCESS,ERROR etc and an execute() method. For convenience Developer implement this interface to have access to String field in action methods.
ActionSupport on other hand implements Action and some other interfaces and provides some feature like data validation and localized error messaging when extended in the action classes by developers.
20. Does the order in which interceptors execute matters ? If yes then why ?
-----------------------------------------------------------------------------------------
Well, the answer is yes and no.Some Interceptors are designed to be independent so the order doesn't matter,but some interceptors are totally dependent on the previous interceptors execution.For example the validation and workflow interceptors,the validation interceptors checks if there is any error in the form being submitted to the action, then comes the workflow interceptor who checks if validation ( occured in the last) has any error,in presence of error it will not let the rest of the interceptors ( if any ) in the stack to execute.So this is very important that the validation interceptors execute first before the workflow. On the other hand lets say you wrote an interceptors who is doing the authentication and you have the user credential provided ( by the time this executes) it doesn't matter where this interceptors is placed( It is a different fact that you would like to keep it in the top ).
21. What is the difference between RequestAware and ServletRequestAware interface ?
---------------------------------------------------------------------------------------------------------
RequestAware and ServletRequestAware both makes your action to deals with the servlet request, but in a different ways,RequestAware gives you the attributes in the servlet request as a map( key as attribute name and value is the object added),But ServletRequestAware gives you the HttpServletRequest object
22.What is the difference between EL and OGNL ?
----------------------------------------------------------------
OGNL is much like EL in JSPs,a language to traverse or manupulate objects like request , session or application in web context.OGNL stands for Object graph navigation language,
23. What are the difference between ActionContext and ServletActionContext ?
----------------------------------------------------------------------------
ActionContext represents the context in which Action is executed, which itself doesn't hold any web parameters like session, request etc. ServletActionContext, extends the ActionContext and provides the web parameters to the Action
24. What is the DispatchAction (Struts1) equivalent in Strtus2 ?
------------------------------------------------------------------
Struts1 provided the facility of having related action methods in a Single Action class,depending on the method parameter, the mapped methods were executed.To achieve this we have to extend the DispatchAction class in Struts1.But this comes as default in Struts2, We need to provide the qualified methods in the action class( no need to inherit any class), and provide the mapping of action path/name to the method attribute in action tag(struts.xml) and proper code in view layer.
25. What is the role of Action/ Model ?
--------------------------------------------------
Actions in Struts are POJO , is also considered as a Model. The role of Action are to execute business logic or delegate call to business logic by the means of action methods which is mapped to request and contains business data to be used by the view layer by means of setters and getters inside the Action class and finally helps the framework decide which result to render
------------------------------------------------------------------
Action servlet: it’s a back-bone of web application it’s a controller class responsible for handling the entire request.
Action class: using Action classes where all the business logic implemented.
Action Form: it’s a java bean which represents our forms and associated with action mapping. And it also maintains the session state its object is
automatically populated on the server side with data entered from a form on the client side.
Action Mapping: using this class we do the mapping between object and Action.
ActionForward: this class in Struts is used to forward the result from controller to destination.
2. How exceptions are handled in Struts application?
----------------------------------------------------
There are two ways of handling exception in Struts:
Pro grammatically handling: using try {} catch block in code where exception can come and flow of code is also decided by programmer .its a normal java language
concept.
Declarative Exception Handling: we can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
example:
<global-exception-mappings>
<exception-mapping exception="java.sql.SQLException" result="SQLException"/>
<exception-mapping exception="java.lang.Exception" result="Exception"/>
</global-exception-mappings>
...
<action name="DataAccess" class="com.company.DataAccess">
<exception-mapping exception="com.company.SecurityException" result="login"/>
<result name="SQLException" type="chain">SQLExceptionAction</result>
<result>/DataAccess.jsp</result>
</action>
...
3. How validation is performed in struts application?
------------------------------------------------------
In struts validation is performed using validator framework, Validator Framework in Struts consist of two XML configuration files.
1. validator-rules.xml file: which contains the default struts pluggable validator definitions. You can add new validation rules by adding an entry in this file.
This was the original beauty of struts which makes it highly configurable.
2. Validation.xml files which contain details regarding the validation routines that are applied to the different Form Beans.
4. Dispatch Action , LookupDispatch Action , EventDispatchAction
------------------------------------------------
Dispatch Action:An abstract Action that dispatches to a public method that is named by the request parameter whose name is specified by the parameter property of the corresponding ActionMapping. This Action is useful for developers who prefer to combine many similar actions into a single Action class, in order to simplify their application design.
Example :
<action path="/saveSubscription" type="org.apache.struts.actions.DispatchAction" name="subscriptionForm" scope="request" input="/subscription.jsp" parameter="method"/>
LookupDispatchAction : An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. To configure the use of this action in your struts-config.xml file, create an entry like this:
<action path="/test"
type="org.example.MyAction"
name="MyForm"
scope="request"
input="/test.jsp"
parameter="method"/>
EventDispatchAction: An Action that dispatches to to one of the public methods that are named in the parameter attribute of the corresponding ActionMapping and matches a submission parameter. This is useful for developers who prefer to use many submit buttons, images, or submit links on a single form and whose related actions exist in a single Action class.
<action path="/saveSubscription"
type="org.example.SubscriptionAction"
name="subscriptionForm"
scope="request"
input="/subscription.jsp"
parameter="save,back,recalc=recalculate,default=save"/>
5. How you can retrieve the value which is set in the JSP Page in case of DynaActionForm?
--------------------------------------------------------------------------------------------
DynaActionForm is a popular topic in Struts interview questions. DynaActionForm is subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time.
6. what the Validate () and reset () method does?
----------------------------------------------------
validate() : validate method is Used to validate properties after they have been populated, and this ,method is Called before FormBean is passed to Action.
Returns a collection of ActionError as ActionErrors.
reset() : The purpose of this method is to reset all of the ActionForm's data
7. How you will make available any Message Resources Definitions file to the Struts Framework Environment?
----------------------------------------------------------------------------------------------------------
Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources
Definitions files can be added to the struts-config.xml file through < message-resources / > tag and also using web.xml
8. Explain Struts work Flow?
---------------------------------
1) A request comes in from a Java Server Page into the ActionServlet.
2) The ActionServlet having already read the struts-config.xml file, knows which form bean relates to this JSP, and delegates work to the validate method of that form bean.
3) The form bean performs the validate method to determine if all required fields have been entered, and performs whatever other types of field validations that need to be performed.
4) If any required field has not been entered, or any field does not pass validation, the form bean generates ActionErrors, and after checking all fields returns back to the ActionServlet.
5) The ActionServlet checks the ActionErrors that were returned from the form beans validate method to determine if any errors have occurred. If errors have occurred, it returns to the originating JSP displaying the appropriate errors.
6) If no errors occurred in the validate method of the form bean, the ActionServlet passes control to the appropriate Action class.
7) The Action class performs any necessary business logic, and then forwards to the next appropriate action (probably another JSP).
9. How can I create a wizard work flow?
-------------------------------------------------
The basic idea is a series of actions with next, back, cancel and finish actions with a common bean. Using a LookupDispatchAction is recommended as it fits the design pattern well and can be internationalized easily.
10. How to do 'chain' Actions?
-----------------------------------------
Chaining actions can be done by simply using the proper mapping in your forward entries in the struts-config.xml file.
example :
<forward name="success" path="/xyz.do" />
11. diff detween Struts 1 and Struts 2
---------------------------------------
Action classes :
In struts 1 Action classes extend an abstract base class.
An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom service,Struts 2 provides a base ActionSupport class to implement commonly used interfaces.
Servlet dependency :
Struts 1 is completely dependent on servlet api. where as Struts 2 action is not its execute() method doesn't required Servlet API. can use simple POJO
Threading Model :
Struts 1 Actions are singletons and must be thread-safe.
Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
Validation :
Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator.
Struts 2 supports manual validation via the validate method and the XWork Validation framework.
Type Conversion :
Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion.
Struts 2 uses OGNL for type conversion.
Binding values into views :
Struts 1 uses the standard JSP mechanism for binding objects into the page context for access.
Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering.
Expression Language :
Struts 1 integrates with JSTL, so it uses the JSTL EL.
Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
12. Which design pattern the Interceptors in Struts2 is based on ?
Interceptors in Struts2 are based on Intercepting Filters.
13 : Are Interceptors and Filters different ? , If yes then how ?
---------------------------------------------------------------------------
Interceptors and filters are based on intercepting filter,there are few differences when it comes to Struts2.
Filters:
(1) Based on Servlet Specification
(2) Executes on the pattern matches on the request.
(3) Not configurable method calls
Interceptors:
(1) Based on Struts2.
(2) Executes for all the request qualifies for a front controller( A Servlet filter ).And can be
configured to execute additional interceptor for a particular action execution.
(3)Methods in the Interceptors can be configured whether to execute or not by means of
exclude methods or include Methods.
14. In Struts1, the front-controller was a Servlet but in Struts2, it is a filter. What is the possible reason to change it to a filter ?
-------------------------------------------------------------------------------------------------------------------
There are two possibilities why filter is designated as front controller in Strtus2
1. Servlet madel as front controller needs developer to provide a right value in <load-on-startup> which lets the framework to initialize many important aspects.
Struts2 makes our life easy by providing front-controller as a filter,and by nature the filters in web.xml gets initialized automatically as the container starts
2. The second but important one is , the introduction of Interceptors in Struts2 framework.
14. Which class is the front-controller in Struts2 ?
org.apache.struts2.dispatcher.FilterDispatcher
15. How does Interceptors help achieve Struts2 a better framework than Struts1 ?
--------------------------------------------------------------------------------
> Most of the trivial work are made easier to achieve for example automatic form population.
> Intelligent configuration and defaults for example you can have struts.xml or annotation based configuration and out of box interceptors can provide facilities that a common web application needs
>Now Struts2 can be used anywhere in desktop applications also, with minimal or no change of existing web application,since actions are now POJO.POJO actions are even easier to unit test
>Easier UI and validation in form of themes and well known DOJO framework.
>Highly plugable,Integrate other technologies like Spring,Hibernate etc at ease.
> Ready for next generation RESTFUL services
16. What is the relation between ValueStack and OGNL ?
-------------------------------------------------------
A ValueStack is a place where all the data related to action and the action itself is stored. OGNL is a mean through which the data in the ValueStack is manipulated.
17. What is the difference between empty default namespace and root name space ?
--------------------------------------------------------------------------------
If the namespace attribute is not defined in the package tag or assigned "" value then it is called empty default namespace.While if "/" is assigned as value to the namespace attribute then it is called as root namespace. The root namespace is treated as all other explicit namespaces and must be matched. It’s important to distinguish between the empty default namespace, which can catch all request patterns as long as the action name matches, and the root namespace, which is an actual namespace that must be matched.
18. Which interceptor is responsible for setting action's JavaBean properties ?
--------------------------------------------------------------------------------
com.opensymphony.xwork2.interceptor.ParametersInterceptor is the interceptor class who sets the action's JavaBean properties from request.
19. What is the difference between Action and ActionSupport ?
--------------------------------------------------------------------------------
Action is interface defines some string like SUCCESS,ERROR etc and an execute() method. For convenience Developer implement this interface to have access to String field in action methods.
ActionSupport on other hand implements Action and some other interfaces and provides some feature like data validation and localized error messaging when extended in the action classes by developers.
20. Does the order in which interceptors execute matters ? If yes then why ?
-----------------------------------------------------------------------------------------
Well, the answer is yes and no.Some Interceptors are designed to be independent so the order doesn't matter,but some interceptors are totally dependent on the previous interceptors execution.For example the validation and workflow interceptors,the validation interceptors checks if there is any error in the form being submitted to the action, then comes the workflow interceptor who checks if validation ( occured in the last) has any error,in presence of error it will not let the rest of the interceptors ( if any ) in the stack to execute.So this is very important that the validation interceptors execute first before the workflow. On the other hand lets say you wrote an interceptors who is doing the authentication and you have the user credential provided ( by the time this executes) it doesn't matter where this interceptors is placed( It is a different fact that you would like to keep it in the top ).
21. What is the difference between RequestAware and ServletRequestAware interface ?
---------------------------------------------------------------------------------------------------------
RequestAware and ServletRequestAware both makes your action to deals with the servlet request, but in a different ways,RequestAware gives you the attributes in the servlet request as a map( key as attribute name and value is the object added),But ServletRequestAware gives you the HttpServletRequest object
22.What is the difference between EL and OGNL ?
----------------------------------------------------------------
OGNL is much like EL in JSPs,a language to traverse or manupulate objects like request , session or application in web context.OGNL stands for Object graph navigation language,
23. What are the difference between ActionContext and ServletActionContext ?
----------------------------------------------------------------------------
ActionContext represents the context in which Action is executed, which itself doesn't hold any web parameters like session, request etc. ServletActionContext, extends the ActionContext and provides the web parameters to the Action
24. What is the DispatchAction (Struts1) equivalent in Strtus2 ?
------------------------------------------------------------------
Struts1 provided the facility of having related action methods in a Single Action class,depending on the method parameter, the mapped methods were executed.To achieve this we have to extend the DispatchAction class in Struts1.But this comes as default in Struts2, We need to provide the qualified methods in the action class( no need to inherit any class), and provide the mapping of action path/name to the method attribute in action tag(struts.xml) and proper code in view layer.
25. What is the role of Action/ Model ?
--------------------------------------------------
Actions in Struts are POJO , is also considered as a Model. The role of Action are to execute business logic or delegate call to business logic by the means of action methods which is mapped to request and contains business data to be used by the view layer by means of setters and getters inside the Action class and finally helps the framework decide which result to render
Hibernate Questions
1. What is Hibernate?
--------------------------
Hibernate is an object-relational mapping tool, a persistence framework.
2. What is ORM
---------------
Object-relational mapping of database tables to domain object classes. ORM resolve Object-Relational Impedance Mismatch sometime called paradigm mismatch viz
Inheritance: RDBMSs do not define anything regarding this, some databases do have subtype support but it is completely non-standardized.
Identity : RDBMS defines exactly one notion of 'sameness' the primary key, but oop defines both object identity (a==b) and object equality (a.equals(b)).
Associations : Associations can be represented as unidirectional/bidirectional in OOP whereas RDBMSs use the notion of foreign keys.
Data navigation : navigate from one association to an other walking the object network.RDBMS use JOINs.
3. Advantage Of ORM
--------------------
1. Productivity : Developers more concentrate on the business logic and increase the project’s productivity by rid of writing complex and tedious SQL statement,
2. Maintainability : helps to reduce the lines of code as a result more easier to refactor.
3. Portability : witching to other SQL database requires few changes in Hibernate configuration file.
4 Caching : Caching feature reduced round trips between an application and the database
4. What are the core interfaces of Hibernate framework?
--------------------------------------------------------
1. Session Interface: Light weight and a non-threadsafe object that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and
closed when all work is complete.
2. SessionFactory interface: SessionFactory is threadsafe responsible for creating session on request from the application. Usually an application has a single
SessionFactory instance
3. Configuration Interface: Allows the application to specify properties and mapping documents to be used when creating a SessionFactory.
4. Transaction Interface: provide support for 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.
5. Explain hibernate object states? Explain hibernate objects life cycle?
-------------------------------------------------------------------------
Transient : An object instantiated using the "new" operator which is not associated with any session in hibernate is said to be in Transient state.
Persistent : A persistent instance has a representation in the database and an identifier value. associated with any session.
Detached : A detached instance is an object that has been persistent, but its Session has been closed hence no longer associated with a session.
life cycle:
When we create an object of our pojo class ,we can say it is in Transient state. At the time of Transient state any modification does not affect database table. If no longer referenced by any other object, it refer to garbage collection.
When you save transient object it enter into persistent state. Persistent instance has valid database table row with a primary key identifier .
The persistent object is still exist after closure of the active session is detached object. It is still represents to the valid row in the database. Can reattach detached
Removed State :
When the persistent object is deleted from the database. At this state java instance exist but any changes made to the object are not saved to the database.
6. When does an object become detached?
---------------------------------------------------
Session session1 = sessionFactory.openSession();
Car myCar = session1.get(Car.class, carId); //”myCar” is a persistent object at this stage.
session1.close();
it can be reattached to another session as shown below:
Session session2 = sessionFactory.openSession();
Transaction tx = session2.beginTransaction();
session2.update(myCar); //detached object ”myCar” gets re-attached
tx.commit(); //change is synchronized with the database.
session2.close()
7. How does Hibernate distinguish between transient and detached objects?
-------------------------------------------------------------------------------------------
Hibernate uses the "version" property, if there is one. If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. Write own strategy with Interceptor.isUnsaved().
8. What are the benefits of detached objects?
-----------------------------------------------------
Detached objects can be reattached to another session. need to make sure that the dependent objects are reattached as well.
9. What is the difference between sorted and ordered collection in hibernate?
-----------------------------------------------------------------------------
Sorted Collection is sorting a collection by utilizing the sorting features provided by the Java collections framework using java comparator.
Order Collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
10. What are the Collection types in Hibernate ?
----------------------------------------------------
Bag
Set
List
Array
Map
11. What is the difference between the session.get() method and the session.load() method?
---------------------------------------------------------------------------------------
Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.
12.What is the difference between the session.update() method and the session.lock() method?
-----------------------------------------------------------------------------------------
Both update() and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database.Use session.lock() only if you are absolutely sure that the detached object is in sync.
13. How would you reattach detached objects to a session when the same object has already been loaded into the session?
-------------------------------------------------------------------------------------------------------------------
use the session.merge() method call.
14. What are different of caches in Hibernate
------------------------------------------------------
Hibernate uses two different caches
First-Level cache : Associated with the Session object. Hibernate uses this cache by default on per-transaction basis to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction.
Second-level cache : Associates with the Session Factory as result available to whole application rather than any particular session. Improve performance by saving few database round trip.By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.
Hibernate configuration:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
15. How does the hibernate second-level cache work?
------------------------------------------------------------------
Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database.
16. What is query cache in Hibernate ?
----------------------------------------------
Query Cache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries.
Example:
final Order customer = ... ;
final String hql = "from Order as order where order.cusomer.id = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer.getId());
q.setCacheable(true);
Hibernate configuration:
<property name="hibernate.cache.use_query_cache">true</property>
17. What are the different cache concurrency strategy:
---------------------------------------------------------------
Read-only : This strategy is useful for data that is read frequently but never updated.
Read-write : appropriate if your data needs to be updated. They carry more overhead than read-only caches.
Nonstrict-read-write: This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes
Transactional : This is a fully transactional cache that may be used only in a JTA environment.
18. What are the different fetching strategy in Hibernate :
---------------------------------------------------------------------
Join Fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
Select Fetching: A second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy=”false”, this second select will only be executed when you access the association.
Subselect fetching: A second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifyinglazy=”false”, this second select will only be executed when you access the association.
Batch fetching: Using primary or foreign keys hibernate retrieves a batch of entity instances or collections in a single SELECT.
19. What do you understand by automatic dirty checking in Hibernate?
-----------------------------------------------------------------------------------
Dirty checking concept :
Dirty checking is a concept to avoid time consuming database write actions. By this concept, all necessary updating and changes are done without affecting the other fields.Only the changed fields of database are updated and the remaining unchanged fields are left untouched.
Hibernate Dirty Checking :
Hibernate allows dirty checking feature. It saves developer's time and effort in updating of database when states of objects are modified inside a transaction.Hibernate automatically detects the object states whenever changed and synchronized with the database in order to update.
20. What session.flush() do
------------------------------------
Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database.By default, Hibernate will flush changes automatically
21. What is version checking in Hibernate ?
-----------------------------------------------------
Version checking used in hibernate when more then one thread trying to access same data.Optimistic locking using the version attribute
22. Optimistic vs. Pessimistic Locking
-------------------------------------------
Optimistic locking assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check
reveals conflicting modifications, the committing transaction rolls back.
Pessimistic locking assumes that concurrent transactions will conflict with each other, and requires resources to be locked after they are read and only unlocked after the application has finished using the data.
23. Why it's important to provide no argument constructor in Hibernate Entities?
----------------------------------------------------------------------------
Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API,
24. 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
25. What is HQL ?
----------------------
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database
26. What is lazy fetching in hibernate ?
------------------------------------------
Lazy fetching is associated with child objects loading for its parents. While loading the parent, the selection of loading a child object is to be specified / mentioned in the hbm.xml file. Hibernate does not load the whole child objects by default. Lazy=true means not to load the child objects.
27. What are derived properties?
--------------------------------------------
The properties that are not mapped to a column, but calculated and evaluated at runtime called derived properties.JPA doesn't offer any support for derived property
example
@Formula("PRICE*1.155")
private float finalPrice;
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;
or
<property name="finalPrice" formula="PRICE*1.155" type="date" />
<property name="firstOrderDate" formula="select min(o.creation_date) from Orders o where o.customer_id = id" type="date" />
28. What are the ways to express joins in HQL?
--------------------------------------------------------
HQL provides four ways of expressing (inner and outer) joins:-
An implicit association join : from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten
join in the FROM clause : from Cat as cat inner join fetch cat.mate left join fetch cat.kittens child left join fetch child.kittens
theta-style join in the WHERE clause.
29. What are the types of inheritance models in Hibernate?
---------------------------------------------------------------------
There are three types of inheritance models in Hibernate:
Table per class hierarchy
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn( name=""discriminator"", discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value=""P"")
Table per subclass
@Inheritance(strategy=InheritanceType.JOINED)
Table per concrete class
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
--------------------------
Hibernate is an object-relational mapping tool, a persistence framework.
2. What is ORM
---------------
Object-relational mapping of database tables to domain object classes. ORM resolve Object-Relational Impedance Mismatch sometime called paradigm mismatch viz
Inheritance: RDBMSs do not define anything regarding this, some databases do have subtype support but it is completely non-standardized.
Identity : RDBMS defines exactly one notion of 'sameness' the primary key, but oop defines both object identity (a==b) and object equality (a.equals(b)).
Associations : Associations can be represented as unidirectional/bidirectional in OOP whereas RDBMSs use the notion of foreign keys.
Data navigation : navigate from one association to an other walking the object network.RDBMS use JOINs.
3. Advantage Of ORM
--------------------
1. Productivity : Developers more concentrate on the business logic and increase the project’s productivity by rid of writing complex and tedious SQL statement,
2. Maintainability : helps to reduce the lines of code as a result more easier to refactor.
3. Portability : witching to other SQL database requires few changes in Hibernate configuration file.
4 Caching : Caching feature reduced round trips between an application and the database
4. What are the core interfaces of Hibernate framework?
--------------------------------------------------------
1. Session Interface: Light weight and a non-threadsafe object that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and
closed when all work is complete.
2. SessionFactory interface: SessionFactory is threadsafe responsible for creating session on request from the application. Usually an application has a single
SessionFactory instance
3. Configuration Interface: Allows the application to specify properties and mapping documents to be used when creating a SessionFactory.
4. Transaction Interface: provide support for 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.
5. Explain hibernate object states? Explain hibernate objects life cycle?
-------------------------------------------------------------------------
Transient : An object instantiated using the "new" operator which is not associated with any session in hibernate is said to be in Transient state.
Persistent : A persistent instance has a representation in the database and an identifier value. associated with any session.
Detached : A detached instance is an object that has been persistent, but its Session has been closed hence no longer associated with a session.
life cycle:
When we create an object of our pojo class ,we can say it is in Transient state. At the time of Transient state any modification does not affect database table. If no longer referenced by any other object, it refer to garbage collection.
When you save transient object it enter into persistent state. Persistent instance has valid database table row with a primary key identifier .
The persistent object is still exist after closure of the active session is detached object. It is still represents to the valid row in the database. Can reattach detached
Removed State :
When the persistent object is deleted from the database. At this state java instance exist but any changes made to the object are not saved to the database.
6. When does an object become detached?
---------------------------------------------------
Session session1 = sessionFactory.openSession();
Car myCar = session1.get(Car.class, carId); //”myCar” is a persistent object at this stage.
session1.close();
it can be reattached to another session as shown below:
Session session2 = sessionFactory.openSession();
Transaction tx = session2.beginTransaction();
session2.update(myCar); //detached object ”myCar” gets re-attached
tx.commit(); //change is synchronized with the database.
session2.close()
7. How does Hibernate distinguish between transient and detached objects?
-------------------------------------------------------------------------------------------
Hibernate uses the "version" property, if there is one. If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. Write own strategy with Interceptor.isUnsaved().
8. What are the benefits of detached objects?
-----------------------------------------------------
Detached objects can be reattached to another session. need to make sure that the dependent objects are reattached as well.
9. What is the difference between sorted and ordered collection in hibernate?
-----------------------------------------------------------------------------
Sorted Collection is sorting a collection by utilizing the sorting features provided by the Java collections framework using java comparator.
Order Collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
10. What are the Collection types in Hibernate ?
----------------------------------------------------
Bag
Set
List
Array
Map
11. What is the difference between the session.get() method and the session.load() method?
---------------------------------------------------------------------------------------
Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.
12.What is the difference between the session.update() method and the session.lock() method?
-----------------------------------------------------------------------------------------
Both update() and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database.Use session.lock() only if you are absolutely sure that the detached object is in sync.
13. How would you reattach detached objects to a session when the same object has already been loaded into the session?
-------------------------------------------------------------------------------------------------------------------
use the session.merge() method call.
14. What are different of caches in Hibernate
------------------------------------------------------
Hibernate uses two different caches
First-Level cache : Associated with the Session object. Hibernate uses this cache by default on per-transaction basis to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction.
Second-level cache : Associates with the Session Factory as result available to whole application rather than any particular session. Improve performance by saving few database round trip.By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.
Hibernate configuration:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
15. How does the hibernate second-level cache work?
------------------------------------------------------------------
Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database.
16. What is query cache in Hibernate ?
----------------------------------------------
Query Cache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries.
Example:
final Order customer = ... ;
final String hql = "from Order as order where order.cusomer.id = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer.getId());
q.setCacheable(true);
Hibernate configuration:
<property name="hibernate.cache.use_query_cache">true</property>
17. What are the different cache concurrency strategy:
---------------------------------------------------------------
Read-only : This strategy is useful for data that is read frequently but never updated.
Read-write : appropriate if your data needs to be updated. They carry more overhead than read-only caches.
Nonstrict-read-write: This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes
Transactional : This is a fully transactional cache that may be used only in a JTA environment.
18. What are the different fetching strategy in Hibernate :
---------------------------------------------------------------------
Join Fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
Select Fetching: A second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy=”false”, this second select will only be executed when you access the association.
Subselect fetching: A second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifyinglazy=”false”, this second select will only be executed when you access the association.
Batch fetching: Using primary or foreign keys hibernate retrieves a batch of entity instances or collections in a single SELECT.
19. What do you understand by automatic dirty checking in Hibernate?
-----------------------------------------------------------------------------------
Dirty checking concept :
Dirty checking is a concept to avoid time consuming database write actions. By this concept, all necessary updating and changes are done without affecting the other fields.Only the changed fields of database are updated and the remaining unchanged fields are left untouched.
Hibernate Dirty Checking :
Hibernate allows dirty checking feature. It saves developer's time and effort in updating of database when states of objects are modified inside a transaction.Hibernate automatically detects the object states whenever changed and synchronized with the database in order to update.
20. What session.flush() do
------------------------------------
Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database.By default, Hibernate will flush changes automatically
21. What is version checking in Hibernate ?
-----------------------------------------------------
Version checking used in hibernate when more then one thread trying to access same data.Optimistic locking using the version attribute
22. Optimistic vs. Pessimistic Locking
-------------------------------------------
Optimistic locking assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check
reveals conflicting modifications, the committing transaction rolls back.
Pessimistic locking assumes that concurrent transactions will conflict with each other, and requires resources to be locked after they are read and only unlocked after the application has finished using the data.
23. Why it's important to provide no argument constructor in Hibernate Entities?
----------------------------------------------------------------------------
Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API,
24. 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
25. What is HQL ?
----------------------
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database
26. What is lazy fetching in hibernate ?
------------------------------------------
Lazy fetching is associated with child objects loading for its parents. While loading the parent, the selection of loading a child object is to be specified / mentioned in the hbm.xml file. Hibernate does not load the whole child objects by default. Lazy=true means not to load the child objects.
27. What are derived properties?
--------------------------------------------
The properties that are not mapped to a column, but calculated and evaluated at runtime called derived properties.JPA doesn't offer any support for derived property
example
@Formula("PRICE*1.155")
private float finalPrice;
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;
or
<property name="finalPrice" formula="PRICE*1.155" type="date" />
<property name="firstOrderDate" formula="select min(o.creation_date) from Orders o where o.customer_id = id" type="date" />
28. What are the ways to express joins in HQL?
--------------------------------------------------------
HQL provides four ways of expressing (inner and outer) joins:-
An implicit association join : from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten
join in the FROM clause : from Cat as cat inner join fetch cat.mate left join fetch cat.kittens child left join fetch child.kittens
theta-style join in the WHERE clause.
29. What are the types of inheritance models in Hibernate?
---------------------------------------------------------------------
There are three types of inheritance models in Hibernate:
Table per class hierarchy
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn( name=""discriminator"", discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value=""P"")
Table per subclass
@Inheritance(strategy=InheritanceType.JOINED)
Table per concrete class
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
EJB Most Wanted Questions
1. What is EJB?
-------------------
Enterprise JavaBeans (EJB) is the server-side component which runs on application server developed for the purpose of distributed and enterprise level application. Container/Server will provide support for system level services like Transaction Management, security which make developer task easy and he can focus on business logic.
2. What are the different types of EJB?
----------------------------------------------
There are 3 types of enterprise beans, namely: Session bean, Entity beans and Message driven beans.
Session bean :
A session bean represents a single client inside the Application Server. To access an application that is deployed on the server, the client invokes the session bean’s methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server.
Two type of session bean:
Stateless : A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client, but only for the duration of the invocation.
Stateful: The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client-bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state.The state is retained for the duration of the client-bean session. If the client removes the bean or terminates, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends there is no need to retain the state
Message Driven Beans: these beans are work as a listener for messaging services like JMS .
3. How EJB Invocation happens?
----------------------------------------
Step 1: Retrieve Home Object reference from Naming Service via JNDI.
step 2: Return Home Object reference to the client.
step 3: Create me a new EJB Object through Home Object interface.
step 4: Create EJB Object from the Ejb Object
step 5: Return EJB Object reference to the client.
step 6: Invoke business method using EJB Object reference.
step 7: Delegate request to Bean (Enterprise Bean
4. session bean life cycle callbacks methods
------------------------------------------
The EJB session bean life cycle methods are called by the EJB container to notify a session bean instance when specific life cycle events occur.
ejbCreate(): Called just after the session bean instance is created. in response to a client calling create() on the bean's home interface.
ejbRemove() : Called just before a session bean instance is permanently destroyed, in response to a client calling remove() on the bean's remote interface or on the bean's home interface
ejbPassivate() : Called just before the container passivated the bean by storing the bean data (typically serializing the bean) and removing the bean instance from memory. The container passivated a bean in order to conserve memory and other resources. The container is prepared, however, to reactivate the bean automatically as soon as it is needed again.
ejbActivate() : Called just after the container has reactivated a bean that was previously passivated.
5. EJB Entity Bean Life Cycle callbacks Methods
-----------------------------------------------------------
The EJB entity bean life cycle methods are called by the EJB container to notify an entity bean instance when specific life cycle events occur
ejbCreate() : Called just after the entity bean instance is created, in response to a client calling create on the bean's home interface. The return PrimaryKeyType depends on the kind of persistence that is used:
Container-Managed Persistence -- returns null
Bean-Managed Persistence -- returns the primary key for this bean instance.
ejbPostCreate() : Called after the entity bean is fully initialized. At this stage both the bean data and the primary key are initialized irrespective of whether container-managed or bean-managed persistence is used.
ejbRemove() : Called just before an entity bean instance is permanently destroyed, in response to a client calling remove() on the bean's remote interface or on the bean's home interface.
ejbPassivate() : Called just before the container passivates the bean by storing the bean data (typically serializing the bean) and removing the bean instance from memory.
ejbActivate() : Called just after the container has reactivated a bean that was previously passivated.
ejbLoad() : Load the entity bean state from the database. Typically, the container calls this method at the start of a transaction to ensure that the state of the bean in memory is synchronized with the state in the database.
ejbStore() : Store the entity bean state in the database. Typically, the container calls this method at the end of a transaction to update the bean state in the database.
ejbFind() : The ejbFind() methods need only be defined on the entity bean class.
setEntityContext : particularly for BMP
unsetEntityContext : particularly for BMP
6. Life Cycle of a Stateless Session Bean
---------------------------------------------------
Does not exist: In this state, the bean instance simply does not exist.
Ready state: When Server is first started, several bean instances are created and placed in the Ready pool. More instances might be created by the container as needed by the EJB container.
Brief :
Stales session bean has short life cycle it can have two stage does not exist and ready stage. ejb container create the instance of stateless session bean and call setSessionContext () and ejbCreate() method.Now the bean is ready to invoke business method on this.it will not maintain the state so remove () method is been called after completion of business method which in turns call ejbRemove and now its ready for garbage collection.
7. Life Cycle of a Stateful Session Bean
----------------------------------------------
Does not exist: In this state, the bean instance simply does not exist.
Ready state: A bean instance in the ready state is tied to particular client and engaged in a conversation.
Passive state: A bean instance in the passive state is passivated to conserve resource.
Brief :
Stateful session beans life cycle starts when client call create() method.The container create the instance of session bean and call setSessionContext() and ejbCreate() method. Now the stateful session bean is ready to serve the client request after serving the request if it is not used after a long time container can move this bean to passive stage by calling the ejbPassivate() method. similarly when bean is in passive stage and client invoke the business method the container call ejbActivate() method to move bean from passive stage to active or ready stage. At the end of life cycle client call remove() method and container will call ejbRemove() method and bean is ready for
8. Life Cycle of an Entity Bean
-----------------------------------
Does not exist: In this state, the bean instance simply does not exist.
Pooled state : When WebLogic server is first started, several bean instances are created and placed in the pool. A bean instance in the pooled state is not tied to particular data, that is, it does not correspond to a record in a database table. Additional bean instances can be added to the pool as needed, and a maximum number of instances can be set.
Ready state: A bean instance in the ready state is tied to particular data, that is, it represents an instance of an actual business object.
Brief :
First stage is Does Not Exist Stage then Container creates the instance of EJB and call SetEntityContext() method which will set all entity context to bean and now it will become available on pool,to get a particular identity of an EJB object it has to move from Pooled stage to ready stage which is done by calling the create () method which in turns call ejbCreate() and ejbPostCreate() method .There is another way by which directly entity bean can move to pooled stage to
ready stage that’s is call ejbActivate() method. now we are ready to invoke method of entity bean .After completion of method if we want to move again in pooled stage from ready stage we can call remove() method which in turns call ejbRemove() or directly call ejbPassivate () method. At the end container remove the instance from pool and call unSetEntityContext().
9. Message-Driven Bean Life Cycle callbacks Methods
---------------------------------------------------------------------
PostConstruct : The PostConstruct callback occurs after the container creates a new instance of MDB and before the first message listener method invocation on the bean
PreDestroy : The PreDestroy callback occurs before the bean is removed from the pool or destroyed.
Brief :
A message-driven bean instance’s life starts when the container invokes newInstance on the message-driven bean class to create a new instance.Next, the container injects the bean’s MessageDrivenContext, if applicable, and performs any other dependency injection as specified by meta-data annotations on the bean class or by the deployment descriptor.The container then calls the bean’s PostConstruct lifecycle callback methods, if any.The message-driven bean instance is now ready to be delivered a message sent to its associated destination or endpoint by any client or a call from the container to a timeout callback method.When the container no longer needs the instance (which usually happens when the container wants to reduce the number of instances in the method-ready pool), the container invokes the PreDestroy lifecycle callback methods for it, if any. This ends the life of the message-driven bean instance.
10. What happens if remove( ) is never invoked on a session bean?
--------------------------------------------------------------------------------
In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of Stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.
11. can we have static initializer Block in EJB.
--------------------------------------------------------
From Technical point view of java its correct but violation of specification. In EJB if we use static initializer block to initialize static field then EJB components are used in distributed environment mean run on different JVM then it will be a problem coz if we change or update the value in on environment then only the instance running on same JVM have new value. that’s why static blocks are avoided and also all static field should be final. and same thing we can
achieve in ejbCreate(), setSessionContext() or setEntityContext() methods.
12.Threading is possible in EJB?
----------------------------------------
Not possible because EJBs are created and managed by container and if in ejbs we allow threading containers life cycle methods will be interrupted by us.
13. What about connection pooling feature of EJB container?
-------------------------------------------------------------------------
Connection pooling is one of the Advance feature of container which enhanced our application performance .Using connection pooling mechanism client are not required to create every time connection object to interact with database.Whenever a client request for a database connection then an instance is picked from the connection pool to get an access to database and when user complete with his work instance is returned to connection pool.
14. What are the transaction Attribute ?
------------------------------------------------
A transaction attribute controls the scope of a transaction. Transaction is group of operation should be performed either completely or none. transaction must have ACID property(atomicity , consistency, integrity,durability) so transaction can be said completed if we commit on successful execution and rollback on unsuccessful execution.
A transaction attribute can have one of the following values
Required : the container starts a new transaction before running the method.
RequiresNew : If the client is not associated with a transaction, the container starts a new transaction before running the method or if associated Suspends transaction and Starts a new transaction. After Delegates the call to the method Resumes the client’s transaction.
Mandatory : If the client is running within a transaction then method executes within the client’s transaction. If the client is not associated with a transaction, the container throws the TransactionRequiredException.
NotSupported : If the client is running within a transaction then container suspends the client’s transaction
Supports : If the client is running within a transaction then method executes within the client’s transaction. If the client is not associated with a transaction, then container does not start a new transaction before running the method.
Never : If the client is running within a transaction and invokes the enterprise bean’s method, the container throws a RemoteException.
15.Difference Between ejbStore() and ejbLoad()?
------------------------------------------------------------
ejbLoad method load or refresh the instance variable from the database. This method is called when it is necessary to synchronize the bean with data from the database
ejbStore method writes the variables to the database.This method is called when it is necessary to synchronize the bean data with the database.
16 .Difference between JNDI , Initial , Session , Entity and Ejb Context.
----------------------------------------------------------------------------------------
JNDI context: provides mechanism to lookup resources on network.
Initial Context: it provides initial context to resources.
Session Context: is an EJBContext object provided by the EJB container. it has all the information available which is required to session bean
Entity Context : is an EJBContext object provided by the EJB container. it has all the information available which is required to entiry bean
17. Transaction Management for EJBs
------------------------------------------------------
Container Managed Transactions - In this type, container manages the transaction states.
Bean Managed Transactions - In this type, developer manages the life cycle of transaction states.
18. Home ,Remote , Local interface
-------------------------------------------
Home Interface : home interface specifies how the server will create the bean, using the EJBCreate() method of the bean implementation.
Local Interface : Allow clients to access bean if reside in same JVM, pass parameter by reference
Remote Interface : Allow clients to access bean if reside in different JVM, pass parameter by value
19. What Stubs and Skeletons
------------------------------------
A stub is a proxy for a remote object that runs on the client computer. Stubs forward a client's remote method invocations and their associated arguments to skeletons. he purpose of stub is marshalling the data. converting the java code in network oriented stream. stub classes needed by EJB applications are generated dynamically at runtime when an EJB client needs them.
A skeleton is a proxy for a remote object that runs on the server. converting the network oriented stream into java code.
20 For session beans, we can use the SessionSynchronization interface. For entity beans, how do we have control over a transaction?
---------------------------------------------------------------------------------------------------------------------------------------
SessionSynchronization interface is used by the Session beans to Synchronize the Instance variables after a rollback or after a commit operation, because container does not have any other way to inform the bean of these operations.
For Entity beans Container automatically calls the ejbLoad method that refreshed the values from the database.
21. Why is ejbFindByPrimaryKey mandatory?
------------------------------------------------------------
ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container.Purpose is to reduce duplication of bean.
22. Why do we have a remove method in both EJBHome and EJBObject?
----------------------------------------------------------------------------------------------
EJBHome version of the remove allow us to delete an entity bean without instantiating it
Remote interface version works on an entity bean that you have already instantiated.
23. What restrictions are imposed on an EJB?
---------------------------------------------------------------
1. An enterprise Bean must not use read/write static fields. Using read-only static fields is allowed.
2. An enterprise Bean must not use thread synchronization.
3. An enterprise Bean must not use the AWT
4. An enterprise bean must not use the java.io package
5. An enterprise bean must not attempt to listen on a socket
6. The enterprise bean must not attempt to load a native library.
7. The enterprise bean must not attempt to manage threads.
24. Is it possible to share an HttpSession between a JSP and EJB?
-----------------------------------------------------------------------------------
we can pass the HttpSession as parameter to an EJB method
-------------------
Enterprise JavaBeans (EJB) is the server-side component which runs on application server developed for the purpose of distributed and enterprise level application. Container/Server will provide support for system level services like Transaction Management, security which make developer task easy and he can focus on business logic.
2. What are the different types of EJB?
----------------------------------------------
There are 3 types of enterprise beans, namely: Session bean, Entity beans and Message driven beans.
Session bean :
A session bean represents a single client inside the Application Server. To access an application that is deployed on the server, the client invokes the session bean’s methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server.
Two type of session bean:
Stateless : A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client, but only for the duration of the invocation.
Stateful: The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client-bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state.The state is retained for the duration of the client-bean session. If the client removes the bean or terminates, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends there is no need to retain the state
Message Driven Beans: these beans are work as a listener for messaging services like JMS .
3. How EJB Invocation happens?
----------------------------------------
Step 1: Retrieve Home Object reference from Naming Service via JNDI.
step 2: Return Home Object reference to the client.
step 3: Create me a new EJB Object through Home Object interface.
step 4: Create EJB Object from the Ejb Object
step 5: Return EJB Object reference to the client.
step 6: Invoke business method using EJB Object reference.
step 7: Delegate request to Bean (Enterprise Bean
4. session bean life cycle callbacks methods
------------------------------------------
The EJB session bean life cycle methods are called by the EJB container to notify a session bean instance when specific life cycle events occur.
ejbCreate(): Called just after the session bean instance is created. in response to a client calling create() on the bean's home interface.
ejbRemove() : Called just before a session bean instance is permanently destroyed, in response to a client calling remove() on the bean's remote interface or on the bean's home interface
ejbPassivate() : Called just before the container passivated the bean by storing the bean data (typically serializing the bean) and removing the bean instance from memory. The container passivated a bean in order to conserve memory and other resources. The container is prepared, however, to reactivate the bean automatically as soon as it is needed again.
ejbActivate() : Called just after the container has reactivated a bean that was previously passivated.
5. EJB Entity Bean Life Cycle callbacks Methods
-----------------------------------------------------------
The EJB entity bean life cycle methods are called by the EJB container to notify an entity bean instance when specific life cycle events occur
ejbCreate() : Called just after the entity bean instance is created, in response to a client calling create on the bean's home interface. The return PrimaryKeyType depends on the kind of persistence that is used:
Container-Managed Persistence -- returns null
Bean-Managed Persistence -- returns the primary key for this bean instance.
ejbPostCreate() : Called after the entity bean is fully initialized. At this stage both the bean data and the primary key are initialized irrespective of whether container-managed or bean-managed persistence is used.
ejbRemove() : Called just before an entity bean instance is permanently destroyed, in response to a client calling remove() on the bean's remote interface or on the bean's home interface.
ejbPassivate() : Called just before the container passivates the bean by storing the bean data (typically serializing the bean) and removing the bean instance from memory.
ejbActivate() : Called just after the container has reactivated a bean that was previously passivated.
ejbLoad() : Load the entity bean state from the database. Typically, the container calls this method at the start of a transaction to ensure that the state of the bean in memory is synchronized with the state in the database.
ejbStore() : Store the entity bean state in the database. Typically, the container calls this method at the end of a transaction to update the bean state in the database.
ejbFind() : The ejbFind() methods need only be defined on the entity bean class.
setEntityContext : particularly for BMP
unsetEntityContext : particularly for BMP
6. Life Cycle of a Stateless Session Bean
---------------------------------------------------
Does not exist: In this state, the bean instance simply does not exist.
Ready state: When Server is first started, several bean instances are created and placed in the Ready pool. More instances might be created by the container as needed by the EJB container.
Brief :
Stales session bean has short life cycle it can have two stage does not exist and ready stage. ejb container create the instance of stateless session bean and call setSessionContext () and ejbCreate() method.Now the bean is ready to invoke business method on this.it will not maintain the state so remove () method is been called after completion of business method which in turns call ejbRemove and now its ready for garbage collection.
7. Life Cycle of a Stateful Session Bean
----------------------------------------------
Does not exist: In this state, the bean instance simply does not exist.
Ready state: A bean instance in the ready state is tied to particular client and engaged in a conversation.
Passive state: A bean instance in the passive state is passivated to conserve resource.
Brief :
Stateful session beans life cycle starts when client call create() method.The container create the instance of session bean and call setSessionContext() and ejbCreate() method. Now the stateful session bean is ready to serve the client request after serving the request if it is not used after a long time container can move this bean to passive stage by calling the ejbPassivate() method. similarly when bean is in passive stage and client invoke the business method the container call ejbActivate() method to move bean from passive stage to active or ready stage. At the end of life cycle client call remove() method and container will call ejbRemove() method and bean is ready for
8. Life Cycle of an Entity Bean
-----------------------------------
Does not exist: In this state, the bean instance simply does not exist.
Pooled state : When WebLogic server is first started, several bean instances are created and placed in the pool. A bean instance in the pooled state is not tied to particular data, that is, it does not correspond to a record in a database table. Additional bean instances can be added to the pool as needed, and a maximum number of instances can be set.
Ready state: A bean instance in the ready state is tied to particular data, that is, it represents an instance of an actual business object.
Brief :
First stage is Does Not Exist Stage then Container creates the instance of EJB and call SetEntityContext() method which will set all entity context to bean and now it will become available on pool,to get a particular identity of an EJB object it has to move from Pooled stage to ready stage which is done by calling the create () method which in turns call ejbCreate() and ejbPostCreate() method .There is another way by which directly entity bean can move to pooled stage to
ready stage that’s is call ejbActivate() method. now we are ready to invoke method of entity bean .After completion of method if we want to move again in pooled stage from ready stage we can call remove() method which in turns call ejbRemove() or directly call ejbPassivate () method. At the end container remove the instance from pool and call unSetEntityContext().
9. Message-Driven Bean Life Cycle callbacks Methods
---------------------------------------------------------------------
PostConstruct : The PostConstruct callback occurs after the container creates a new instance of MDB and before the first message listener method invocation on the bean
PreDestroy : The PreDestroy callback occurs before the bean is removed from the pool or destroyed.
Brief :
A message-driven bean instance’s life starts when the container invokes newInstance on the message-driven bean class to create a new instance.Next, the container injects the bean’s MessageDrivenContext, if applicable, and performs any other dependency injection as specified by meta-data annotations on the bean class or by the deployment descriptor.The container then calls the bean’s PostConstruct lifecycle callback methods, if any.The message-driven bean instance is now ready to be delivered a message sent to its associated destination or endpoint by any client or a call from the container to a timeout callback method.When the container no longer needs the instance (which usually happens when the container wants to reduce the number of instances in the method-ready pool), the container invokes the PreDestroy lifecycle callback methods for it, if any. This ends the life of the message-driven bean instance.
10. What happens if remove( ) is never invoked on a session bean?
--------------------------------------------------------------------------------
In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of Stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.
11. can we have static initializer Block in EJB.
--------------------------------------------------------
From Technical point view of java its correct but violation of specification. In EJB if we use static initializer block to initialize static field then EJB components are used in distributed environment mean run on different JVM then it will be a problem coz if we change or update the value in on environment then only the instance running on same JVM have new value. that’s why static blocks are avoided and also all static field should be final. and same thing we can
achieve in ejbCreate(), setSessionContext() or setEntityContext() methods.
12.Threading is possible in EJB?
----------------------------------------
Not possible because EJBs are created and managed by container and if in ejbs we allow threading containers life cycle methods will be interrupted by us.
13. What about connection pooling feature of EJB container?
-------------------------------------------------------------------------
Connection pooling is one of the Advance feature of container which enhanced our application performance .Using connection pooling mechanism client are not required to create every time connection object to interact with database.Whenever a client request for a database connection then an instance is picked from the connection pool to get an access to database and when user complete with his work instance is returned to connection pool.
14. What are the transaction Attribute ?
------------------------------------------------
A transaction attribute controls the scope of a transaction. Transaction is group of operation should be performed either completely or none. transaction must have ACID property(atomicity , consistency, integrity,durability) so transaction can be said completed if we commit on successful execution and rollback on unsuccessful execution.
A transaction attribute can have one of the following values
Required : the container starts a new transaction before running the method.
RequiresNew : If the client is not associated with a transaction, the container starts a new transaction before running the method or if associated Suspends transaction and Starts a new transaction. After Delegates the call to the method Resumes the client’s transaction.
Mandatory : If the client is running within a transaction then method executes within the client’s transaction. If the client is not associated with a transaction, the container throws the TransactionRequiredException.
NotSupported : If the client is running within a transaction then container suspends the client’s transaction
Supports : If the client is running within a transaction then method executes within the client’s transaction. If the client is not associated with a transaction, then container does not start a new transaction before running the method.
Never : If the client is running within a transaction and invokes the enterprise bean’s method, the container throws a RemoteException.
15.Difference Between ejbStore() and ejbLoad()?
------------------------------------------------------------
ejbLoad method load or refresh the instance variable from the database. This method is called when it is necessary to synchronize the bean with data from the database
ejbStore method writes the variables to the database.This method is called when it is necessary to synchronize the bean data with the database.
16 .Difference between JNDI , Initial , Session , Entity and Ejb Context.
----------------------------------------------------------------------------------------
JNDI context: provides mechanism to lookup resources on network.
Initial Context: it provides initial context to resources.
Session Context: is an EJBContext object provided by the EJB container. it has all the information available which is required to session bean
Entity Context : is an EJBContext object provided by the EJB container. it has all the information available which is required to entiry bean
17. Transaction Management for EJBs
------------------------------------------------------
Container Managed Transactions - In this type, container manages the transaction states.
Bean Managed Transactions - In this type, developer manages the life cycle of transaction states.
18. Home ,Remote , Local interface
-------------------------------------------
Home Interface : home interface specifies how the server will create the bean, using the EJBCreate() method of the bean implementation.
Local Interface : Allow clients to access bean if reside in same JVM, pass parameter by reference
Remote Interface : Allow clients to access bean if reside in different JVM, pass parameter by value
19. What Stubs and Skeletons
------------------------------------
A stub is a proxy for a remote object that runs on the client computer. Stubs forward a client's remote method invocations and their associated arguments to skeletons. he purpose of stub is marshalling the data. converting the java code in network oriented stream. stub classes needed by EJB applications are generated dynamically at runtime when an EJB client needs them.
A skeleton is a proxy for a remote object that runs on the server. converting the network oriented stream into java code.
20 For session beans, we can use the SessionSynchronization interface. For entity beans, how do we have control over a transaction?
---------------------------------------------------------------------------------------------------------------------------------------
SessionSynchronization interface is used by the Session beans to Synchronize the Instance variables after a rollback or after a commit operation, because container does not have any other way to inform the bean of these operations.
For Entity beans Container automatically calls the ejbLoad method that refreshed the values from the database.
21. Why is ejbFindByPrimaryKey mandatory?
------------------------------------------------------------
ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container.Purpose is to reduce duplication of bean.
22. Why do we have a remove method in both EJBHome and EJBObject?
----------------------------------------------------------------------------------------------
EJBHome version of the remove allow us to delete an entity bean without instantiating it
Remote interface version works on an entity bean that you have already instantiated.
23. What restrictions are imposed on an EJB?
---------------------------------------------------------------
1. An enterprise Bean must not use read/write static fields. Using read-only static fields is allowed.
2. An enterprise Bean must not use thread synchronization.
3. An enterprise Bean must not use the AWT
4. An enterprise bean must not use the java.io package
5. An enterprise bean must not attempt to listen on a socket
6. The enterprise bean must not attempt to load a native library.
7. The enterprise bean must not attempt to manage threads.
24. Is it possible to share an HttpSession between a JSP and EJB?
-----------------------------------------------------------------------------------
we can pass the HttpSession as parameter to an EJB method
Subscribe to:
Posts (Atom)
AWS Services
1. Identity Access Management (IAM): Used to control Identity (who) Access (what AWS resources). 1....
-
Where will you use ArrayList and where will you use LinkedList? ------------------------------------------------------------------- ArrayLis...
-
1. What is a servlets? Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic re...
-
Context Configuration Annotations : These annotations are used by Spring to guide creation and injection of beans @Req...