Java Question Bank(2)
Java Question Bank(2)
ans The question mark (?) is known as the wildcard in generic programming. It
represents an unknown type. The wildcard can be used in a variety of situations such
as the type of a parameter, field, or local variable; sometimes as a return type. Unlike
arrays, different instantiations of a generic type are not compatible with each other,
not even explicitly. This incompatibility may be softened by the wildcard if ? is used
as an actual type parameter.
ans Generics means parameterized types. The idea is to allow type (Integer, String, …
etc., and user-defined types) to be a parameter to methods, classes, and interfaces.
Using Generics, it is possible to create classes that work with different data types. An
entity such as class, interface, or method that operates on a parameterized type is a
generic entity.
Why generics?
The Object is the superclass of all other classes, and Object reference can refer to
any object. These features lack type safety. Generics add that type of safety feature.
Generics in Java are similar to templates in C++. For example, classes like HashSet,
ArrayList, HashMap, etc., use generics very well. There are some fundamental
differences between the two approaches to generic types.
Types of java generic
1. Generic methods
Generic Java method takes a parameter and returns some value after
performing a task. It is exactly like a normal function, however, a generic
method has type parameters that are cited by actual type. This allows the
generic method to be used in a more general way. The compiler takes care of
the type of safety which enables programmers to code easily since they do
not have to perform long, individual type castings.
2. Generic classes
A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than
one type of parameter, separated by a comma. The classes, which accept one
or more parameters, are known as parameterized classes or parameterized
types.
3. Generic functions
We can also write generic functions that can be called with different types of
arguments based on the type of arguments passed to the generic method. The
compiler handles each method.
Generic only works with reference type
When we declare an instance of a generic type, the type argument passed to the type
parameter must be a reference type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20);
The above line results in a compile-time error that can be resolved using type
wrappers to encapsulate a primitive type.
But primitive type arrays can be passed to the type parameter because arrays are
reference types.
ArrayList<int[]> a = new ArrayList<>();
Advantages of generic
1. Code Reuse: We can write a method/class/interface once and use it for any type
we want.
2. Type Safety: Generics make errors to appear compile time than at run time (It’s
always better to know problems in your code at compile time rather than making
your code fail at run time). Suppose you want to create an ArrayList that store name
of students, and if by mistake the programmer adds an integer object instead of a
string, the compiler allows it. But, when we retrieve this data from ArrayList, it
causes problems at runtime.
3. Individual Type Casting is not needed: If we do not use generics, then, in the
above example, every time we retrieve data from ArrayList, we have to typecast it.
Typecasting at every retrieval operation is a big headache. If we already know that
our list only holds string data, we need not typecast it every time.
4. Generics Promotes Code Reusability: With the help of generics in Java, we can
write code that will work with different types of data.For example,
public <T> void genericsMethod (T data) {...}
Here, we have created a generics method. This same method can be used to perform
operations on integer data, string data, and so on.
5. Implementing Generic Algorithms: By using generics, we can implement
algorithms that work on different types of objects, and at the same, they are type-safe
too.
Interface
It’s one of the collection components that can be abstract with a data type to
represent the collection. The framework’s root interface in java.util.Collection by
using this import the significant class of the framework, with some default methods
like add(), remove(), size() etc. Mainly it has below default interfaces like Map, Set
and Deque all come under the util package
Implementation classes
The Collection implementation classes are provided by the framework libraries. And
the Java programmes, which may utilise them to create many types of collections
based on this parent and root class of the collection package. It includes some types
like ArrayList, HashMap, TreeMap, LinkedList, Doubly-LinkedList etc.
Use of iterator
Generally, the ‘Iterator’ is one of the interfaces and it is the main part of the
collection framework for iterating the data using the loop conditions.
It is also used to navigate the collection for storing and retrieving the data element,
and delete the collection’s data elements if not required. It’s the public interface so it
calls and is imported from the util package and the programmer access its default
methods. Some of the methods like hasNext(),next(), remove() these are the three
different methods with different data types hasNext() will return only the boolean
condition, next() method returns only the object value and remove() return void this
method. It has some type like ListIterator for traverse the datas in both forward and
backward directions.
Use of comparator
The Instances of different classes can be compared using the Comparator Interface.
Generally, the class requires a natural ordering for its objects so it implements using
the Comparable Interface. If you want to design an externally configurable ordering
behaviour that overrides the default ordering behaviour, use Comparator. A
comparator interface is also used to sort the objects of a user-defined class. The
return value of the TreeSet interface which compares using the comparator set and is
used to sort the elements of the same set in a certain order is returned by this method.
If the set follows the default or natural ordering pattern, it will return a Null value.
ans The map interface is present in java.util package represents a mapping between a
key and a value. The Map interface is not a subtype of the Collection interface.
Therefore it behaves a bit differently from the rest of the collection types. A map
contains unique keys.
Maps are perfect to use for key-value association mapping such as dictionaries. The
maps are used to perform lookups by keys or when someone wants to retrieve and
update elements by keys. Some common scenarios are as follows:
● A map of error codes and their descriptions.
● A map of zip codes and cities.
● A map of managers and employees. Each manager (key) is associated
with a list of employees (value) he manages.
● A map of classes and students. Each class (key) is associated with a list of
students (value).
Since Map is an interface, objects cannot be created of the type map. We always
need a class that extends this map in order to create an object. And also, after the
introduction of Generics in Java 1.5, it is possible to restrict the type of object that
can be stored in the Map.
Map hm = new HashMap();
// Obj is the type of the object to be stored in Map
Characteristics of map interfaces
1. A Map cannot contain duplicate keys and each key can map to at most
one value. Some implementations allow null key and null values like the
HashMap and LinkedHashMap, but some do not like the TreeMap.
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders, while
HashMap does not.
3. There are two interfaces for implementing Map in java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and
LinkedHashMap.
Class in map interface
1. Hashmap
HashMap is a part of Java’s collection since Java 1.2. It provides the basic
implementation of the Map interface of Java. It stores the data in (Key, Value)
pairs. To access a value one must know its key. This class uses a technique
called Hashing. Hashing is a technique of converting a large String to a small
String that represents the same String. A shorter value helps in indexing and
faster searches.
2. Linkedhashmap
LinkedHashMap is just like HashMap with an additional feature of
maintaining an order of elements inserted into it. HashMap provided the
advantage of quick insertion, search, and deletion but it never maintained the
track and order of insertion which the LinkedHashMap provides where the
elements can be accessed in their insertion order.
3. Treemap
The TreeMap in Java is used to implement the Map interface and
NavigableMap along with the Abstract Class. The map is sorted according to
the natural ordering of its keys, or by a Comparator provided at map creation
time, depending on which constructor is used. This proves to be an efficient
way of sorting and storing the key-value pairs. The storing order maintained
by the treemap must be consistent with equals just like any other sorted map,
irrespective of the explicit comparators.
Since Map is an interface, it can be used only with a class that implements this
interface. Now, let’s see how to perform a few frequently used operations on a Map
using the widely used HashMap class. And also, after the introduction of Generics in
Java 1.5, it is possible to restrict the type of object that can be stored in the map.
Operation 1: Adding Elements
In order to add an element to the map, we can use the put() method. However, the
insertion order is not retained in the hashmap. Internally, for every element, a
separate hash is generated and the elements are indexed based on this hash to make it
more efficient.
Operation 2: Changing Element
After adding the elements if we wish to change the element, it can be done by again
adding the element with the put() method. Since the elements in the map are indexed
using the keys, the value of the key can be changed by simply inserting the updated
value for the key for which we wish to change.
Operation 3: Removing Elements
In order to remove an element from the Map, we can use the remove() method. This
method takes the key value and removes the mapping for a key from this map if it is
present in the map.
Operation 4: Iterating through the Map
There are multiple ways to iterate through the Map. The most famous way is to use a
for-each loop and get the keys. The value of the key is found by using the getValue()
method.
ans JSP architecture gives a high-level view of the working of JSP. JSP architecture is a
3 tier architecture. It has a Client, Web Server, and Database. The client is the web
browser or application on the user side. Web Server uses a JSP Engine i.e; a
container that processes JSP. For example, Apache Tomcat has a built-in JSP Engine.
JSP Engine intercepts the request for JSP and provides the runtime environment for
the understanding and processing of JSP files. It reads, parses, build Java Servlet,
Compiles and Executes Java code, and returns the HTML page to the client. The
webserver has access to the Database. The following diagram shows the architecture
of JSP.
Now let us discuss JSP which stands for Java Server Pages. It is a server-side
technology. It is used for creating web applications. It is used to create dynamic web
content. In this JSP tags are used to insert JAVA code into HTML pages. It is an
advanced version of Servlet Technology. It is a Web-based technology that helps us
to create dynamic and platform-independent web pages. In this, Java code can be
inserted in HTML/ XML pages or both. JSP is first converted into a servlet by JSP
container before processing the client’s request. JSP Processing is illustrated and
discussed in sequential steps prior to which a pictorial media is provided as a handful
pick to understand the JSP processing better which is as follows:
Step 1: The client navigates to a file ending with the .jsp extension and the browser
initiates an HTTP request to the webserver. For example, the user enters the login
details and submits the button. The browser requests a status.jsp page from the
webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file.
Otherwise, the request is forwarded to the JSP Engine. This is done by recognizing
the URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java
code). This is done by converting all the template text into println() statements and
JSP elements to Java code. This process is called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is
forwarded to the Servlet engine. This process is called compilation or request
processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web
Server. The output is an HTML file. The Servlet engine passes the output as an
HTTP response to the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.
ans Servlet are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the webserver, process the
request, produce the response, then send a response back to the webserver
HTTP is a “stateless” protocol, which means that each time a client requests a Web
page, the client establishes a new connection with the Web server, and the server
does not retain track of prior requests.
● The conversion of a user over a period of time is referred to as a session.
In general, it refers to a certain period of time.
● The recording of the object in session is known as tracking.
● Session tracking is the process of remembering and documenting
customer conversions over time. Session management is another name for
it.
● The term “stateful web application” refers to a web application that is
capable of remembering and recording client conversions over time.
<session-config>
<session-timeout>20</session-timeout>
</session-config>
The timeout is specified in minutes and overrides Tomcat’s default timeout of 30
minutes.
In a servlet, the getMaxInactiveInterval() function delivers the session’s timeout
period in seconds. GetMaxInactiveInterval() returns 900 if your session is set to 20
minutes in web.xml.
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
A. Cookies
Cookies are little pieces of data delivered by the web server in the response header
and kept by the browser. Each web client can be assigned a unique session ID by a
web server. Cookies are used to keep the session going. Cookies can be turned off by
the client.
B. Hidden Form Field
The information is inserted into the web pages via the hidden form field, which is
then transferred to the server. These fields are hidden from the user’s view.
C. URL Rewriting
With each request and return, append some more data via URL as request
parameters. URL rewriting is a better technique to keep session management and
browser operations in sync.
D. HttpSession
A user session is represented by the HttpSession object. A session is established
between an HTTP client and an HTTP server using the HttpSession interface. A user
session is a collection of data about a user that spans many HTTP requests.
ans A JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java
classes −
● It provides a default, no-argument constructor.
● It should be serializable and that which can implement the Serializable
interface.
● It may have a number of properties which can be read or written.
● It may have a number of "getter" and "setter" methods for the
properties.
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including the classes that you
define.
A JavaBean property may be read, write, read only, or write only. JavaBean
properties are accessed through two methods in the JavaBean's implementation class
−
1. getPropertyName()
For example, if property name is firstName, your method name would be
getFirstName() to read that property. This method is called accessor.
2. setPropertyName()
For example, if property name is firstName, your method name would be
setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only
attribute will have only a setPropertyName() method.
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean
becomes a scripting variable that can be accessed by both scripting elements and
other custom tags used in the JSP. The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application
based on your requirement. The value of the id attribute may be any value as a long
as it is a unique name among other useBean declarations in the same JSP.
ans
Autowiring feature of spring framework enables you to inject the object dependency
implicitly. It internally uses setter or constructor injection.
Autowiring can't be used to inject primitive and string values. It works with
reference only.
Advantage of Autowiring
It requires the less code because we don't need to write the code to inject the
dependency explicitly.
Disadvantage of Autowiring
No control of programmer.
In case of byName autowiring mode, bean id and reference name must be same.
In case of byType autowiring mode, bean id and reference name may be different.
But there must be only one bean of a type.
If you have 3 constructors in a class, zero-arg, one-arg and two-arg then injection
will be performed by calling the two-arg constructor.
no autowiring mode
ans The Spring Framework is an open-source framework for building enterprise Java
applications. Spring aims to simplify the complex and cumbersome enterprise Java
application development process by offering a framework that includes technologies
such as:
1. Aspect-oriented programming (AOP)
2. Dependency injection (DI)
3. Plain Old Java Object (POJO)
Even with all these technologies, Spring is a lightweight framework that can be used
to create scalable, secure, and robust enterprise web applications.
● Core (spring-core) is the core of the framework that power features such as
Inversion of Control and dependency injection.
● Beans (spring-beans) provides Beanfactory, which is a sophisticated
implementation of the factory pattern.
● Context (spring-context) builds on Core and Beans and provides a medium
to access defined objects. ApplicationContext interface is the core part of the
Context module, and the spring-context-support provides support for
third-party interactions such as caching, mailing, and template engines.
● SpEL (spring-expression) enables users to use the Spring Expression
Language to query and manipulate the object graph at runtime.
Data access/integration
This includes the modules that are used to handle data access and transaction
processing in an application.
Web
The Web layer relates to modules that power web-based functions in Spring.
Other Modules
● AOP (spring-aop) provides an aspect-oriented programming implementation
that can be used when creating applications.
● Aspects (spring-aspects) enables direct integration with the AspectJ
programming extension by the eclipse foundation.
● Instrumentation (spring-instrument) is the class instrumentation support
and class loader implementations for application servers.
● Messaging (spring-messaging) provides a robust platform to manage
messaging in applications.
● Test (spring-test) is the Spring test module that supports unit and integration
testing with JUnit and TestNG.
ans Dependency Injection (DI) is a design pattern that removes the dependency from the
programming code so that it can be easy to manage and test the application.
Dependency Injection makes our programming code loosely coupled. To understand
the DI better, Let's understand the Dependency Lookup (DL) first:
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand.
There can be various ways to get the resource for example:
● tight coupling The dependency lookup approach makes the code tightly
coupled. If resource is changed, we need to perform a lot of modification in
the code.
● Not easy for testing This approach creates a lot of problems while testing the
application especially in black box testing.
Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of the
programs. In such case we provide the information from the external source such as
XML file. It makes our code loosely coupled and easier for testing. In such case we
write the code as:
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
public void setAddress(Address address){
this.address=address;
}
}
In such case, instance of Address class is provided by external souce such as XML
file either by constructor or setter method.
● By Constructor
● By Setter method
We can inject the dependency by setter method also. The <property> subelement of
<bean> is used for setter injection. Here we are going to inject
ans The objects that form the backbone of your application and that are managed by the
Spring IoC container are called beans. A bean is an object that is instantiated,
assembled, and otherwise managed by a Spring IoC container. These beans are
created with the configuration metadata that you supply to the container. For
example, in the form of XML <bean/> definitions which you have already seen in
the previous chapters.
Bean definition contains the information called configuration metadata, which is
needed for the container to know the following −
● How to create a bean
● Bean's lifecycle details
● Bean's dependencies
All the above configuration metadata translates into a set of the following properties
that make up each bean definition.
1. Class - This attribute is mandatory and specifies the bean class to be used to
create the bean.
2. Name - This attribute specifies the bean identifier uniquely. In XMLbased
configuration metadata, you use the id and/or name attributes to specify the
bean identifier(s).
3. Scope - This attribute specifies the scope of the objects created from a
particular bean definition and it will be discussed in bean scopes chapter.
4. scope
This attribute specifies the scope of the objects created from a particular bean
definition and it will be discussed in bean scopes chapter.
5. properties
This is used to inject the dependencies and will be discussed in subsequent
chapters.
6. autowiring mode
This is used to inject the dependencies and will be discussed in subsequent
chapters.
7. lazy-initialization mode
A lazy-initialized bean tells the IoC container to create a bean instance when
it is first requested, rather than at the startup.
8. initialization method
A callback to be called just after all necessary properties on the bean have
been set by the container. It will be discussed in bean life cycle chapter.
9. destruction method
A callback to be used when the container containing the bean is destroyed. It
will be discussed in bean life cycle chapter.
14 With a suitable program explain dependency injection with spring- setter injection
We can inject the dependency by setter method also. The <property> subelement of
<bean> is used for setter injection. Here we are going to inject
Let's see the simple example to inject primitive and string-based values by setter
method. We have created three files here:
● Employee.java
● applicationContext.xml
● Test.java
It is a simple class containing three fields id, name and city with its setters and
getters and a method to display these informations.
package com.javatpoint;
public class Employee {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
void display(){
System.out.println(id+" "+name+" "+city);
}
}
applicationContext.xml
We are providing the information into the bean by this file. The property element
invokes the setter method. The value subelement of property will assign the specified
value.
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
This class gets the bean from the applicationContext.xml file and calls the display
method.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
Employee e=(Employee)factory.getBean("obj");
s.display();
}
}
ans One of the key components of Spring Framework is the Aspect oriented
programming (AOP) framework. Aspect-Oriented Programming entails breaking
down program logic into distinct parts called so-called concerns. The functions that
span multiple points of an application are called cross-cutting concerns and these
cross-cutting concerns are conceptually separate from the application's business
logic. There are various common good examples of aspects like logging, auditing,
declarative transactions, security, caching, etc.
The key unit of modularity in OOP is the class, whereas in AOP the unit of
modularity is the aspect. Dependency Injection helps you decouple your application
objects from each other and AOP helps you decouple cross-cutting concerns from
the objects that they affect. AOP is like triggers in programming languages such as
Perl, .NET, Java, and others.
Spring AOP module provides interceptors to intercept an application. For example,
when a method is executed, you can add extra functionality before or after the
method execution.
AOP Terminologies
Before we start working with AOP, let us become familiar with the AOP concepts
and terminology. These terms are not specific to Spring, rather they are related to
AOP.
1. Aspect
This is a module which has a set of APIs providing cross-cutting
requirements. For example, a logging module would be called AOP aspect
for logging. An application can have any number of aspects depending on the
requirement.
2. Join point
This represents a point in your application where you can plug-in the AOP
aspect. You can also say, it is the actual place in the application where an
action will be taken using Spring AOP framework.
3. Advice
This is the actual action to be taken either before or after the method
execution. This is an actual piece of code that is invoked during the program
execution by Spring AOP framework.
4. Pointcut
This is a set of one or more join points where an advice should be executed.
You can specify pointcuts using expressions or patterns as we will see in our
AOP examples.
5. Introduction
An introduction allows you to add new methods or attributes to the existing
classes.
6. Target object
The object being advised by one or more aspects. This object will always be a
proxied object, also referred to as the advised object.
7. Weaving
Weaving is the process of linking aspects with other application types or
objects to create an advised object. This can be done at compile time, load
time, or at runtime.
Types of Advice
Spring aspects can work with five kinds of advice mentioned as follows −
1. before
Run advice before the a method execution.
2. after
Run advice after the method execution, regardless of its outcome.
3. after-returning
Run advice after the a method execution only if method completes
successfully.
4. after-throwing
Run advice after the a method execution only if method exits by throwing an
exception.
5. around
Run advice before and after the advised method is invoked.
ans
AOP
Using AOP, we define common functionality in one place. We are free to define how
and where this functionality is applied without modifying the class to which we are
applying the new feature. The cross-cutting concern can now be modularized into
special classes, called aspect.
● Before Advice
● After Advice
● Around Advice
● After Throwing
● After Returning
Before Advice: An advice that executes before a join point, is called before advice.
We use @Before annotation to mark an advice as Before advice.
After Advice: An advice that executes after a join point, is called after advice. We
use @After annotation to mark an advice as After advice.
Around Advice: An advice that executes before and after of a join point, is called
around advice.
After Throwing Advice: An advice that executes when a join point throws an
exception.
ans A Joinpoint is a point in Spring AOP during the execution of a program, such as the
execution of a method or the handling of an exception, etc. This symbolizes a point
in your web application where you can easily plug in the AOP aspect of your
software. In Spring AOP, a JoinPoint always represents a method execution. It is
mainly the actual place in the web application where an action will be executed using
the Spring AOP framework.
ans In this article, you will learn about the Pointcut expressions used to match advice
with the target Joinpoints. Spring AOP uses AspectJ pointcut expressions. In the
tutorial home page, you read the Pointcut definition. Spring AOP only supports
method execution join points, so you can think of a pointcut as matching the
execution of methods on Spring beans.
In simple words, a pointcut expression is like a Regular Expression which
determines the classes and methods where the Advice will be executed.
Declaring a Pointcut
Declaring a pointcut is simple, all you need is annotate the method with
@Pointcut(POINTCUT_EXPRESSION).
It is optional to use @Pointcut instead, the pointcut expressions can be directly used
inside the advice annotations as shown below.
● execution – for matching method execution join points. This is the most
widely used PCD.
● within – for matching methods of classes within certain types e.g. classes
within a package.
● @within – for matching to join points within types (target object class) that
have the given annotation.
● this – for matching to join points (the execution of methods) where the bean
reference (Spring AOP proxy) is an instance of the given type.
● target – for matching with the target object of the specific instance type.
● @target – for matching with the target object annotated with a specific
annotation.
● args – for matching with methods where its arguments are of a specific type.
● @args – for matching with methods where its arguments are annotated with a
specific annotation.
● @annotation – for matching to join points where the subject (method) of the
Joinpoint has the given annotation.
● bean (idOrNameOfBean) – This PCD lets you limit the matching of join
points to a particular named Spring bean or to a set of named Spring beans
(when using wildcards).
AspectJ provides several other designators which are not supported in Spring AOP,
only the above mentioned PCD are supported.
1. execution designator
This is the most widely used designator that everyone needs to know, used to match
the method execution Joinpoint. The syntax of an execution() designator is discussed
below.
Similarly, the @within is used for matching with join points (method execution)
where the declared class of the target object has a given annotation.
"this(com.jbd.service.AccountService)"
Example, any join point where the target object implements the AccountService
interface.
"target(com.jbd.service.AccountService)"
For example, any join point (method execution) that takes a single parameter and
where the argument passed at runtime is Serializable.
"args(java.io.Serializable)"
Example, match with any join point (method execution) where the executing method
has an @Transactional annotation.
"@annotation(org.springframework.transaction.annotation.Transactional)"
Example, any join point (method execution) on Spring beans having names that
match the wildcard expression *Manager.
"bean(*Manager)"
So what you have to do is just define the connection parameters and specify the SQL
statement to be executed and do the required work for each iteration while fetching
data from the database.
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "password"/>
</bean>
Data Access Object (DAO)
DAO stands for Data Access Object, which is commonly used for database
interaction. DAOs exist to provide a means to read and write data to the database and
they should expose this functionality through an interface by which the rest of the
application will access them.
The DAO support in Spring makes it easy to work with data access technologies like
JDBC, Hibernate, JPA, or JDO in a consistent way.
ans
Spring JdbcTemplate is a powerful mechanism to connect to the database and
execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of
JDBC API.
● We need to write a lot of code before and after executing the query, such as
creating connection, statement, closing resultset, connection etc.
● We need to perform exception handling code on the database logic.
● We need to handle transaction.
● Repetition of all these codes from one to another database logic is a time
consuming task.
Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It
provides you methods to write the queries directly, so it saves a lot of work and time.
● JdbcTemplate
● NamedParameterJdbcTemplate
● SimpleJdbcTemplate
● SimpleJdbcInsert and SimpleJdbcCall
JdbcTemplate class
It is the central class in the Spring JDBC support classes. It takes care of creation and
release of resources such as creating and closing of connection object etc. So it will
not lead to any problem if you forget to close the connection.
It handles the exception and provides the informative exception messages by the help
of excepion classes defined in the org.springframework.dao package.
We can perform all the database operations by the help of JdbcTemplate class such as
insertion, updation, deletion and retrieval of the data from the database.
21 Write short note on approaches for JDBC database access
Once you start using one of these approaches, you can still mix and match to include
a feature from a different approach. All approaches require a JDBC 2.0-compliant
driver, and some advanced features require a JDBC 3.0 driver.
Interface Declaration
Following is the declaration for
org.springframework.jdbc.core.NamedParameterJdbcTemplate class −
Syntax
MapSqlParameterSource in = new MapSqlParameterSource();
in.addValue("id", id);
in.addValue("description", new SqlLobValue(description, new
DefaultLobHandler()), Types.CLOB);
String SQL = "update Student set description = :description where id = :id";
NamedParameterJdbcTemplate jdbcTemplateObject = new
NamedParameterJdbcTemplate(dataSource);
jdbcTemplateObject.update(SQL, in);
Where,
● Update the project Student created under chapter Spring JDBC - First
Application
● Update the bean configuration and run the application as explained below.