Advance Java[1]
Advance Java[1]
Generics in Java provide type safety, reusability, and cleaner code. They allow
you to write classes, methods, and interfaces that can operate on objects of
various types while ensuring compile-time type checking. This prevents runtime
errors and eliminates the need for type casting.
Key Benefits:
class Box<T> {
private T value;
1. List Interface
Key Characteristics:
o Ordered: Elements are stored in a specific order.
o Allows duplicates: Same element can appear multiple times.
o Index-based access: Allows retrieving elements based on their
position.
Common Implementations:
o ArrayList
o LinkedList
Example:
java
Copy code
import java.util.*;
2. Set Interface
The Set interface represents a collection that does not allow duplicate elements.
It models the mathematical set abstraction, where each element is unique.
Key Characteristics:
o Unordered: Elements are stored without any specific order.
o No duplicates: Duplicate elements are not allowed.
Common Implementations:
o HashSet
o LinkedHashSet
o TreeSet
Example:
java
Copy code
import java.util.*;
Conclusion
Example:
java
Copy code
import java.util.*;
// Before sorting
System.out.println("Before sorting: " +
list);
// After sorting
System.out.println("After sorting: " + list);
}
}
Output:
less
Copy code
Before sorting: [5, 2, 8, 1, 7]
After sorting: [1, 2, 5, 7, 8]
Explanation:
Collections.sort(list): This method sorts the ArrayList in
ascending order (natural ordering).
Ans:
Both List and Set are part of the Java Collections Framework. They are
used to store collections of elements, but they have distinct characteristics. Here
is a comparison:
Feature List Set
Set is a collection that
List is an ordered collection
does not allow duplicate
that allows duplicates and
Definition elements and does not
allows access to elements by
guarantee any specific
index.
order.
Does not maintain any
specific order (although
Maintains the order of elements LinkedHashSet
Order
(insertion order or index-based). maintains insertion order
and TreeSet maintains
natural order).
Does not allow duplicate
Duplicates Allows duplicate elements.
elements.
Provides index-based access Does not support indexing.
Indexing (you can get elements by their You cannot access
position in the list). elements by position.
HashSet,
Common ArrayList, LinkedList,
LinkedHashSet,
Implementations Vector
TreeSet
List Example:
java
Copy code
import java.util.*;
Summary
Ans:
Both Set and Map are part of the Java Collections Framework but are used
for different purposes. Here's a detailed comparison:
Set Example:
java
Copy code
import java.util.*;
Set:
o Stores unique values only (no duplicates).
o Does not associate values with keys.
o Does not allow indexing (no positional access).
Map:
o Stores key-value pairs, where keys are unique and values can be
duplicated.
o Keys are used to map to values, providing a way to efficiently look
up values based on keys.
o Does not allow direct indexing but provides key-based access to
values.
Choose Set when you only need unique elements, and choose Map when you
need to associate a unique key with a value.
Ans:
Syntax:
import java.util.*;
Key Points:
Ans:
Wildcards in Java are used with generics to represent an unknown type. They
are commonly used in situations where you want to work with a generic type
without specifying the exact type. There are three types of wildcards in Java:
import java.util.*;
import java.util.*;
import java.util.*;
Summary:
Unbounded Wildcard (<?>): Used when the type is not specified and
can be any type.
Upper Bounded Wildcard (<? extends T>): Used when the type is
a subtype of T.
Lower Bounded Wildcard (<? super T>): Used when the type is a
supertype of T.
Q8 Set interface with program
Ans:
The Set interface in Java is part of the Java Collections Framework and
represents a collection of unique elements. It does not allow duplicates and
does not guarantee any specific order of elements (unless specified by a
particular implementation, like LinkedHashSet or TreeSet).
Key Points:
import java.util.*;
Output:
Explanation:
Summary:
The Set interface is ideal when you need to store unique elements and don't
care about their order. The common implementations include HashSet,
LinkedHashSet, and TreeSet.
Q9. Map interface with program
Ans:
The Map interface in Java represents a collection of key-value pairs. Each key is
unique, and each key maps to exactly one value. Unlike Set and List, a Map
does not extend the Collection interface.
Key Points:
import java.util.*;
Output:
Explanation:
put(): Adds key-value pairs to the map. If the key already exists, the
value is overwritten.
get(): Retrieves the value associated with the given key.
Overwriting: The value for the key "Apple" is overwritten from 10 to
15.
Summary:
The Map interface is used for storing key-value pairs. It does not allow
duplicate keys, but values can be repeated. Common implementations include
HashMap, LinkedHashMap, and TreeMap.
Q10 JSP Architecture
Ans:
+---------------------+
| Client (Browser) |
+---------------------+
|
v
+---------------------+
| Web Container |
| (Servlet Engine) |
+---------------------+
|
v
+---------------------+
+---------------------+
| JSP Page | ---> | Servlet (JSP
Engine)|
+---------------------+
+---------------------+
|
v
+---------------------+
| JavaBeans/Model | <---> | Database
(Optional) |
+---------------------+
+---------------------+
Summary:
Ans:
Implicit Objects in JSP are pre-defined objects provided by the JSP container
that can be used directly in JSP pages without needing to explicitly declare or
instantiate them. These objects provide a convenient way to interact with the
request, response, session, application, etc.
1. request:
o Type: HttpServletRequest
o Represents the client's request.
o Used to access request parameters, headers, attributes, etc.
o Example: request.getParameter("name");
2. response:
o Type: HttpServletResponse
o Represents the HTTP response to be sent to the client.
o Used to send data to the client (e.g., setting headers, cookies).
o Example: response.setContentType("text/html");
3. out:
o Type: JspWriter
o Represents the output stream to send data to the client.
o Used to send content (e.g., HTML) to the browser.
o Example: out.println("Hello, World!");
4. session:
o Type: HttpSession
o Represents the session between the client and the server.
o Used to store session-specific data (e.g., user login status).
o Example: session.setAttribute("username",
"John");
5. application:
o Type: ServletContext
o Represents the entire web application's context.
o Used to store data that is shared across the application.
o Example: application.setAttribute("appVersion",
"1.0");
6. config:
o Type: ServletConfig
o Provides initialization parameters for the JSP page (typically from
the web.xml).
o Example: config.getInitParameter("maxUsers");
7. pageContext:
o Type: PageContext
o Provides access to various page-level attributes like session,
request, response, etc.
o Example: pageContext.getSession();
8. page:
o Type: Object
o Refers to the current JSP page (equivalent to this in Java).
o Example: out.println(this); (represents the current page
instance).
9. exception (only in error pages):
o Type: Throwable
o Represents the exception that occurred in the JSP page (only in
error pages).
o Example: out.println(exception.getMessage());
10.param:
o Type: Map<String, String>
o Provides a map of request parameters (similar to
request.getParameter() but in a map form).
o Example: param.get("name");
11.header:
o Type: Map<String, String>
o Provides a map of request headers.
o Example: header.get("User-Agent");
12.cookie:
o Type: Cookie[]
o Represents the cookies sent by the client.
o Example: cookie[0].getValue();
13.initParam:
o Type: Map<String, String>
o Provides access to initialization parameters from the web.xml.
o Example: initParam.get("serverName");
Example Usage:
<%@ page import="java.util.*" %>
<html>
<body>
<h2>JSP Implicit Objects Example</h2>
<p>Request Parameter: <%=
request.getParameter("name") %></p>
<p>Session Attribute: <%=
session.getAttribute("username") %></p>
<p>Application Attribute: <%=
application.getAttribute("appVersion") %></p>
<p>Request Header: <%= header.get("User-Agent")
%></p>
</body>
</html>
Summary:
JSP Implicit Objects simplify interactions with the HTTP request, response,
session, application context, and other resources, making it easier to handle
common tasks like getting request parameters, managing session data, and
writing output.
Q12 JSP standard actions
Ans:
JSP Standard Actions are predefined tags that provide functionality to a JSP
page without writing Java code. They are used to perform tasks such as
including content, forwarding requests, or creating and using JavaBeans, among
others.
1. <jsp:include>:
o Includes a file (HTML, JSP, or servlet) at request time.
o Used to include static or dynamic content in a JSP page.
o Syntax:
o <jsp:include page="filename.jsp" />
2. <jsp:forward>:
o Forwards the request to another resource (e.g., another JSP or
servlet).
o Used for request dispatching in a web application.
o Syntax:
o <jsp:forward page="nextpage.jsp" />
3. <jsp:useBean>:
o Creates or locates a JavaBean and makes it available to the JSP
page.
o Typically used for accessing and setting JavaBean properties in the
JSP page.
o Syntax:
o <jsp:useBean id="bean"
class="com.example.MyBean" scope="page|
request|session|application" />
4. <jsp:setProperty>:
o Sets a property of a JavaBean.
o Typically used after <jsp:useBean> to populate the bean with
values (either from parameters, attributes, or other sources).
o Syntax:
o <jsp:setProperty name="bean"
property="propertyName" value="value" />
5. <jsp:getProperty>:
o Retrieves the value of a property from a JavaBean and outputs it to
the client.
oTypically used to display the value of a bean's property.
o Syntax:
o <jsp:getProperty name="bean"
property="propertyName" />
6. <jsp:param>:
o Used inside <jsp:include> or <jsp:forward> to pass
parameters to the included or forwarded page.
o Syntax:
o <jsp:param name="paramName"
value="paramValue" />
7. <jsp:plugin>:
o Embeds an applet, a JavaBean, or other plugin elements in the JSP
page.
o Typically used to embed Java applets or ActiveX controls.
o Syntax:
o <jsp:plugin type="applet|bean"
code="AppletClass" width="300" height="200">
o <jsp:param name="paramName"
value="paramValue" />
o </jsp:plugin>
Summary:
JSP Standard Actions help simplify tasks in a JSP page, such as including
content, forwarding requests, working with JavaBeans, and passing parameters.
These actions allow for cleaner and more modular JSP code by reducing the
need for Java logic within the page.
Q13 Factorial program?greater number /program/current date
display program in jsp
Ans:
<%
String numStr = request.getParameter("num");
if (numStr != null) {
int num = Integer.parseInt(numStr);
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
out.println("Factorial of " + num + " is:
" + factorial);
}
%>
</body>
</html>
This program compares two numbers and displays the greater one.
<%
String num1Str =
request.getParameter("num1");
String num2Str =
request.getParameter("num2");
if (num1Str != null && num2Str != null) {
int num1 = Integer.parseInt(num1Str);
int num2 = Integer.parseInt(num2Str);
if (num1 > num2) {
out.println("Greater number is: " +
num1);
} else {
out.println("Greater number is: " +
num2);
}
}
%>
</body>
</html>
Summary:
Each of these programs leverages basic JSP functionalities like handling user
inputs, performing calculations, and displaying results dynamically.
Ans:
1. Using Cookies
2. Using URL Rewriting
3. Using HttpSession
4. Using Hidden Form Fields
Among these, HttpSession is the most common and widely used for session
tracking.
1. Using HttpSession
1. Cookies:
o The server sends a small piece of data (cookie) to the client's
browser. The browser returns this data with each subsequent
request, allowing the server to identify the client.
o Example: Cookie objects are used to store the session ID.
2. URL Rewriting:
o The session ID is appended to the URL. It’s used when cookies are
disabled in the browser.
o Example: response.encodeURL("/page?id=123").
3. Hidden Form Fields:
o Hidden form fields store the session ID and are included with form
submissions to track the session.
o Example: <input type="hidden" name="sessionID"
value="12345"/>.
4. HttpSession:
o The most commonly used method. Stores session data on the
server, identified by a session ID stored in a cookie or passed via
the URL.
Summary:
Session Tracking helps maintain state across multiple requests from the
same user.
HttpSession is the most common method for session tracking,
where you store data on the server and associate it with a session ID.
Ans:
1. Tag Handler Class: This class contains the logic to process the custom
tag.
2. Tag Library Descriptor (TLD): This XML file defines the tag and its
attributes.
3. Tag Usage in JSP: Custom tags are used in JSP pages just like built-in
tags.
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import java.io.IOException;
@Override
public int doStartTag() throws JspException {
try {
// Write the custom output to the page
if (name != null) {
pageContext.getOut().write("Hello, "
+ name + "!");
} else {
pageContext.getOut().write("Hello,
World!");
}
} catch (IOException e) {
throw new JspException("Error: " +
e.getMessage());
}
return SKIP_BODY; // Don't process the body
content
}
}
2. TLD File (taglib.tld):
Import the tag library and use the custom tag in your JSP page.
<html>
<body>
<h2>Custom Tag Example</h2>
<mytags:hello name="John" />
<br>
<mytags:hello />
</body>
</html>
Explanation:
Summary:
Ans:
Dependency Injection in Java (Short Answer)
// Service Implementation
public class EmailGreetingService implements
GreetingService {
public void greet(String name) {
System.out.println("Sending email greeting to
" + name);
}
}
Step 2: Define Client Class
public class Client {
private GreetingService greetingService;
// Constructor Injection
public Client(GreetingService greetingService) {
this.greetingService = greetingService;
}
client.executeGreeting("John");
}
}
Output:
Summary:
Ans:
Types of Autowiring:
1. By Type (@Autowired):
o The Spring container injects the dependency based on the data
type of the property.
3. By Constructor (@Autowired):
o The Spring container uses the constructor to inject the
dependencies.
@Service
public class EmailService implements MessagingService
{
@Override
public void sendMessage(String message) {
System.out.println("Sending email: " +
message);
}
}
Step 2: Define the Client (Controller) Class
import
org.springframework.beans.factory.annotation.Autowire
d;
import org.springframework.stereotype.Component;
@Component
public class NotificationController {
private MessagingService messagingService;
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
Output:
Summary:
Ans:
Circular Dependency occurs when two or more beans (or classes) depend on
each other directly or indirectly, creating a cycle. In simple terms, it's when
Class A depends on Class B, and Class B depends on Class A. This
can lead to issues like infinite loops or a failure to resolve dependencies.
@Component
public class ClassA {
private ClassB classB;
@Autowired
public void setClassB(ClassB classB) {
this.classB = classB;
}
@Component
public class ClassB {
private ClassA classA;
@Autowired
public void setClassA(ClassA classA) {
this.classA = classA;
}
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
Step 3: Main Class to Run the Application
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConf
igApplicationContext;
Setter Injection resolves the issue because Spring can instantiate the beans and
inject dependencies later.
Summary:
Ans:
4. Web Layer: Spring offers a comprehensive set of tools for building web
applications, including:
o Spring Web MVC: A model-view-controller framework used to
build web applications.
o Spring WebSocket: Enables full-duplex communication between
the client and server.
o Spring REST: Facilitates building RESTful web services.
5. Spring Security: Provides authentication, authorization, and other
security features for your application.
6. Spring Boot (optional): Simplifies Spring application development by
providing auto-configured settings and embedded servers, reducing the
complexity of traditional Spring configuration.
Basic Example:
@Component
public class MessagePrinter {
private final MessageService messageService;
@Autowired
public MessagePrinter(MessageService
messageService) {
this.messageService = messageService;
}
public void printMessage() {
System.out.println(messageService.getMessage());
}
}
3. Main Class to Run the Application:
import
org.springframework.context.annotation.AnnotationConf
igApplicationContext;
MessagePrinter printer =
context.getBean(MessagePrinter.class);
printer.printMessage(); // Output: Hello,
Spring!
context.close();
}
}
Summary:
Ans:
1. Before Advice:
o Executed before the target method is invoked.
o Used for actions like logging, security checks, or validating inputs.
Example:
@Before("execution(*
com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before method: " +
joinPoint.getSignature().getName());
}
2. After Advice:
o Executed after the target method is invoked, regardless of its
outcome (whether the method succeeded or threw an exception).
o Useful for cleanup actions, logging, etc.
Example:
@After("execution(*
com.example.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("After method: " +
joinPoint.getSignature().getName());
}
Example:
@AfterReturning(pointcut = "execution(*
com.example.service.*.*(..))", returning =
"result")
public void logAfterReturning(JoinPoint
joinPoint, Object result) {
System.out.println("Method " +
joinPoint.getSignature().getName() + " returned:
" + result);
}
Example:
@AfterThrowing(pointcut = "execution(*
com.example.service.*.*(..))", throwing =
"error")
public void logAfterThrowing(JoinPoint joinPoint,
Throwable error) {
System.out.println("Method " +
joinPoint.getSignature().getName() + " threw
exception: " + error);
}
5. Around Advice:
o Surrounds the target method execution, allowing it to control
whether the method proceeds or not.
o It can modify input arguments and the return value.
Example:
@Around("execution(*
com.example.service.*.*(..))")
public Object logAround(ProceedingJoinPoint
joinPoint) throws Throwable {
System.out.println("Before method execution:
" + joinPoint.getSignature().getName());
Object result = joinPoint.proceed(); //
Proceed with method execution
System.out.println("After method execution: "
+ joinPoint.getSignature().getName());
return result;
}
Summary:
Advice is the action taken by an aspect at a specific join point in Spring
AOP.
Common types of advice include Before, After, After Returning, After
Throwing, and Around.
Before advice runs before the target method, while After advice runs
after the method.
Around advice can control method execution, and After
Returning/Throwing are invoked based on the method’s outcome.
Spring AOP provides a powerful way to separate cross-cutting concerns
like logging, security, and transaction management.
Ans:
In Spring AOP, a Pointcut defines the join points where advice (actions like
logging, security checks, etc.) should be applied. Pointcut designators are
expressions that help you specify those join points where you want to apply the
advice.
Types of Pointcut Designators:
1. execution():
o Matches method executions based on the method signature.
o Syntax: execution([access_modifier]
[return_type] [class_name].[method_name]
([parameters]))
Example:
@Before("execution(public void
com.example.service.UserService.createUser(..))")
public void logBeforeCreateUser() {
System.out.println("Before creating user");
}
2. within():
o Matches the execution within a given class or package.
o It restricts the advice to be applied only within the specified class
or package.
Example:
@Before("within(com.example.service.*)")
public void logBeforeServiceMethods() {
System.out.println("Before service method
execution");
}
3. args():
o Matches method execution based on the arguments passed to the
method.
o It’s used to select methods that have specific argument types.
Example:
@Before("args(String, ..)")
public void logBeforeStringArgumentMethod() {
System.out.println("Method called with String
argument");
}
This applies the advice before any method that takes a String as the
first argument.
4. @annotation():
o Matches methods annotated with a specific annotation.
Example:
@Before("@annotation(com.example.annotations.Logg
able)")
public void logMethod() {
System.out.println("Method with @Loggable
annotation called");
}
This applies the advice before any method annotated with @Loggable.
5. @within():
o Matches join points where the target class is annotated with the
specified annotation.
Example:
@Before("@within(com.example.annotations.Transact
ional)")
public void logBeforeTransactionalMethods() {
System.out.println("Before method in
@Transactional class");
}
This applies the advice before any method in a class annotated with
@Transactional is executed.
6. this():
o Matches the target object type (proxy type).
Example:
@Before("this(com.example.service.UserService)")
public void logBeforeUserServiceMethods() {
System.out.println("Before method in
UserService proxy");
}
7. target():
o Matches the target object (actual class) rather than the proxy type.
Example:
@Before("target(com.example.service.UserService)"
)
public void logBeforeTargetUserServiceMethods() {
System.out.println("Before method in actual
UserService class");
}
This applies the advice before any method in the actual UserService
class.
Summary:
Q22 Pointcut
Ans:
A Pointcut in Spring AOP defines a set of join points (specific points in the
execution of a program, such as method calls) where an advice (action) should
be applied. The pointcut is essentially a condition that matches specific methods
based on various criteria such as method name, parameters, annotations, etc.
Pointcuts are used in conjunction with advices to apply cross-cutting concerns
like logging, transaction management, etc.
Key Concepts of Pointcut:
Example:
@Before("execution(public void
com.example.service.UserService.createUser(..))")
public void logBeforeCreateUser() {
System.out.println("Before creating user");
}
Example:
@Before("within(com.example.service.UserService)"
)
public void logBeforeUserServiceMethods() {
System.out.println("Before method execution
in UserService");
}
Example:
@Before("args(String, ..)")
public void logBeforeStringArgumentMethod() {
System.out.println("Method called with a
String argument");
}
This pointcut matches methods that accept a String as the first
argument.
Example:
@Before("@annotation(com.example.annotations.Logg
able)")
public void logBeforeAnnotatedMethods() {
System.out.println("Method annotated with
@Loggable is about to be called");
}
Example:
@Before("@within(com.example.annotations.Transact
ional)")
public void logBeforeTransactionalMethods() {
System.out.println("Before method execution
in a @Transactional class");
}
Summary:
Ans:
The JdbcTemplate class in Spring JDBC is the central class for interacting
with databases. It simplifies database operations like executing SQL queries,
updating data, and handling exceptions. It handles the low-level details of JDBC
such as opening and closing connections, and managing resources.
1. queryForObject():
o Executes a query and maps the result to a single object.
o Useful for retrieving a single record.
Example:
2. queryForList():
o Executes a query and maps the result to a list of objects.
o Useful for retrieving multiple records.
Example:
3. update():
o Executes an update, insert, or delete SQL statement.
Example:
4. query():
o Executes a query that returns multiple rows, mapping each row to
an object using a RowMapper.
Example:
5. batchUpdate():
o Executes multiple update, insert, or delete statements in a batch.
Example:
String sql = "UPDATE users SET name = ? WHERE id
= ?";
List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(new Object[]{"John", 1});
batchArgs.add(new Object[]{"Jane", 2});
jdbcTemplate.batchUpdate(sql, batchArgs);
Example:
Summary:
Ans:
Frameworks like Spring JDBC and JPA eliminate the need to write low-
level code for opening/closing database connections, handling SQL
exceptions, or managing transactions.
3. Exception Handling:
5. Improved Maintainability:
6. Transaction Management:
Summary:
Modeling JDBC in Java using frameworks like Spring JDBC offers benefits
such as simplified interaction with databases, reduced boilerplate code, better
exception handling, increased productivity, improved maintainability, automatic
transaction management, and more efficient resource handling.
Ans:
In a Spring application, when dealing with multiple complex SQL queries, it's
common to use Spring JDBC or Spring Data JPA to handle database
operations in a clean and efficient manner. Below is an example of how you can
execute multiple complex queries using Spring JDBC with JdbcTemplate.
Setup
1. Employee Table:
2.CREATE TABLE employees (
3. id INT PRIMARY KEY,
4. name VARCHAR(100),
5. department_id INT
6.);
7. Department Table:
8.CREATE TABLE departments (
9. id INT PRIMARY KEY,
10. department_name VARCHAR(100)
11. );
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
@Bean
public JdbcTemplate jdbcTemplate(DataSource
dataSource) {
return new JdbcTemplate(dataSource);
}
}
3. Repository or DAO for Complex Queries:
@Repository
public class EmployeeDao {
@Autowired
private JdbcTemplate jdbcTemplate;
// Complex query to fetch all employees with
their department name
public List<Employee>
getAllEmployeesWithDepartment() {
String sql = "SELECT e.id, e.name,
d.department_name " +
"FROM employees e " +
"JOIN departments d ON
e.department_id = d.id";
return jdbcTemplate.query(sql, new
RowMapper<Employee>() {
@Override
public Employee mapRow(ResultSet rs, int
rowNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getInt("id"));
employee.setName(rs.getString("name"));
employee.setDepartmentId(rs.getInt("department_id"));
return employee;
}
});
}
@Autowired
private EmployeeDao employeeDao;
Summary:
This example demonstrates how to execute multiple complex SQL queries using
Spring JDBC with JdbcTemplate. By using RowMapper, complex queries
(such as JOINs and aggregation) can be executed easily, while Spring handles
boilerplate JDBC tasks like connection management and exception handling,
making the application cleaner and more maintainable.
Q26 Data Access operations.
Ans:
Data access operations in Java are typically performed through various methods
and libraries to interact with databases. Below are the main ways to perform
data access operations in Java:
Key Operations:
o Connecting to Database: Establish a connection using
DriverManager or DataSource.
o Executing Queries: Execute SELECT, INSERT, UPDATE, and
DELETE using Statement, PreparedStatement, or
CallableStatement.
o Handling Result Sets: Use ResultSet to retrieve and process
query results.
o Closing Resources: Always close connections, statements, and
result sets to avoid resource leaks.
Example:
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3
306/mydb", "user", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM
users");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
Key Operations:
o EntityManager: The central API to interact with the persistence
context.
o CRUD Operations: Use methods like persist(), find(),
merge(), and remove() to manage entities.
o JPQL: Java Persistence Query Language allows you to write
queries that operate on Java objects.
Example:
@Entity
public class User {
@Id
private int id;
private String name;
// getters and setters
}
// Usage
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
User user = new User();
user.setName("John");
em.persist(user);
em.getTransaction().commit();
3. Spring JDBC:
Spring JDBC simplifies database access and transaction management while still
using low-level JDBC operations. It abstracts away boilerplate code related to
managing connections, statements, and result sets.
Key Operations:
o JdbcTemplate: The core class for executing SQL queries and
updates.
o RowMapper: Used to map rows of a result set to Java objects.
o Exception Handling: Automatically handles SQLExceptions
and converts them to Spring's DataAccessException.
Example:
Spring Data JPA is a part of the Spring Data project that simplifies JPA-based
data access. It automatically implements CRUD operations for repository
interfaces and allows the use of custom queries.
Key Operations:
o Repository Interface: Extends JpaRepository to enable
automatic CRUD operations.
o Custom Queries: Define custom queries using JPQL or native
SQL with @Query annotation.
o Pagination and Sorting: Supports pagination and sorting easily.
Example:
// Usage
List<User> users = userRepository.findByName("John");
Spring Data MongoDB provides an easy way to integrate MongoDB with Java
applications. It offers a repository-based approach to interact with MongoDB.
Key Operations:
o MongoRepository: Interface for basic CRUD operations with
MongoDB.
o Custom Queries: Write custom queries using the @Query
annotation or Criteria.
Example:
// Usage
List<User> users = userRepository.findByName("John");
6. MyBatis:
MyBatis is a persistence framework that offers more control over SQL queries
and mapping to objects compared to JPA or Hibernate. It uses XML or
annotations to define SQL statements and mappings.
Key Operations:
o SQL Mapping: Define SQL statements in XML or annotations.
o Mapper Interfaces: Define methods in interfaces that are mapped
to SQL queries.
Example:
@Mapper
public interface UserMapper {
@Select("SELECT name FROM users WHERE id =
#{id}")
String findById(int id);
}
// Usage
String name = userMapper.findById(1);
Summary:
Each of these methods provides its own set of tools and abstractions to simplify
or control how Java interacts with databases.
Ans:
The RowMapper interface is part of Spring JDBC, and it is used to map rows
of a ResultSet to Java objects. It allows developers to convert each row of
data returned by a SQL query into a Java object (POJO) based on column names
or custom mapping logic.
Key Method:
o mapRow(ResultSet rs, int rowNum): This method is
called for each row of the ResultSet, and it converts the data
from the row into an instance of a Java object.
Example of RowMapper:
// Usage in JdbcTemplate
String sql = "SELECT id, name FROM employees";
List<Employee> employees = jdbcTemplate.query(sql,
new EmployeeRowMapper());
Key Method:
o extractData(ResultSet rs): This method is called to
extract the data from the entire ResultSet.
Example of ResultSetExtractor:
// Usage in JdbcTemplate
String sql = "SELECT id, name FROM employees";
List<Employee> employees = jdbcTemplate.query(sql,
new EmployeeResultSetExtractor());
Summary of Differences:
RowMapper:
o Maps each row of the ResultSet to a Java object.
o Returns a single object for each row.
o Best suited for single-object mapping.
ResultSetExtractor:
o Extracts data from the entire ResultSet.
o Can return complex objects or collections based on all rows.
o Best suited for complex or aggregate results (e.g., lists, maps, or
multiple objects).
Both interfaces are part of Spring's JDBC framework and are used to simplify
data extraction and mapping from databases to Java objects.
Q28 Spring Boot Web Application
Ans:
Here’s how you can quickly set up a Spring Boot Web Application:
You can create a Spring Boot web application using the Spring Initializr
(https://start.spring.io/) or by manually setting it up in your IDE.
Add dependencies:
o Spring Web (for REST controllers and web functionalities).
o Spring Boot DevTools (for hot swapping and development
features).
The entry point of a Spring Boot application is the main() method annotated
with @SpringBootApplication.
@SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApp.class,
args);
}
}
3. Create a Controller:
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}
4. application.properties:
server.port=8080
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
This configures the application to run on port 8080 and set view resolution
properties for JSP views if used.
5. Running the Application:
Run the Spring Boot application via the command line using:
mvn spring-boot:run
Or, from your IDE, you can run the main() method directly.
@SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApp.class,
args);
}
}
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Spring Boot Web
Application!";
}
}
Summary:
Ans:
Spring Boot is an extension of the Spring Framework that simplifies the setup
and development of Java-based applications, especially web applications. It
provides a wide range of features to create stand-alone, production-grade
applications with minimal configuration.
1. Auto Configuration:
o Automatically configures Spring and third-party libraries based on
project dependencies. This reduces the need for manual
configuration.
2. Embedded Servers:
o Spring Boot provides embedded servers like Tomcat, Jetty, or
Undertow, so you don’t need to install and configure a separate
application server. Applications can be packaged as JAR or WAR
files.
3. Starter POMs:
o Spring Boot offers pre-configured templates called starters (e.g.,
spring-boot-starter-web, spring-boot-starter-
data-jpa) that include the necessary dependencies for various
functionality (web, database, etc.).
4. Production-Ready Features:
o Includes built-in features for monitoring, metrics, health checks,
and external configuration management, making it easy to deploy
applications to production environments.
5. Minimal Configuration:
o Reduces the need for extensive XML or Java configuration. It uses
sensible defaults and allows custom configuration via properties or
YAML files.
6. Spring Boot CLI:
Command-line interface to run Spring Boot applications from the
o
terminal with minimal setup, useful for rapid prototyping.
7. Microservices Support:
o Works well in microservices architectures, integrating easily with
Spring Cloud for building scalable, distributed applications.
@SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApp.class,
args);
}
}
Benefits:
Quick setup and deployment: Spring Boot provides a faster way to set
up and deploy applications without complex configurations.
Embedded server support: No need for external application servers like
Tomcat, as it provides its own server.
Production-ready: Built-in production-ready features like health checks,
metrics, and logging.
Ans:
RESTful Web Services in Java refer to web services that adhere to the
principles of Representational State Transfer (REST). REST is an
architectural style that uses HTTP methods (GET, POST, PUT, DELETE) to
interact with resources (data) represented as URLs, typically in a lightweight,
stateless manner.
Key Features:
1. Stateless: Each request from a client to the server must contain all the
information the server needs to understand and process the request. The
server does not store any session information.
2. Client-Server Architecture: The client and server are separate entities,
allowing them to evolve independently.
3. Cacheable: Responses must define themselves as cacheable or not to
improve performance by reducing the need for repeated requests.
4. Uniform Interface: RESTful services use standard HTTP methods and
status codes, making them easy to understand and use.
1. Spring Boot Setup: You can easily create RESTful services using Spring
Boot and the @RestController annotation.
2. Controller Class: A simple controller that provides RESTful endpoints.
3.@RestController
4.@RequestMapping("/api")
5.public class UserController {
6.
7. @GetMapping("/users/{id}")
8. public ResponseEntity<User>
getUserById(@PathVariable("id") int id) {
9. // Assume UserService retrieves a user by
ID
10. User user = userService.getUserById(id);
11. return ResponseEntity.ok(user);
12. }
13.
14. @PostMapping("/users")
15. public ResponseEntity<User>
createUser(@RequestBody User user) {
16. // Assume UserService saves the user
17. User createdUser =
userService.createUser(user);
18. return
ResponseEntity.status(HttpStatus.CREATED).body(cr
eatedUser);
19. }
20.
21. @DeleteMapping("/users/{id}")
22. public ResponseEntity<Void>
deleteUser(@PathVariable("id") int id) {
23. // Assume UserService deletes the user
by ID
24. userService.deleteUser(id);
25. return
ResponseEntity.noContent().build();
26. }
27. }
28.Data Model (User):
29. public class User {
30. private int id;
31. private String name;
32. private String email;
33. // Getters and Setters
34. }