Monday, February 20, 2012

Java Spring and Hibernate Interview Questions

1. Explain DI or IOC pattern. 

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependency Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor method instead of creating one inside the constructor. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected; rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter, constructor and interface-based injection. 

Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.


2. What are the different IOC containers available?

Spring is an IOC container. Other IOC containers are HiveMind, Avalon, PicoContainer.

3. What are the different types of dependency injection? Explain with examples.


There are two types of dependency injection: setter injection and constructor injection.
Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows:

public class namebean {
String name;
public void setName(String a) {
name = a; }
public String getName() {
return name; }
}

We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration file as shown below:

< bean id="bean1" class="namebean" >
< property name="name" >
< value > tom < / value >
< / property >
< / bean >

The subelement < value > sets the 'name' property by calling the set method as setName("tom"); This process is called setter injection.

To set properties that reference other beans , subelement of is used as shown below,
< bean id="bean1" class="bean1impl" >
< property name="game" >
< ref bean="bean2" / >
< / property >
< / bean >
< bean id="bean2" class="bean2impl" / >

Constructor injection: For constructor injection, we use constructor with parameters as shown below,

public class namebean {
String name;
public namebean(String a) {
name = a;
}
}

We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");

Here we use the < constructor-arg > element to set the property by constructor injection as
< bean id="bean1" class="namebean" >
< constructor-arg >
< value > My Bean Value < / value >
< / constructor-arg >
< / bean >


4. What is spring? What are the various parts of spring framework? What are the different persistence frameworks which could be used with spring?


Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows:

The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.

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

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

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

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

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

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

5. What is AOP? How does it relate with IOC? What are different tools to utilize AOP?


Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behaviour that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviours affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn't need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at the byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features. In general any AOP framework control aspects in three possible ways:

Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific context at those points
Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message before executing a joinpoint

6. What are the advantages of spring framework?

Spring has layered architecture. Use what you need and leave you don't need.
Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.
7. Can you name a tool which could provide the initial ant files and directory structure for a new spring project?


Appfuse or equinox.

8. Explain BeanFactory in spring.

Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.XmlBeanFactory" It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory.
BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));

This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection.

myBean bean1 = (myBean)factory.getBean("myBean");

9. Explain the role of ApplicationContext in spring.


While Bean Factory is used for simple applications; the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide

1) A means for resolving text messages, including support for internationalization.
2) A generic way to load file resources.
3) Events to beans that are registered as listeners.

Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are

1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code

ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");

3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

10. How does Spring supports DAO in hibernate?

Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free.
Example:

public class UserDAOHibernate extends HibernateDaoSupport {

public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
}
public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);
if (log.isDebugEnabled()) {
log.debug(“userId set to: “ + user.getID());
}
}
public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id);
getHibernateTemplate().delete(user);
}

}


11. What are the id generator classes in hibernate?

increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.
seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.
guid: It uses a database-generated GUID string on MS SQL Server and MySQL.
native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified.
select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.
foreign: uses the identifier of another associated object. Usually used in conjunction with a primary key association.

12. How is a typical spring implementation look like?

For a typical Spring Application we need the following files

1. An interface that defines the functions.
2. An Implementation that contains properties, its setter and getter methods, functions etc.,
3. A XML file called Spring configuration file.
4. Client program that uses the function.


13. How do you define hibernate mapping file in spring?

Add the hibernate mapping file entry in mapping resource inside Spring’s applicationContext.xml file in the web/WEB-INF directory.

< property name="mappingResources" >
< list >
< value > org/appfuse/model/User.hbm.xml < / value >
< / list >
< / property >


14. How do you configure spring in a web application?

It is very easy to configure any J2EE-based web application to use Spring. At the very least, you can simply add Spring’s ContextLoaderListener to your web.xml file:

< listener >
< listener-class > org.springframework.web.context.ContextLoaderListener < / listener-class >
< / listener >


15. Can you have xyz.xml file instead of applicationcontext.xml?

ContextLoaderListener is a ServletContextListener that initializes when your webapp starts up. By default, it looks for Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a element named “contextConfigLocation.” Example:

< listener >
< listener-class > org.springframework.web.context.ContextLoaderListener

< context-param >
< param-name > contextConfigLocation < / param-name >
< param-value > /WEB-INF/xyz.xml< / param-value >
< / context-param >

< / listener-class >
< / listener >



16. How do you configure your database driver in spring?

Using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". Example:

< bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
< property name="driverClassName" >
< value > org.hsqldb.jdbcDriver < / value >
< / property >
< property name="url" >
< value > jdbc:hsqldb:db/appfuse < / value >
< / property >
< property name="username" > < value > sa < / value > < / property >
< property name="password" > < value > < / value > < / property >
< / bean >


17. How can you configure JNDI instead of datasource in spring applicationcontext.xml?

Using "org.springframework.jndi.JndiObjectFactoryBean". Example:

< bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" >
< property name="jndiName" >
< value > java:comp/env/jdbc/appfuse < / value >
< / property >
< / bean >

18. What are the key benefits of Hibernate?

These are the key benifits of Hibernate:
Transparent persistence based on POJOs without byte code processing
Powerful object-oriented hibernate query language
Descriptive O/R Mapping through mapping file.
Automatic primary key generation
Hibernate cache: Session Level, Query and Second level cache.
Performance: Lazy initialization, Outer join fetching, Batch fetching

19. What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file?

Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

// Initialize the Hibernate environment
Configuration cfg = new Configuration().configure();
// Create the session factory
SessionFactory factory = cfg.buildSessionFactory();
// Obtain the new session object
Session session = factory.openSession();

The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance. An instance of SessionFactory is typically created once and used to create all sessions related to a given context.
The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session

A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session:
Session session = null;
UserInfo user = null;
Transaction tx = null;
try {
session = factory.openSession();
tx = session.beginTransaction();
user = (UserInfo)session.load(UserInfo.class, id);
tx.commit();
} catch(Exception e) {
if (tx != null) {
try {
tx.rollback();
} catch (HibernateException e1) {
throw new DAOException(e1.toString()); }
} throw new DAOException(e.toString());
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) { }
}
}

20. What is the difference between hibernate get and load methods?

The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial:
The following Hibernate code snippet retrieves a User object from the database:
User user = (User) session.get(User.class, userID);

The get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached.
Hibernate also provides a load() method:
User user = (User) session.load(User.class, userID);

If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns
null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method. On the other hand, get() never returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed.

21. What type of transaction management is supported in hibernate?

Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions.

Non-managed in web containers:

< bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager" >
< property name="sessionFactory" >
< ref local="sessionFactory" / >
< / property >
< / bean >

Managed in application server using JTA:

< bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager." >
< property name="sessionFactory" >
< ref local="sessionFactory" / >
< / property >
< / bean >


22. What is lazy loading and how do you achieve that in hibernate?


Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actually called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.

23. What are the different fetching strategies in Hibernate?

Hibernate3 defines the following fetching strategies:

Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.

24. What are different types of cache hibernate supports?

Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly 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, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:

EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory and disk-based caching. However, it does not support clustering.
OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Commercial Tangosol Coherence cache.
25. What are the different caching strategies?

The following four caching strategies are available:
Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
Transactional: This is a fully transactional cache that may be used only in a JTA environment.
26. How do you configure 2nd level cache in hibernate?

To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows:
< hibernate-configuration >
< session-factory >
< property name="hibernate.cache.provider_class" >org.hibernate.cache.EHCacheProvider< / property >
< / session-factory >
< / hibernate-configuration >

By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.

27. What is the difference between sorted and ordered collection in hibernate?

A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.

28. What are the types of inheritance models and describe how they work like vertical inheritance and horizontal?

There are three types of inheritance mapping in hibernate:

Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class.
1. Table per concrete class with unions: In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker


If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.

Happy Learning!

Thursday, February 9, 2012

J2EE Design Patterns - Interview Questions

J2EE Design Patterns - Interview Questions The following are some questions that you might encounter when you face an Interview for a position of a Senior Java/J2EE Developer. Design Patterns are very exciting and useful and most managers expect their developers to have a sound understanding of the most important patterns. 

Questions


What are design patterns?

A pattern is a proven (and recurring) solution to a problem in a context. Each pattern describes a problem which occurs time and again in our environment, and describes its solution to this problem in such a way that we can use this solution any number of times. In simple words, there are a lot of common problems which a lot of developers have faced over time. These common problems ideally should have a common solution too. It is this solution when documented and used over and over becomes a design pattern.

Can we always apply the same solution to different problems at hand?

No. Design patterns would study the different problems at hand. To these problems then it would suggest different design patterns to be used. However, the type of code to be written in that design pattern is solely the discretion of the Project Manager who is handling that project.

What should be the level of detail/abstraction which should be provided by a design pattern?

Design patterns should present a higher abstraction level though it might include details of the solution. However, these details are lower abstractions and are called strategies. There may be more than one way to apply these strategies in implementing the patterns. The details of implementation are usually upto the developer who is coding at the ground level. 

What are the most common problems which one faces during the application design phase that are solved by design patterns?

Some are:

1. Identifying components, internal structures of the components, and relationships between components. 
2. Determining component granularity and appropriate interactions 
3. Defining component interfaces. 

How does one decide which Design pattern to use in our application?

We need to follow these steps:

1. We need to understand the problem at hand. Break it down to finer grained problems. Each design pattern is meant to solve certain kinds of problems. This would narrow down our search for design patterns. 
2. Read the problem statement again along with the solution which the design pattern will provide. This may instigate to change a few patterns that we are to use. 
3. Now figure out the interrelations between different patterns. Also decide what all patterns will remain stable in the application and what all need to change (with respect to Change Requests received from the clients). 


What is Refactoring?

Learning different design patterns is not sufficient to becoming a good designer.We have to understand these patterns and use them where they have more benefits. Using too many patterns (more than required) would be over-engineering and using less design patterns than required would be under-engineering. In both these scenarios we use refactoring. Refactoring is a change made to the internal structure of the software to make it easier to understand and cheaper to modify, without changing its observable behaviour.

What are Antipatterns?

Though the use of patterns fulfils our objectives in the applications; there are also several instances where several applications did not fulfill their goals. The architects of these applications too need to document these wrong decisions.This helps others by preventing them from repeating these mistakes in their applications. Such documented mistakes are called antipatterns. 

As we do development in tiers, how do we divide patterns in tiers?

The Sun Java Center has classified the patterns in three tiers. These are:

Presentation tier patterns for web-component tier, 
Business tier patterns for business logic (EJB) tier, and 
Integration tier patterns for connection to the databases. 

What are the Presentation Tier Patterns? 

The presentation tier patterns are: 

Intercepting filter, Front Controller, View Helper, Composite View, Service-to-Worker, and Dispatcher View.

What are the Business Tier Patterns? 

The business tier patterns are:

Business delegate, Value Object, Session Façade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.

What are the Integration Tier Patterns? 

Integration tier patterns are:

Data Access Object (DAO) and Service Activator

What is Intercepting Filter pattern?

Provides a solution for pre-processing and post-processing a request. It allows us to declaratively apply filters for intercepting requests and responses. For ex. Servlet filters.

What is Front Controller pattern?

It manages and handles requests through a centralized code. This could either be through a servlet or a JSP (through a Java Bean). This Controller takes over the common processing which happens on the presentation tier. The front controller manages content retrieval, security, view management and retrieval.

What is View Helper pattern?

There generally are two parts to any application – the presentation and the business logics. The “View” is responsible for the output-view formatting whereas “Helper” component is responsible for the business logic. Helper components do content retrieval, validation and adaptation. Helper components generally use Business delegate pattern to access business classes.

What is Composite View pattern?

This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components which makes the presentation flexible by allowing personalization and customization.

What is Service to Worker pattern?

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. This differentiation is done for maintainability.

What is Dispatcher View pattern?

This is similar to Service to Worker pattern except that it is used for smaller applications. In this one class is used for both request and view processing.

What is Business Delegate pattern?

This pattern is used to reduce the coupling between the presentation and business-logic tier. It provides a proxy to the façade from where one could call the business classes or DAO class. This pattern can be used with Service Locator pattern for improving performance.

What is Value Object pattern?

Value Object is a serializable object which would contain lot of atomic values.These are normal java classes which may have different constructors (to fill in the value of different data) and getter methods to get access to these data. VOs are used as a course grained call which gets lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be transferred between different tiers within a single remote method invocation

What is Session Façade pattern?

This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead. This pattern fits well with declarative transactions and security management. 

What is Value Object Assembler pattern?

This pattern allows for composing a Value Object from different sources which could be EJBs, DAOs or Java objects. 

What is Value List Handler pattern?

This pattern provides a sound solution for query execution and results processing. 

What is Service Locator pattern?

It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance. 

What is Data Access Object pattern?

It provides a flexible and transparent access to the data, abstracts the data sources and hides the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer. 

What is EJB Command pattern?

Session Façade and EJB Command patterns are competitor patterns. It wraps business logic in command beans, decouples the client and business logic tier, and reduces the number of remote method invocations. 

What is Version Number pattern?

This pattern is used for transaction and persistence and provides a solution for maintaining consistency and protects against concurrency. Every time a data is fetched from the database, it comes out with a version number which is saved in the database. Once any update is requested on the same row of the database, this version is checked. If the version is same, the update is allowed else not.

What all patterns are used to improve performance and scalability of the application?

Value Object, Session Façade, Business Delegate and Service Locator.

What design patterns could be used to manage security?

Single Access Point, Check point and Role patterns


* * *

If you have any more questions on J2EE concepts that you have faced during your interviews and wish to add them to this collection - Please drop a note to me and I shall be glad to add them to this list.



J2EE Interview Questions

The following are some questions you might encounter with respect to the J2EE Technology in any Interview for a Java J2EE Developer. The questions below are pretty exhaustive and practically speaking, you might not be asked most of the questions because - interviewers might prefer to test out your knowledge of core J2EE technologies like Servlets, JSPs, Struts, Hibernate etc. Nonetheless, there is nothing wrong in being prepared and the questions below would help you prepare for your J2EE Interview.

Questions:

1. What is J2EE?

J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitier, web-based applications.

2. What is the J2EE module?

A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.

3. What are the components of J2EE application?

A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
* Application clients and applets are client components.
* Java Servlet and JavaServer Pages (JSP) technology components are web components.
* Enterprise JavaBeans (EJB) components are business components.
* Resource adapter components provided by EIS and tool vendors.

4. What does application client module contain?

The application client module contains:
*class files
*an application client deployment descriptor.

Application client modules are packaged as JAR files with a .jar extension.

5. What does web module contain?

The web module contains:
*JSP files,
*class files for servlets,
*GIF and HTML files, and
*a Web deployment descriptor.

Web modules are packaged as JAR files with a .war (Web ARchive) extension.

6. What are the differences between Ear, Jar and War files? Under what circumstances should we use each one?

There are no structural differences between the files; they are all archived using zip-jar compression. However, they are intended for different purposes.

*Jar files are intended to hold generic libraries of Java classes, resources, auxiliary files, etc.
*War files are intended to contain complete Web applications.
*Ear files are intended to contain complete enterprise applications.

Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc.

7. What is an applet?

A J2EE component that typically executes in a Web browser but can execute in a variety of other applications or devices that support the applet programming model.

8. What is applet container?

A container that includes support for the applet programming model.

9. What is application assembler?

A person who combines J2EE components and modules into deployable application units

10. What is application client?

A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs.

11. What is application client container?

A container that supports application client components.

12. What is application client module?

A software unit that consists of one or more classes and an application client deployment descriptor.

13. What is application component provider?

A vendor that provides the Java classes that implement components' methods, JSP page definitions, and any required deployment descriptors.

14. What is application configuration resource file?

An XML file used to configure resources for a Java Server Faces application, to define navigation rules for the application, and to register converters, Validator, listeners, renders, and components with the application.

15. What is build file?

The XML file that contains one or more ant targets. A target is a set of tasks you want to be executed. When starting asant, you can select which targets you want to have executed. When no target is given, the project's default target is executed.

ant - is a tool that is used to build web applications

16. What is deployment?

The process whereby software is installed into an operational environment. For ex: deploying an EAR file into a Weblogic Server.

17. What is deployment descriptor?

An XML file provided with each module and J2EE application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.

18. What is HTML?

Hypertext Markup Language. A markup language for hypertext documents on the Internet. HTML enables the embedding of images, sounds, video streams, form fields, references to other objects with URLs, and basic text formatting.

19. What is HTTP?

Hypertext Transfer Protocol. The Internet protocol used to retrieve hypertext objects from remote hosts. HTTP messages consist of requests from client to server and responses from server to client.

20. What is HTTPS?

HTTP layered over the SSL protocol. It is the secure version of the HTTP protocol

21. What is Java 2 Platform, Micro Edition (J2ME)?

A highly optimized Java runtime environment targeting a wide range of consumer products, including pagers, cellular phones, screen phones, digital set-top boxes, and car navigation systems.

22. What is JDBC?

An JDBC for database-independent connectivity between the J2EE platform and a wide range of data sources.

23. What is JNDI?

Abbreviate of Java Naming and Directory Interface. It is used as part of JDBC

24. What is query string?

A component of an HTTP request URL that contains a set of parameters and values that affect the handling of the request

25. What is resource adapter?

A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter typically is specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs in to a container. The application components deployed on the container then use the client API (exposed by the adapter) or tool-generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.

26. What is Secure Socket Layer (SSL)?

A technology that allows Web browsers and Web servers to communicate over a secured connection.

27. What is URI?

Uniform resource identifier. A globally unique identifier for an abstract or physical resource. A URL is a kind of URI that specifies the retrieval protocol (http or https for Web applications) and physical location of a resource (host name and host-relative path). A URN is another type of URI.

28. What is URL?

Uniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the World Wide Web. A URL looks like this:
protocol://host/local info

where protocol specifies a protocol for fetching the object (such as http or ftp), host specifies the Internet name of the targeted host, and local info is a string (often a file name) passed to the protocol handler on the remote host.

29. What is URL path?

The part of a URL passed by an HTTP request to invoke a servlet. A URL path consists of the context path + servlet path + path info, where Context path is the path prefix associated with a servlet context of which the servlet is a part. If this context is the default context rooted at the base of the Web server's URL namespace, the path prefix will be an empty string. Otherwise, the path prefix starts with a / character but does not end with a / character. Servlet path is the path section that directly corresponds to the mapping that activated this request. This path starts with a / character. Path info is the part of the request path that is not part of the context path or the servlet path

30. What is URN?

Uniform resource name. A unique identifier that identifies an entity but doesn't tell where it is located. A system can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Web location to change, while still allowing the entity to be found.

* * *


If you have any more questions on J2EE concepts that you have faced during your interviews and wish to add them to this collection - Please drop a note to me and I shall be glad to add them to this list.

Wednesday, January 25, 2012

Core Java Interview Questions - Exception Handling

The following are some questions you might encounter with respect to Java Exception Handling in any Interview. Exception Handling is an important part of any Java Application because, this determines how gracefully you capture and handle unexpected situations. 

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Exception Handling that you might find useful. You can use them to revise/review your understanding of Exception Handling. 

They are: 

Exception Handling 
Common Exceptions & Errors 


Questions: 


1. How could Java classes direct messages to a file instead of the Console? 

The System class has a variable "out" that represents the standard output, and the variable "err" that represents the standard error device. By default, they both point at the system console. 

The standard output could be re-directed to a file as follows: 

Stream st = new Stream(new FileOutputStream("output.txt")); 
System.setErr(st); 
System.setOut(st); 

2. Does it matter in what order catch statements for FileNotFoundException and IOException are written? 

Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last. 

3. What is user-defined exception in java ? 

User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inheriting the Exception class. Using this class we can create & throw new exceptions. 

4. What is the difference between checked and Unchecked Exceptions in Java ? 

Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions. 

5. What is the catch or declare rule for method declarations? 

If a checked exception may be thrown within the body of a method, the method must either catch that exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions that are not handled by any method. 

6. What is the purpose of the finally clause of a try-catch-finally statement? 

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. It is usually used in places where we are connecting to a database so that, we can close the connection or perform any cleanup even if the query execution in the try block caused an exception. 

7. What classes of exceptions may be caught by a catch clause? 

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. 

8. Can an exception be rethrown? 

Yes, an exception can be rethrown any number of times. 

9. When is the finally clause of a try-catch-finally statement executed? 

The finally clause of the try-catch-finally statement is always executed after the catch block is executed, unless the thread of execution terminates or an exception occurs within the execution of the finally clause. 

10. What classes of exceptions may be thrown by a throw statement? 

A throw statement may throw any expression that may be assigned to the Throwable type. 

11. What happens if an exception is not caught? 

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. 


12. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination. 

13. Can try statements be nested? 

Try statements can be tested. It is possible to nest them to any level, but it is preferable to keep the nesting to 2 or 3 levels at max. 


14. How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception that was thrown, is executed. The remaining catch clauses are ignored. 

15. What is difference between error and exception 

Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters, that can be recovered such as FileNotFound exception or IO exceptions 

16. What is the base class from which all exceptions are subclasses 

All exceptions are subclasses of a class called java.lang.Throwable 

17. How do you intercept and control exceptions 

We can intercept and control exceptions by using try/catch/finally blocks. 

You place the normal processing code in try block 
You put the code to deal with exceptions that might arise in try block in catch block 
Code that must be executed no matter what happens must be place in finally block 

18. When do we say an exception is handled 

When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled. Or when an exception thrown by a method is caught by the calling method and handled, an exception can be considered handled. 

19. When do we say an exception is not handled 

There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed 

20. In what sequence does the finally block gets executed 

If you put finally after a try block without a matching catch block then it will be executed after the try block 
If it is placed after the catch block and there is no exception then also it will be executed after the try block 
If there is an exception and it is handled by the catch block then it will be executed after the catch block 

21. What can prevent the execution of the code in finally block 

Theoretically, the finally block will execute no matter what. But practically, the following scenarios can prevent the execution of the finally block. 

* The death of thread 
* Use of system.exit() 
* Turning off the power to CPU 
* An exception arising in the finally block itself 


22. What are the rules for catching multiple exceptions? 

A more specific catch block must precede a more general one in the source, else it gives compilation error about unreachable code blocks. 


23. What does throws statement declaration in a method indicate? 

This indicates that the method throws some exception and the caller method should take care of handling it. If a method invokes another method that throws some exception, the compiler will complain until the method itself throws it or surrounds the method invocation with a try-catch block. 

24. What are checked exceptions? 

Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems. Checked Exceptions can be caught and handled by the programmer to avoid random error messages on screen. 

25. What are runtime exceptions 

Runtime exceptions are due to programming bugs like out of bound arrays or null pointer exceptions. 

26. What is difference between Exception and errors 

Errors are situations that cannot be recovered and the system will just crash or end. Whereas, Exceptions are just unexpected situations that can be handled and the system can recover from it. We usually catch & handle exceptions while we dont handle Errors. 

27. How will you handle the checked exceptions 

You can provide a try/catch block to handle it or throw the exception from the method and have the calling method handle it. 

28. When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method? 

No it cannot throw, except for the subclasses of the exceptions thrown by the parent class's method. 

29. Is it legal for the extending class which overrides a method which throws an exception, not to throw in the overridden class? 

Yes, it is perfectly legal.

If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.

Happy Learning!



Friday, January 20, 2012

Java Database Connectivity JDBC Interview Questions

Well, here we go. The following are some questions that you may encounter on JDBC concepts during your interviews. Remember that if you are a junior level developer (with less than 3 years working experience) many of these questions may seem too complicated for you and frankly you won’t be expected to know them either. 

You cannot think of an Enterprise Java Application that does not connect to a database. So, a strong understanding of JDBC concepts is crucial to your success as a potential candidate during an interview. 

Questions – Part 1: 

1. What is the JDBC? 

Java Database Connectivity (JDBC) is a standard Java API that is used to interact with relational databases from within a Java application. JDBC has set of classes and interfaces which can use from our Java application and interact with the database.

2. What are the Basic Steps in writing a Java program to connect to a database using JDBC? 

The basic steps in connecting to a database using JDBC are: 

1. Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded). 
2. Open the connection to database which is then used to send SQL statements and get results back. 
3. Create JDBC Statement object. This object contains SQL query. 
4. Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query. 
5. Process the result set. 
6. Close the connection. 

3. What are the main components of JDBC ? 

The five main components of JDBC are:

1. Driver Manager
2. Driver
3. Connection
4. Statement &
5. ResultSet 

4. How does a JDBC application work? 

A JDBC application can be logically divided into two layers: 
1. Driver layer 
2. Application layer 

First the Driver layer consists of DriverManager class and the available JDBC drivers. The application begins with requesting the DriverManager for the connection. An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer. The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results. 


5. How do I load a database driver with JDBC 4.0 / Java 6? 

Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.

Remember - if the correct JAR Files are missing in the classpath, this auto feature will not work 

6. What is JDBC Driver interface? 

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver so that the Java classes that connect to the database can use them. 

7. What does the connection object represents? 

The connection object represents a literal connection or a communication context through which our Java code can interact with a database. i.e., all communication with database is through connection object only.

8. What is a Statement? 

The Statement acts like a vehicle through which SQL commands can be sent. You can create a Statement as follows: 

Statement stmt = conn.createStatement();


This method returns an object which implements statement interface which can be executed. 

9. What is a PreparedStatement? 

A prepared statement is an SQL statement that is precompiled by the database. It is a sub-set of the Statement. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters. 

You can create a prepared statement as follows: 

PreparedStatement pstmt = conn.prepareStatement("UPDATE Emp_Salary SET Salary = ? WHERE Emp_Id = ?");
pstmt.setBigDecimal(1, 75000.00);
pstmt.setInt(2, 12345);


Note that conn is an instance of the collection class and the "?" represent the parameters that are to be passed to the query/prepared statement before it can be executed. 


10. What are callable statements? 

Callable statements are used from JDBC application to invoke stored procedures and functions objects of a database.

11. Can you call a stored procedure using JDBC? If so, how? 

Yes, you can call Stored Procedures using JDBC. we have to use the CallableStatement to do so. 

Example:


CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");


Here conn is an instance of the Connection class.

12. How many types of JDBC drivers are there and What are they? 

There are four types of drivers defined by JDBC as follows: 
1. Type 1 – JDBC-ODBC Bridge 
2. Type 2 – Native API (Partly Java) Driver
3. Type 3 – Net-Protocol Fully Java Driver
4. Type 4 – Pure Java Driver

Type 4 JDBC driver is most preferred kind of approach in JDBC.

13. Which type of JDBC driver is the fastest one? 

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database. 

14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? 

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

15. What are the standard transaction isolation levels defined by JDBC? 

The values are defined in the class java.sql.Connection and are: 

TRANSACTION_NONE 
TRANSACTION_READ_COMMITTED 
TRANSACTION_READ_UNCOMMITTED 
TRANSACTION_REPEATABLE_READ 
TRANSACTION_SERIALIZABLE 

You need to double check that the database you are connecting to, supports these isolation levelts. 

16. What is a ResultSet? 

The ResultSet represents set of rows retrieved due to query execution. You get a result set object as the output when you execute a query using the Statement or the PreparedStatement objects. 
Example:

ResultSet rs = stmt.executeQuery(sqlQuery);


17. What are the types of resultsets? 

JDBC supports 3 types of ResultSets. They are: 

1. TYPE_FORWARD_ONLY 
2. TYPE_SCROLL_INSENSITIVE and
3. TYPE_SCROLL_SENSITIVE 

18. What are the types of statements in JDBC?

The JDBC API has 3 types of Statement Interfaces. They are:

1. Statement
2. PreparedStatement
3. CallableStatement

19. What are the differences/key features between the 3 different types of Statements in JDBC? 

Statement 
* This interface is used for executing a static SQL statement and returning the results it produces. 
* The object of Statement class can be created using Connection.createStatement() method. 

PreparedStatement 
* A SQL statement is pre-compiled and stored in a PreparedStatement object.
* This object can then be used to efficiently execute this statement multiple times.
* The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface. 

CallableStatement 
* This interface is used to execute SQL stored procedures.
* This extends PreparedStatement interface.
* The object of CallableStatement class can be created using Connection.prepareCall() method.

20. What is Connection pooling? What are the advantages of using a connection pool?

Connection Pooling is a technique used for sharing the server resources among requested clients. It was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provides access to a database. Getting connection and disconnecting are costly operation, which affects the application performance, so we should avoid creating multiple connection during multiple database interactions. A pool contains set of Database connections which are already connected, and any client who wants to use it can take it from pool and when done with using it can be returned back to the pool. Apart from performance this also saves you resources as there may be limited database connections available for your application. 

21. What does the Class.forName() method do? 

Method forName() is a static method of java.lang.Class. This can be used to dynamically load a class at run-time. Class.forName() loads the class if its not already loaded. It also executes the static block of loaded class. Then this method returns an instance of the loaded class. So a call to Class.forName('MyClass') is going to do following 
- Load the class MyClass.
- Execute any static block code of MyClass.
- Return an instance of MyClass.

JDBC Driver loading using Class.forName is a good example of best use of this method. The driver loading is done like this 

Class.forName("org.mysql.Driver"); 

All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static initializer method registerDriver() which can be called in a static blocks of Driver class. A MySQL JDBC Driver has a static initializer which looks like this: 

static { 
try { 
java.sql.DriverManager.registerDriver(new Driver()); 
} catch (SQLException E) { 
throw new RuntimeException("Can't register driver!"); 

Class.forName() loads driver class and executes the static block and the Driver registers itself with the DriverManager. 

22. When to use a PreparedStatement and when to use a Statement?

Statement is a object used for executing a static SQL statement and returning the results it produces. PreparedStatement is a SQL statement which is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. 

There are few advantages of using PreparedStatements over Statements 
* Since its pre-compiled, Executing the same query multiple times in loop, binding different parameter values each time is faster. 
* In PreparedStatement the setDate()/setString() methods can be used to escape dates and strings properly, in a database-independent way.
* SQL injection attacks on a system are virtually impossible while using PreparedStatements.

23. What do you mean by the term pre-compiled from a PreparedStatemnet perspective? 

The prepared statement(pre-compiled) concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution which makes it much faster than executing a fresh query that has to be compiled before execution. 

24. What does setAutoCommit(false) do?

A JDBC connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit mode manually as follows: 

con.setAutoCommit(false); 


Once auto-commit mode is disabled, no SQL statements will be committed until you explicitly call the commit method as follows:


con.commit(); 


Alternately, if you want to ensure that all further transactions/queries are auto-committed then you can enable auto-commit as follows:

con.setAutoCommit(true); 


25. What are database warnings and How can I get them?

Warnings are issued by database to notify user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. In JDBC SQLWarning is an exception that provides information on database access warnings. Warnings are silently chained to the object whose method caused it to be reported. Warnings may be retrieved from Connection, Statement, and ResultSet objects. 

The call to the getWarnings() method of either of these objects retrieves the first warning reported by calls on this object. If there is more than one warning, subsequent warnings will be chained to the first one and can be retrieved by calling the method SQLWarning.getNextWarning on the warning that was retrieved previously. 


Questions – Part 2: 

1. How will you retreive database warnings from a Connection object in JDBC? 


//Retrieving warning from connection object 
SQLWarning warning = conn.getWarnings(); 

//Retrieving next warning from warning object itself 
SQLWarning nextWarning = warning.getNextWarning(); 


2. How will you retreive database warnings from a Statement object in JDBC? 


//Retrieving warning from statement object 
stmt.getWarnings(); 

//Retrieving next warning from warning object itself 
SQLWarning nextWarning = warning.getNextWarning(); 



3. How will you retreive database warnings from a ResultSet object in JDBC? 

//Retrieving warning from resultset object 
rs.getWarnings(); 

//Retrieving next warning from warning object itself 
SQLWarning nextWarning = warning.getNextWarning(); 


4. What does the clearWarnings() method do? 

A call to clearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object. 

5. What happens when I try to call the getWarning() method on a connection/statement/resultset after it has been closed? 

Trying to call the getWarning() method on either of these 3 objects after they are closed will cause an SQLException to be thrown. 

6. Let us say that I just closed my Statement object so, I cannot access the getWarning() on my statement. Can I still access the getWarning() on my ResultSet? 

No. Closing a Statement automatically closes the ResultSet connected to it. So, you will get the same SQLException if you try to do so. 

7. What is DatabaseMetaData? 

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC technology ("JDBC driver") that is used with it. Use DatabaseMetaData to find information about your database, such as its capabilities and structure.

8. How will you use the DatabaseMetaData? Can you write a sample example code? 


DatabaseMetaData md = conn.getMetaData(); 
System.out.println("Database Name: " + md.getDatabaseProductName()); 
System.out.println("Database Version: " + md.getDatabaseProductVersion()); 
System.out.println("Driver Name: " + md.getDriverName()); 
System.out.println("Driver Version: " + md.getDriverVersion()); 


9. What is ResultSetMetaData? 

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns. 

10. How will you use the ResultSetMetaData? Can you write a sample example code? 


ResultSet rs = stmt.executeQuery("SELECT * FROM TABLE_NAME"); 
ResultSetMetaData rsmd = rs.getMetaData(); 
int numberOfColumns = rsmd.getColumnCount(); 
boolean b = rsmd.isSearchable(1); 



11. What is rowset? 

A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. 

12. Why do we need a RowSet?

RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset's command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet

13. What are the advantages of using RowSet over ResultSet?

There are two clear advantages of using RowSet over ResultSet: 

* RowSet makes it possible to use the ResultSet object as a JavaBeans component. 
* RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.

14. What are the different types of RowSet ? 
There are two types of RowSet are there. They are: 
* Connected - A connected RowSet object connects to the database once and remains connected until the application terminates. 
* Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

15. Can you give an example of Connected RowSet? 

A JdbcRowSet object is a example of connected RowSet, which means it continually maintains its connection to a database using a JDBC technology-enabled driver. 

16. Can you give an example of Disconnected RowSet?

A CachedRowSet object is a example of disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA). 

17. What are the benefits of having JdbcRowSet implementation? 

The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet 
* This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. 
* It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object. 

18. What is the need of BatchUpdates feature in JDBC? 

The BatchUpdates feature allows us to group SQL statements together and send to database server in one single shot instead of multiple calls.

19. What is a DataSource? 

A DataSource object is the representation of a source of data in the Java programming language. 

In basic terms: 
* A DataSource is a facility for storing data. 
* DataSource can be referenced by JNDI. 
* Data Source may point to RDBMS, file System , any DBMS etc..

Typically in enterprise application perspective, the term DataSource can be used interchangeably with a RDBMS database because in almost all cases, our DataSource will be pointing to an RDBMS database. 

20. What are the advantages of DataSource? 

The few advantages of using data source are : 
* An application does not need to hardcode driver information, as it does with the DriverManager. 
* The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details. 
* The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions. 

21. What is the difference between a Statement and a PreparedStatement? 

Some of the main differences between a statement & PreparedStatement are: 

A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database. A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.
Statement has to verify its metadata against the database every time. A prepared statement has to verify its metadata against the database only once.
If you want to execute the SQL statement once go for STATEMENT If you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries.


22. What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE in ResultSets? 

An insensitive resultset is like the snapshot of the data in the database when query was executed. A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive. After we obtain the resultset if the data is modified then such modifications are visible through resultset.
Performance not effected with insensitive. Since a trip is made for every ‘get’ operation, the performance drastically get affected.


If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.

Happy Learning!