0% found this document useful (0 votes)
10 views28 pages

Immutable Classes and REST API Guide

The document provides guidelines on creating immutable classes, using custom classes as keys in hashmaps, and exposing REST web services. It details steps for implementing REST APIs, including identifying resources, defining endpoints, and externalizing resources using JSON. Additionally, it explains various Spring annotations used for handling web requests, including @Controller, @RequestMapping, and others for managing HTTP methods and request parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views28 pages

Immutable Classes and REST API Guide

The document provides guidelines on creating immutable classes, using custom classes as keys in hashmaps, and exposing REST web services. It details steps for implementing REST APIs, including identifying resources, defining endpoints, and externalizing resources using JSON. Additionally, it explains various Spring annotations used for handling web requests, including @Controller, @RequestMapping, and others for managing HTTP methods and request parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. How to make immutable class?

Ans) a. Make your class final, so that no other classes can extend it.
[Link] all your fields final, so that they’re initialized only once inside
the constructor and never modified afterward.
[Link]’t expose setter methods.
[Link] exposing methods which modify the state of the class, you must
always return a new instance of the class.

2. How to use custom class as key in my hashmap?


Ans) Contract for hashCode and equals method :
1. The equals() method must return true if the fields of the current
object equal those of the object passed in, else return false. By “equal”,
we generally mean that primitive fields match via the == operator, and
objects are either both null or both non-null and match via the equals()
method. Note two important constraints on equals():
2. if [Link](y) returns true, then the hash codes of x and y must be
identical;

3. it must be reflexive and transitive: that is, [Link](y) must return the
same value as [Link](x), and if [Link](y) and [Link](z), then
[Link](z) must also be true (see below for what this actually means in
real terms!).

3. How to expose REST web service?


Ans) If your software module has a user interface that needs to consume
a REST API, you should expose web-services from your module with a
REST API.

In this tutorial you will learn how to identify and implement a set of REST
endpoints that expose your module features through web-services.

STEP 1 - IDENTIFY YOUR RESOURCES

The first thing to do when building a REST API is to identify which


resources will be exposed by your module. Note that resources are not
necessarily domain entities, althought it may appear to be so.

Let’s take for instance an application that manages a library. Examples of


resources that you might want to expose are:

 books
 requisitions
 …
These resources identify the data entities that your user interface will
need to display to the user so that he can interact with the application
and perform all the necessary use cases.

STEP 2 - DEFINE YOUR ENDPOINTS AND METHODS

Now that you identified all the necessary resources to expose, you need
to identify their respective locations.

REST APIs are accessible through HTTP, therefore, it is necessary to


identify the URIs and the respective methods where the resources they
expose can be accessed. These URIs are essentially paths, and can be
contextual, like for example listing all the requisitions of a particular
book: /books/523523435/requisitions
Then, you can associate a particular HTTP method to each one of these
paths, where each method has a particular meaning: The main four HTTP
methods, and their meanings, are:

 GET - Reads an existing resource


 POST - Creates a new resource
 PUT - Updates an existing resource
 DELETE - Deletes an existing resource
For example, creating a new book, should be represented by:
A POST on /books .
And the parameters to pass on that POST invocation should be the
following JSON:

{
"title": "The Hobbit",
"isbn": 3423123421213
}

If successful, this invocation should provide the following JSON response,


but it is optional:

{
"id": 1542341141,
"title": "The Hobbit",
"isbn": 3423123421213
}

Consequently, invoking a GET on /books/1542341141 , we should obtain


a similar response, i.e. a JSON describing a possible representation of the
book with object id 1542341141:
{
"id": 1542341141,
"title": "The Hobbit",
"isbn": 3423123421213
}

STEP 3 - EXTERNALIZE YOUR RESOURCES

A REST API normally operates with the exchange of resources that are
externalized through a particular data notation. As you’ve seen in the
previous steps, we are big fans of the JSON (JavaScript Object Notation).
This is because our client-side front-end technologies are mainly
Javascript-based, and it becomes easier to create and parse data in this
JSON format.

Before you get to implement the endpoints that you identified in the
previous step, you must provide externalizations of your application
resources using an interchangeble notation like JSON. The Bennu
infrastructure provides a library that eases that externalization through
the implementation of three interfaces:

 JsonViewer - Given a particular domain object, creates a JsonElement


that represents that domain object.
 JsonCreator - Given a particular JSON object, creates a new domain
object.
 JsonUpdater - Given a particular JSON object, updates an existing
domain object.
 JsonAdapter - This interface implements the above three interfaces.
An example of a BookAdapter that implements the JsonAdapter interface,
i.e. all three JsonViewer, JsonCreator and JsonUpdater interfaces:

@DefaultJsonAdapter([Link])
public class BookAdapter implements JsonAdapter<Book> {

@Override
public Book create(JsonElement jsonElement, JsonBuilder ctx) {
final JsonObject json = [Link]();
String name = [Link]("title");
String isbn = [Link]("isbn");
return [Link](title, isbn);
}

@Override
public Book update(JsonElement jsonElement, Book book, JsonBuilder
ctx) {
final JsonObject json = [Link]();
String name = [Link]("title");
String isbn = [Link]("isbn");
return [Link](title, isbn);
}

@Override
public JsonElement view(Book book, JsonBuilder ctx) {
final JsonObject json = new JsonObject();
[Link]("id", [Link]());
[Link]("title", [Link]());
[Link]("isbn", [Link]());
return json;
}
}

The annotation @DefaultJsonAdapter([Link]) registers this Adapter


class in the the JSON library, so it knowns what adapter to use when
handling a object of the Book class.

STEP 4 - IMPLEMENT THE IDENTIFIED ENDPOINTS

Now that you identified the necessary endpoints, you should implement
them on the server side, consuming the domain information in order to
produce JSON responses to invocations on those endpoints. The Bennu
infrastructure uses a library that eases this task, which is the bennu-json
library.

Then, to expose a particular endpoint, the Bennu infrastructure also


provides another context class, from which you can extend you should
create a new class that extends the BennuRestResource class, like in the
example:

public class OrderResource extends BennuRestResource {

@POST
@Path("/orders")
@Produces(MediaType.APPLICATION_JSON)
public String createOrder(JsonElement jsonElement) {
accessControl("#users");
return create(jsonElement);
}

...
}

4. Left outer join.

Ans) In an left outer join, all rows from the first table mentioned in the
SQL query is selected, regardless whether there is a matching row on the
second table mentioned in the SQL query. Let's assume that we have the
following two tables,

Table Store_Information

Store_Nam Sale
Txn_Date
e s
Jan-05-
Los Angeles 1500
1999
Jan-07-
San Diego 250
1999
Jan-08-
Los Angeles 300
1999
Jan-08-
Boston 700
1999

Table Geography

Region_Nam Store_Nam
e e
East Boston
East New York
West Los Angeles
West San Diego

We want to find out sales by store, and we want to see the results for all
stores regardless whether there is a sale in
the Store_Information table. To do this, we can use the following SQL
statement using LEFT OUTER JOIN:

SELECT A1.Store_Name STORE, SUM([Link]) SALES


FROM Geography A1
LEFT OUTER JOIN Store_Information A2
ON A1.Store_Name = A2.Store_Name
GROUP BY A1.Store_Name;
Result:

SALE
STORE
S
Los
1800
Angeles
San Diego 250
New York NULL
Boston 700

By using LEFT OUTER JOIN, all four rows in the Geography table is
listed. Since there is no match for "New York" in
the Store_Information table, the Sales total for "New York" is NULL.
Note that it is NULL and not 0, as NULL indicates there is no match

5. What are the annotations in Spring?

@Controller
This annotation is used on Java classes that play the role of
controller in your application. The @Controllerannotation allows
autodetection of component classes in the classpath and auto-
registering bean definitions for them. To enable autodetection of
such annotated controllers, you can add component scanning to
your configuration. The Java class annotated with @Controller is
capable of handling multiple request mappings.
This annotation can be used with Spring MVC and Spring WebFlux.

@RequestMapping
This annotation is used both at class and method level.
The @RequestMapping annotation is used to map web requests
onto specific handler classes and handler methods.
When @RequestMapping is used on class level it creates a base
URI for which the controller will be used. When this annotation is
used on methods it will give you the URI on which the handler
methods will be executed. From this you can infer that the class
level request mapping will remain the same whereas each handler
method will have their own request mapping.
Sometimes you may want to perform different operations based on
the HTTP method used, even though the request URI may remain
the same. In such situations, you can use the method attribute
of @RequestMapping with an HTTP method value to narrow down
the HTTP methods in order to invoke the methods of your class.
Here is a basic example on how a controller along with request
mappings work:
@Controller

@RequestMapping("/welcome")

public class WelcomeController{

@RequestMapping(method = [Link])

public String welcomeAll(){

return "welcome all";

In this example only GET requests to /welcome is handled by


the welcomeAll() method.
This annotation also can be used with Spring MVC and Spring
WebFlux.

The @RequestMapping annotation is very versatile. Please see my


in depth post on Request Mapping bere

@CookieValue
This annotation is used at method parameter
level. @CookieValue is used as argument of request mapping
method. The HTTP cookie is bound to the @CookieValue parameter
for a given cookie name. This annotation is used in the method
annotated with @RequestMapping.
Let us consider that the following cookie value is received with a
http request:
JSESSIONID=418AB76CD83EF94U85YD34W
To get the value of the cookie, use @CookieValue like this:

@RequestMapping("/cookieValue")

public void getCookieValue(@CookieValue "JSESSIONID" String cookie)


{

@CrossOrigin
This annotation is used both at class and method level to enable
cross origin requests. In many cases the host that serves JavaScript
will be different from the host that serves the data. In such a case
Cross Origin Resource Sharing (CORS) enables cross-domain
communication. To enable this communication you just need to add
the@CrossOrigin annotation.
By default the @CrossOrigin annotation allows all origin, all
headers, the HTTP methods specified in
the@RequestMapping annotation and maxAge of 30 min. You can
customize the behavior by specifying the corresponding attribute
values.
An example to use @CrossOrigin at both controller and handler
method levels is this.

@CrossOrigin(maxAge = 3600)

@RestController

@RequestMapping("/account")

public class AccountController {

@CrossOrigin(origins = "[Link]

@RequestMapping("/message")

public Message getMessage() {

// ...

@RequestMapping("/note")

public Note getNote() {

// ...

}
Composed @RequestMapping
Variants
Spring framework 4.3 introduced the following method-level
variants of @RequestMapping annotation to better express the
semantics of the annotated methods. Using these annotations have
become the standard ways of defining the endpoints. They act as
wrapper to @RequestMapping.
These annotations can be used with Spring MVC and Spring
WebFlux.

@GetMapping
This annotation is used for mapping HTTP GET requests onto
specific handler methods. @GetMapping is a composed annotation
that acts as a shortcut
for @RequestMapping(method = [Link])

@PostMapping
This annotation is used for mapping HTTP POST requests onto
specific handler methods. @PostMapping is a composed annotation
that acts as a shortcut
for @RequestMapping(method = [Link])

@PutMapping
This annotation is used for mapping HTTP PUT requests onto
specific handler methods. @PutMapping is a composed annotation
that acts as a shortcut
for @RequestMapping(method = [Link])

@PatchMapping
This annotation is used for mapping HTTP PATCH requests onto
specific handler methods. @PatchMapping is a composed
annotation that acts as a shortcut for @RequestMapping(method =
[Link])

@DeleteMapping
This annotation is used for mapping HTTP DELETE requests onto
specific handler methods. @DeleteMapping is a composed
annotation that acts as a shortcut
for @RequestMapping(method = [Link])
@ExceptionHandler
This annotation is used at method levels to handle exception at the
controller level. The @ExceptionHandlerannotation is used to
define the class of exception it will catch. You can use this
annotation on methods that should be invoked to handle an
exception. The @ExceptionHandler values can be set to an array of
Exception types. If an exception is thrown that matches one of the
types in the list, then the method annotated with
matching @ExceptionHandler will be invoked.

@InitBinder
This annotation is a method level annotation that plays the role of
identifying the methods which initialize theWebDataBinder -
a DataBinder that binds the request parameter to JavaBean objects.
To customise request parameter data binding , you can
use @InitBinder annotated methods within our controller. The
methods annotated with @InitBinder all argument types that
handler methods support.
The @InitBinder annotated methods will get called for each HTTP
request if you don’t specify the value element of this annotation.
The value element can be a single or multiple form names or
request parameters that the init binder method is applied to.

@Mappings and @Mapping


This annotation is used on fields. The @Mapping annotation is a
meta annotation that indicates a web mapping annotation. When
mapping different field names, you need to configure the source
field to its target field and to do that you have to add
the @Mappings annotation. This annotation accepts an array
of @Mapping having the source and the target fields.

@MatrixVariable
This annotation is used to annotate request handler method
arguments so that Spring can inject the relevant bits of matrix URI.
Matrix variables can appear on any segment each separated by a
semicolon. If a URL contains matrix variables, the request mapping
pattern must represent them with a URI template.
The@MatrixVariable annotation ensures that the request is
matched with the correct matrix variables of the URI.

@PathVariable
This annotation is used to annotate request handler method
arguments. The @RequestMapping annotation can be used to
handle dynamic changes in the URI where certain URI value acts as
a parameter. You can specify this parameter using a regular
expression. The @PathVariable annotation can be used declare this
parameter.

@RequestAttribute
This annotation is used to bind the request attribute to a handler
method parameter. Spring retrieves the named attributes value to
populate the parameter annotated with @RequestAttribute. While
the @RequestParamannotation is used bind the parameter values
from query string, the @RequestAttribute is used to access the
objects which have been populated on the server side.

@RequestBody
This annotation is used to annotate request handler method
arguments. The @RequestBody annotation indicates that a method
parameter should be bound to the value of the HTTP request body.
The HttpMessageConveter is responsible for converting from the
HTTP request message to object.

@RequestHeader
This annotation is used to annotate request handler method
arguments. The @RequestHeader annotation is used to map
controller parameter to request header value. When Spring maps
the request, @RequestHeader checks the header with the name
specified within the annotation and binds its value to the handler
method parameter. This annotation helps you to get the header
details within the controller class.

@RequestParam
This annotation is used to annotate request handler method
arguments. Sometimes you get the parameters in the request URL,
mostly in GET requests. In that case, along with
the @RequestMapping annotation you can use
the @RequestParam annotation to retrieve the URL parameter and
map it to the method argument. The@RequestParam annotation is
used to bind request parameters to a method parameter in your
controller.

@RequestPart
This annotation is used to annotate request handler method
arguments. The @RequestPart annotation can be used instead
of @RequestParam to get the content of a specific multipart and
bind to the method argument annotated with @RequestPart. This
annotation takes into consideration the “Content-Type” header in
the multipart(request part).

@ResponseBody
This annotation is used to annotate request handler methods.
The @ResponseBody annotation is similar to
the@RequestBody annotation. The @ResponseBody annotation
indicates that the result type should be written straight in the
response body in whatever format you specify like JSON or XML.
Spring converts the returned object into a response body by using
the HttpMessageConveter.

@ResponseStatus
This annotation is used on methods and exception
classes. @ResponseStatus marks a method or exception class with
a status code and a reason that must be returned. When the
handler method is invoked the status code is set to the HTTP
response which overrides the status information provided by any
other means. A controller class can also be annotated
with @ResponseStatus which is then inherited by
all @RequestMapping methods.

@ControllerAdvice
This annotation is applied at the class level. As explained earlier,
for each controller you can use@ExceptionHandler on a method
that will be called when a given exception occurs. But this handles
only those exception that occur within the controller in which it is
defined. To overcome this problem you can now use
the@ControllerAdvice annotation. This annotation is used to
define @ExceptionHandler, @InitBinder and@ModelAttribute meth
ods that apply to all @RequestMapping methods. Thus if you define
the @ExceptionHandlerannotation on a method
in @ControllerAdvice class, it will be applied to all the controllers.

@RestController
This annotation is used at the class level.
The @RestController annotation marks the class as a controller
where every method returns a domain object instead of a view. By
annotating a class with this annotation you no longer need to
add @ResponseBody to all the RequestMapping method. It means
that you no more use view-resolvers or send html in response. You
just send the domain object as HTTP response in the format that is
understood by the consumers like JSON.
@RestController is a convenience annotation which
combines @Controller and @ResponseBody .

@RestControllerAdvice
This annotation is applied on Java
classes. @RestControllerAdvice is a convenience annotation which
combines @ControllerAdvice and @ResponseBody. This annotation
is used along with the @ExceptionHandler annotation to handle
exceptions that occur within the controller.

@SessionAttribute
This annotation is used at method parameter level.
The @SessionAttribute annotation is used to bind the method
parameter to a session attribute. This annotation provides a
convenient access to the existing or permanent session attributes.

@SessionAttributes
This annotation is applied at type level for a specific handler.
The @SessionAtrributes annotation is used when you want to add a
JavaBean object into a session. This is used when you want to keep
the object in session for short lived. @SessionAttributes is used in
conjunction with @ModelAttribute.
Consider this example.

6. How to convert JSON to java object?

Just like above example, conversion between JSON to POJO also involves
only two steps,

 Create instance of [Link]


 Use [Link]() method to convert JSON to POJO

e.g.

//JSON input

String json = "{\"id\":1,\"name\":\"Lokesh Gupta\",\"age\":34,\"location\":\"India\"}";

//Object mapper instance


ObjectMapper mapper = new ObjectMapper();

//Convert JSON to POJO

Employee emp = [Link](json, [Link]);

Example for converting from JSON to Java object


package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class FromJSONToPOJO {

public static void main(String[] args) {

String json = "{\"id\":1,\"name\":\"Lokesh Gupta\",\"age\":34,\"location\":\"India\"}";

ObjectMapper mapper = new ObjectMapper();

try

Employee emp = [Link](json, [Link]);

[Link](emp);

catch (JsonGenerationException e)

[Link]();

} catch (JsonMappingException e) {

[Link]();
} catch (IOException e) {

[Link]();

Output:

Employee [id=1, name=Lokesh Gupta, age=34, location=India]

7. How to create a JDBC INSERT statement

Inserting data into a SQL database table using Java is a simple


two-step process:

1. Create a Java Statement object.


2. Execute a SQL INSERT command through the
JDBC Statement object.

If you’re comfortable with SQL, this is a simple process. When


Sun (now Oracle) created JDBC, they intended to “make the
simple things simple.”

public class JDBCExample {

// JDBC driver name and database URL

static final String JDBC_DRIVER = "[Link]";

static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

// Database credentials

static final String USER = "username";

static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;

Statement stmt = null;

try{

//STEP 2: Register JDBC driver

[Link]("[Link]");

//STEP 3: Open a connection

[Link]("Connecting to a selected database...");

conn = [Link](DB_URL, USER, PASS);

[Link]("Connected database successfully...");

//STEP 4: Execute a query

[Link]("Inserting records into the table...");

stmt = [Link]();

String sql = "INSERT INTO Registration " +

"VALUES (100, 'Zara', 'Ali', 18)";

[Link](sql);

sql = "INSERT INTO Registration " +

"VALUES (101, 'Mahnaz', 'Fatma', 25)";

[Link](sql);

sql = "INSERT INTO Registration " +

"VALUES (102, 'Zaid', 'Khan', 30)";

[Link](sql);

sql = "INSERT INTO Registration " +

"VALUES(103, 'Sumit', 'Mittal', 28)";

[Link](sql);

[Link]("Inserted records into the table...");

}catch(SQLException se){
//Handle errors for JDBC

[Link]();

}catch(Exception e){

//Handle errors for [Link]

[Link]();

}finally{

//finally block used to close resources

try{

if(stmt!=null)

[Link]();

}catch(SQLException se){

}// do nothing

try{

if(conn!=null)

[Link]();

}catch(SQLException se){

[Link]();

}//end finally try

}//end try

[Link]("Goodbye!");

}//end main

}//end JDBCExample

8. Transaction management in case of JDBC

JDBC API provide method setAutoCommit() through which we can


disable the auto commit feature of the connection. We should disable
auto commit only when it’s required because the transaction will not be
committed unless we call the commit() method on connection. Database
servers uses table locks to achieve transaction management and it’s
resource intensive process. So we should commit the transaction as soon
as we are done with it. Let’s write another program where we will use
JDBC transaction management feature to make sure data integrity is not
violated.

[Link]
package [Link];

import [Link];
import [Link];

public class EmployeeJDBCTransactionExample {

public static void main(String[] args) {

Connection con = null;


try {
con = [Link]();

//set auto commit to false


[Link](false);

[Link](con, 1,
"Pankaj");

[Link](con, 1, "Albany
Dr", "San Jose", "USA");

//now commit transaction


[Link]();

} catch (SQLException e) {
[Link]();
try {
[Link]();
[Link]("JDBC Transaction
rolled back successfully");
} catch (SQLException e1) {
[Link]("SQLException in
rollback"+[Link]());
}
} catch (ClassNotFoundException e) {
[Link]();
} finally {
try {
if (con != null)
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}

}
8. How many types of statements are there in JDBC? What are they?
There are 3 types of Statements, as given below:

Statement:

It can be used for general-purpose access to the database. It is useful when you are
using static SQL statements at runtime.

PreparedStatement:

It can be used when you plan to use the same SQL statement many times. The
PreparedStatement interface accepts input parameters at runtime.

CallableStatement:

CallableStatement can be used when you want to access database stored


procedures.

9. Transaction management in Spring and Hibernate.

A few things are not clear from your question. My explanation follows based
on below assumptions -

 You are using spring to create a datasource and session factory


 You are using Java 5 or above and could use annotations.
Here is what your spring configuration would look like.

<bean id="myDataSource" class="[Link]"


destroy-method="close">
<property name="driverClassName" value="[Link]" />
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>

<bean id="mySessionFactory"
class="[Link]">
<property name="dataSource" ref="myDataSource" />
<property name="mappingResources">
<list>
<value>[Link]</value>
</list>
</property>
<property name="hibernateProperties">
<value>
[Link]=[Link]
</value>
</property>
</bean>

<bean id="transactionManager"
class="[Link]">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />


Once this is set up, you could use spring transactional annotations on your
DAO methods as shown below. Spring would take care of starting
transactions, committing your transactions or rolling back your transactions
when exceptions are thrown. If you have business services, you would
ideally use transactional annotations on your services instead of DAOs.

@Transactional(propagation=[Link])
public class MyTestDao extends HibernateDaoSupport {
public void saveEntity(Entity entity){
getHibernateTemplate().save(entity);
}
@Transactional(readOnly=true)
public Entity getEntity(Integer id){
return getHibernateTemplate().get([Link], id);
}
}
Below code shows how transaction management could be achieve using
spring's support for AOP rather than annotations.

<!-- Define your 'myDatasource' bean and 'mySessionFactory' bean as shown in


previous code snippet -->
<!-- Then follow the steps shown below -->

<bean id="transactionManager"
class="[Link]">
<property name="sessionFactory" ref="mySessionFactory" />

<!-- this is the dao object that we want to make transactional -->
<bean id="testDao" class="[Link]" />

<!-- the transactional advice -->


<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>

<!-- ensure that the above transactional advice runs for any execution of
a method in 'daos' package-->
<aop:config>
<aop:pointcut id="allDaoMethods"
expression="execution(* [Link].*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethods" />
</aop:config>

10. Lifecycle of a Servlet.

The web container maintains the life cycle of a servlet instance. Let's see the life cycle
of the servlet:
1. Servlet class is loaded.

2. Servlet instance is created.

3. init method is invoked.

4. service method is invoked.

5. destroy method is invoked.

12. How many types of cloning are there? Explain.


In object-oriented programming, object copying is creating a copy of an existing object,
the resulting object is called an object copy or simply copy of the original [Link]
are several ways to copy an object, most commonly by a copy constructor or cloning.
We can define Cloning as “create a copy of object” Shallow, deep and lazy copy is
related to cloning process
these are actually the ways for creating copy object.
Shallow Copy
 Whenever we use default implementation of clone method we get shallow copy of
object means it creates new instance and copies all the field of object to that new
instance and returns it as object type, we need to explicitly cast it back to our
original object. This is shallow copy of the object.
 clone() method of the object class support shallow copy of the object. If the object
contains primitive as well as nonprimitive or reference type variable in shallow
copy, the cloned object also refers to the same object to which the original object
refers as only the object references gets copied and not the referred objects
themselves.
 That’s why the name shallow copy or shallow cloning in Java. If only primitive type
fields or Immutable objects are there then there is no difference between shallow
and deep copy in Java.
//code illustrating shallow copy

public class Ex {

private int[] data;

// makes a shallow copy of values

public Ex(int[] values) {

data = values;

public void showData() {

[Link]( [Link](data) );

Deep Copy
 Whenever we need own copy not to use default implementation we call it as deep
copy, whenever we need deep copy of the object we need to implement according
to our need.
 So for deep copy we need to ensure all the member class also implement the
Cloneable interface and override the clone() method of the object class.
A deep copy means actually creating a new array and copying over the
values.
// Code explaining deep copy
public class Ex {

private int[] data;

// altered to make a deep copy of values


public Ex(int[] values) {
data = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
data[i] = values[i];
}
}

public void showData() {


[Link]([Link](data));
}
}

13. What is the use of serialVersionUID ?

As I said, when we don't declare SerialVersionUID, as


a static, final and long value in our class, Serialization mechanism
creates it for us. This mechanism is sensitive to many details including
fields in your class, there access modifier, the interface they implement
and even different Compiler implementations, any change on class or
using different compiler may result in different SerialVersionUID, which
many eventually stop reloading serialized data.

It's too risky to rely on Java Serialization mechanism for generating this
id, and that's why it's recommended to declare explicit SerialVersionUID
in your Serializable class. I strongly suggest to read Joshua Bloch's
classic Java title, Effective Java to understand Java Serialization and
issues of incorrect handling it.
14. Difference between Truncate and Delete.
TRUNCATE

 TRUNCATE is a DDL command


 TRUNCATE is executed using a table lock and whole table is locked for
remove all records.
 We cannot use Where clause with TRUNCATE.
 TRUNCATE removes all rows from a table.
 Minimal logging in transaction log, so it is performance wise faster.
 TRUNCATE TABLE removes the data by deallocating the data pages used to
store the table data and records only the page deallocations in the
transaction log.
 Identify column is reset to its seed value if table contains any identity
column.
 To use Truncate on a table you need at least ALTER permission on the table.
 Truncate uses the less transaction space than Delete statement.
 Truncate cannot be used with indexed views.

DELETE

 DELETE is a DML command.


 DELETE is executed using a row lock, each row in the table is locked for
deletion.
 We can use where clause with DELETE to filter & delete specific records.
 The DELETE command is used to remove rows from a table based on
WHERE condition.
 It maintain the log, so it slower than TRUNCATE.
 The DELETE statement removes rows one at a time and records an entry in
the transaction log for each deleted row.
 Identity of column keep DELETE retain the identity.
 To use Delete you need DELETE permission on the table.
 Delete uses the more transaction space than Truncate statement.
 Delete can be used with indexed views.

15. Query to find duplicates rows in sql.

 SELECT name, COUNT(email)


 FROM users
 GROUP BY email
 HAVING COUNT(email) > 1
 So if we have a table
 ID NAME EMAIL
 1 John asd@[Link]
 2 Sam asd@[Link]
 3 Tom asd@[Link]
 4 Bob bob@[Link]
 5 Tom asd@[Link]
 This query will give us John, Sam, Tom, Tom because they all have the
same email.
 However, what I want is to get duplicates with the
same email and name.
 That is, I want to get "Tom", "Tom".
 The reason I need this: I made a mistake, and allowed to insert
duplicate name and email values. Now I need to remove/change the
duplicates, so I need to find them first.
16. Procedures, functions and synonyms and purpose.

 Use the CREATE SYNONYM statement to create a synonym, which is an


alternative name for a table, view, sequence, procedure, stored function,
package, materialized view, Java class schema object, user-defined object
type, or another synonym.
 Synonyms provide both data independence and location transparency.
Synonyms permit applications to function without modification regardless of
which user owns the table or view and regardless of which database holds
the table or view. However, synonyms are not a substitute for privileges on
database objects. Appropriate privileges must be granted to a user before
the user can use the synonym.

 You can refer to synonyms in the following DML


statements: SELECT, INSERT, UPDATE, DELETE, FLASHBACK TABLE, EXPLAI
N PLAN, and LOCK TABLE.

 You can refer to synonyms in the following DDL


statements: AUDIT, NOAUDIT, GRANT, REVOKE, and COMMENT.

17. Connection pooling in spring


Setting up JDBC Database Connection Pool in Spring framework is easy for any Java
application, just matter of changing few configuration in spring configuration [Link] you are
writing core java application and not running on any web or application server like Tomcat or
Weblogic, Managing Database connection pool using Apache Commons DBCP and Commons
Pool along-with Spring framework is nice choice but if you have luxury of having web server and
managed J2EE Container, consider using Connection pool managed by J2EE server those are
better option in terms of maintenance, flexibility and also help to
prevent [Link]:PermGen Space in tomcat by avoiding loading of JDBC
driver in web-app class-loader, Also keeping JDBC connection pool information in Server makes it
easy to change or include settings for JDBC over SSL. In this article we will see how to setup
Database connection pool in spring framework using Apache commons DBCP and commons
[Link]

18. How to retrieve or get the access to servlet context in spring


Spring web application has separate applicaitonContext called WebApplicationContext. In order
to get this, you need a reference of the ServletContext object. Since every Controller in Spring
has access to HttpRequest and HttpResponseobject, we can get ServletContext from request
object, but request object doesn't have direct access to ServletContext prior to Servlet
Specification 3.0, hence you need to first get HttpSession object from request and
than ServletContextobject form session as shown in below code example:

19. How to create primary key in table.

1. In Object Explorer, right-click the table to which you want to add a


unique constraint, and click Design.

2. In Table Designer, click the row selector for the database column
you want to define as the primary key. If you want to select multiple
columns, hold down the CTRL key while you click the row selectors
for the other columns.

3. Right-click the row selector for the column and select Set Primary
Key.
20. What is anonymous class in java how to create it.

A class that have no name is known as anonymous inner class in java. It should be used
if you have to override method of class or interface. Java Anonymous inner class can be
created by two ways:

1. Class (may be abstract or concrete).

2. Interface
3. abstract class Person{
4. abstract void eat();
5. }
6. class TestAnonymousInner{
7. public static void main(String args[]){
8. Person p=new Person(){
9. void eat(){[Link]("nice fruits");}
10. };
11. [Link]();
12. }
13. }

21. Different type of inner classes in java.

Java inner class or nested class is a class which is declared inside the class or
interface.

We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.

Additionally, it can access all the members of outer class including private data
members and methods.

There are two types of nested classes non-static and static nested [Link] non-static
nested classes are also known as inner classes.

o Non-static nested class (inner class)

1. Member inner class

2. Anonymous inner class

3. Local inner class


o Static nested class

22. How Garbage Collector will work.

 Object creation is faster because global synchronization with the


operating system is not needed for every single object. An
allocation simply claims some portion of a memory array and moves
the offset pointer forward (see Figure 2.1). The next allocation
starts at this offset and claims the next portion of the array.
 When an object is no longer used, the garbage collector reclaims
the underlying memory and reuses it for future object allocation.
This means there is no explicit deletion and no memory is given
back to the operating system.

23. What is [Link]().

The [Link]() method runs the garbage collector. Calling this


suggests that the Java Virtual Machine expend effort toward recycling unused
objects in order to make the memory they currently occupy available for quick
reuse

24. What is difference between servletconfig and servlet context.

ServletConfig
 ServletConfig available in [Link].*; package
 ServletConfig object is one per servlet class
 Object of ServletConfig will be created during initialization process of the
servlet
 This Config object is public to a particular servlet only
 Scope: As long as a servlet is executing, ServletConfig object will be
available, it will be destroyed once the servlet execution is completed.
 We should give request explicitly, in order to create ServletConfig object
for the first time
 In [Link] – <init-param> tag will be appear under <servlet-class> tag
Here's how it looks under [Link] : (Source)
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-
value>
</init-param>
</servlet>
ServletContext
 ServletContext available in [Link].*; package
 ServletContext object is global to entire web application
 Object of ServletContext will be created at the time of web application
deployment
 Scope: As long as web application is executing, ServletContext object will
be available, and it will be destroyed once the application is removed
from the server.
 ServletContext object will be available even before giving the first request
In [Link] – <context-param> tag will be appear under <web-app> tag
Here's how it looks under [Link] :

<context-param>
<param-name>globalVariable</param-name>
<param-value>[Link]</param-value>
</context-param>

25. How you will create a sequence

Use the CREATE SEQUENCE statement to create a sequence, which


is a database object from which multiple users may generate
unique integers. You can use sequences to automatically
generate primary key values.

26. What is the purpose of @join column annotation

The @OneToMany annotation is used to create the one-to-many relationship


between the Student and Phone entities. The @JoinTable annotation is used
to create the STUDENT_PHONE link table and @JoinColumn annotation is
used to refer the linking columns in both the tables. Phone class is used to
create the PHONE table

You might also like