18
UNIT- 4 Q. No Question Description Course Outcom e Mark s Difficul ty level 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define ejb Create() and EjbPostCreate ()? CO4 2 Low 4. Define EAR, WAR and JAR ? CO4 2 Low 5. What is the difference between stateful and stateless session beans? CO4 5 Low 6. When is bean managed persistence used? CO4 5 Low 7. What do you mean by Introspection of a bean? Explain with suitable example? How persistence is important for a Java Bean? CO4 5 Medium 8. Write a note on Struts Framework. CO4 5 Medium 9. What do you mean by JDBC driver in Java? Explain web database. How do you manage a database through web? Explain with the help of example. CO4 5 Medium 10. What is EJB? Explain its types? CO4 5 Medium 11. What are jar files? Explain its advantage? Write the command for creating jar file? CO4 5 High 12. Explain in detail the creation, instantiation and usage of java beans objects. CO4 5 High 13. Enlist the CallBack methods of Entity Bean. CO4 5 Medium 14. How can I connect MySQL or Oracle with Java? CO4 10 Medium 15. What is the limitation of PreparedStatement and how to overcome it? CO4 10 High 16. What does Java Database Connectivity Architecture (JDBC Architecture) mean? CO4 10 Medium 17. What are the main steps in java to make JDBC connectivity? CO4 10 Medium 18. What are different types of Statement? CO4 10 Medium 19. What are java beans explain with an example. Give properties of java beans CO4 10 Medium 20. What is the difference between EJB and Java beans? CO4 10 Medium

Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

Q. No Question Description Course

Outcom

e

Mark

s

Difficul

ty level

1. What are entity beans?

CO4 2 Low

2. How can one EJB be called from within another

EJB?

CO4 2 Low

3. Define ejb Create() and EjbPostCreate ()?

CO4 2 Low

4. Define EAR, WAR and JAR ?

CO4 2 Low

5. What is the difference between stateful and stateless

session beans?

CO4 5 Low

6. When is bean managed persistence used? CO4 5 Low

7. What do you mean by Introspection of a bean?

Explain with suitable example? How persistence is

important for a Java Bean?

CO4 5 Medium

8. Write a note on Struts Framework. CO4 5 Medium

9. What do you mean by JDBC driver in Java? Explain

web database. How do you manage a database

through web? Explain with the help of example.

CO4 5 Medium

10. What is EJB? Explain its types?

CO4 5 Medium

11. What are jar files? Explain its advantage? Write the

command for creating jar file?

CO4 5 High

12. Explain in detail the creation, instantiation and usage

of java beans objects.

CO4 5 High

13. Enlist the CallBack methods of Entity Bean.

CO4 5 Medium

14. How can I connect MySQL or Oracle with Java? CO4 10 Medium

15. What is the limitation of PreparedStatement and how

to overcome it?

CO4 10 High

16. What does Java Database Connectivity Architecture

(JDBC Architecture) mean?

CO4 10 Medium

17. What are the main steps in java to make JDBC

connectivity?

CO4 10 Medium

18. What are different types of Statement?

CO4 10 Medium

19. What are java beans explain with an example. Give

properties of java beans

CO4 10 Medium

20. What is the difference between EJB and Java beans? CO4 10 Medium

Page 2: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

Solution

1. What are entity beans?

An entity bean, in the context of Java Platform 2, Enterprise Edition (J2EE), represents the

business objects retained at the end of a session in a persistent storage

mechanism. Business objects may include items like customer name, account number and/or

account balance, etc. In J2EE, a relational database is a persistent storage mechanism. In a

relational database, there is a table for each entity bean and every bean instance corresponds

to a particular table row.

The following are characteristics differentiating entity beans from session beans:

Entity beans are retained after the end of a session, unlike session beans.

Entity beans permit shared data access.

Entity beans have a primary key or a unique identifier.

2. How can one EJB be called from within another EJB?

An EJB can be called within another EJB by using JNDI which can be used for locating the

Home Interface and acquiring the instance.

3. Define ejb Create() and EjbPostCreate ()?

When the method is called before the persistence storage is written with the bean state, it is

ejbCreate ().

When the method is called after the persistence storage is written with the bean state, it is

ejbPostCreate ().

4. Define EAR, WAR and JAR ?

JAR files contain all EJB classes.

WAR files contain all servlets, web component pages, gif, html, beans, applets, classes and

classes.

EAR files contain both JAR and WAR files.

5. What is the difference between stateful and stateless session beans?

Stateful session beans:

A Stateful session bean is an client application.

It maintains conversational state when used by a client.

Conversational state is not written to a database; it's a state that is kept in memory

while a client uses a session.

Maintaining conversational state allows a client to carry on a conversation with a

bean.

Page 3: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

Conversational state is only kept for as long as the client application is actively using

the bean.

Stateful session bean are not sharing among clients; they are dedicated to the same

client for the life of the bean.

Stateless session beans:

A Stateless session bean is a collection of related services, each represented by a

method; the bean maintains no conversational state from one method invocation to the

next.

Each method is used completely independent and uses only the data passed in its

parameters.

6. When is bean managed persistence used?

Bean Managed Persistence is used as an alternative to container managed persistence when

the deployment tools are inadequate for mapping the bean instance's state to the database.

Bean Managed Persistence is preferred by the enterprise developers for creating custom

beans for their business system.

7. What do you mean by Introspection of a bean? Explain with suitable example?

How persistence is important for a Java Bean?

Introspection is the ability to ask a JavaBean component what properties and events it

supports. By default, introspection is supported by reflection, where you name methods with

certain naming patterns, like set/getProperty() and add/removeListener(). You can also

explicitly expose the bean's behavior through creation of a BeanInfo class related to the bean.

The BeanInfo class can be used for many things, like setting up an icon for the component

when used in a bean builder tool like JBuilder, limiting the properties available, or mapping

methods to properties that don't follow standard naming patterns.

Purpose of Introspection

A growing number of Java object repository sites exist on the Internet in answer to the

demand for centralized deployment of applets, classes, and source code in general. Any

developer who has spent time hunting through these sites for licensable Java code to

incorporate into a program has undoubtedly struggled with issues of how to quickly and

cleanly integrate code from one particular source into an application.

The way in which introspection is implemented provides great advantages, including:

1. Portability - Everything is done in the Java platform, so you can write components

once, reuse them everywhere. There are no extra specification files that need to be

maintained independently from your component code. There are no platform-specific

issues to contend with. Your component is not tied to one component model or one

proprietary platform. You get all the advantages of the evolving Java APIs, while

maintaining the portability of your components.

Page 4: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

2. Reuse - By following the JavaBeans design conventions, implementing the

appropriate interfaces, and extending the appropriate classes, you provide your

component with reuse potential that possibly exceeds your expectations.

The following example represents code to perform introspection:

import java.beans.BeanInfo;

import java.beans.Introspector;

import java.beans.IntrospectionException;

import java.beans.PropertyDescriptor;

public class SimpleBean

{

private final String name = "SimpleBean";

private int size;

public String getName()

{

return this.name;

}

public int getSize()

{

return this.size;

}

public void setSize( int size )

{

this.size = size;

}

public static void main( String[] args )

throws IntrospectionException

{

BeanInfo info = Introspector.getBeanInfo( SimpleBean.class );

for ( PropertyDescriptor pd : info.getPropertyDescriptors() )

System.out.println( pd.getName() );

}

}

This example creates a non-visual bean and displays the following properties derived from

the BeanInfo object:

class

name

size

Note that a class property was not defined in the SimpleBean class. This property was

inherited from the Object class. To get properties defined only in the SimpleBean class, use

the following form of the getBeanInfo method:

Page 5: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

Introspector.getBeanInfo( SimpleBean.class, Object.class );

Bean Persistence

A bean has the property of persistence when its properties, fields, and state information are

saved to and retrieved from storage. Component models provide a mechanism for persistence

that enables the state of components to be stored in a non-volatile place for later retrieval.

The mechanism that makes persistence possible is called serialization. Object serialization

means converting an object into a data stream and writing it to storage. Any applet,

application, or tool that uses that bean can then "reconstitute" it by deserialization. The object

is then restored to its original state.

For example, a Java application can serialize a Frame window on a Microsoft Windows

machine, the serialized file can be sent with e-mail to a Solaris machine, and then a Java

application can restore the Frame window to the exact state which existed on the Microsoft

Windows machine.

Any applet, application, or tool that uses that bean can then "reconstitute" it by

deserialization.

All beans must persist. To persist, your beans must support serialization by implementing

either the java.io.Serializable (in the API reference documentation) interface, or the

java.io.Externalizable (in the API reference documentation) interface. These interfaces offer

you the choices of automatic serialization and customized serialization. If any class in a

class's inheritance hierarchy implements Serializable or Externalizable, then that class is

serializable.

8. Write a note on Struts Framework.

The struts framework is an open source framework for creating well-structured web based

applications. The struts framework is based on the Model View Controller (MVC) paradigm

which distinctly separates all the three layers - Model (state of the application), View

(presentation) and Controller (controlling the application flow). This makes struts different

from conventional JSP applications where sometimes logic, flow and UI are mingled in a

Java Server Page.

The struts framework is a complete web framework as it provides complete web form

components, validators, error handling, internationalization, tiles and more. Struts framework

provides its own Controller component. It integrates with other technologies for both Model

and View components. Struts can integrate well with Java Server Pages (JSP), Java Server

Faces (JSF), JSTL, Velocity templates and many other presentation technologies for View.

For Model, Struts works great with data access technologies like JDBC, Hibernate, EJB and

many more.

Page 6: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

How Struts Works

When the framework’s controller receives a request, it uses the configuration file, struts-

config.xml to find out the correct routing information. Based on the information configured

in the configuration file, it internally invokes an Action class. The Action class interacts with

the Model (also called the business layer) to access or update the underlying data in database/

file. The framework includes ActionForm classes to transfer data between Model and View.

Creating a Hello World Application using Struts:

For the purposes of this tutorial, we will be using the following tools and software.

1. Eclipse Juno - download

2. Apache Tomcat version 6x or greater

3. JDK version 6 or greater

Step 1:

Install all required tools and software.

Step 2:

Go to Java EE perspective in eclipse and create a new Dynamic Web Application.

Go to File >> New >> Dynamic Web Project

In the dialog that appears, enter the name of the Struts project you would like to create. The

name here is “StrutsHelloWorld”.

Select the target runtime. If there are no target runtimes available already, then click “New

Runtime…” button. The following dialog will appear

Select a runtime available in the computer., we select Apache Tomcat v7.0 and click the next

button. dialog will appear.

Select the tomcat installation directory and JRE and click finish.

Click Finish.

The project will now appear on the “Project Explorer” window.

Step 3:

Add the required struts library files. These libraries are important to run the application, thus

all the libraries should be included..

Step 4:

Next comes the most important part of in creating the application, writing the code.

Page 7: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

As with any web application, a deployment descriptor is required for this struts application.

Here is the output StrutsHelloWorld project..

9. What do you mean by JDBC driver in Java? Explain web database. How do you

manage a database through web? Explain with the help of example.

JDBC drivers are client-side adapters (installed on the client machine, not on the server) that

convert requests from Java programs to a protocol that the DBMS can understand. There are

4 types of JDBC drivers:

1. Type-1 driver or JDBC-ODBC bridge driver

2. Type-2 driver or Native-API driver

3. Type-3 driver or Network Protocol driver

4. Type-4 driver or Thin driver

Type-1 driver

Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database.

The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.

Type-1 driver is also called Universal driver because it can be used to connect to any of the

databases.

Page 8: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

As a common driver is used in order to interact with different databases, the data

transferred through this driver is not so secured.

The ODBC bridge driver is needed to be installed in individual client machines.

Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.

Type-2 driver

The Native API driver uses the client -side libraries of the database. This driver converts

JDBC method calls into native calls of the database API. In order to interact with different

database, this driver needs their local API, that’s why data transfer is much more secure as

compared to type-1 driver.

Driver needs to be installed separately in individual client machines

The Vendor client library needs to be installed on client machine.

Type-2 driver isn’t written in java, that’s why it isn’t a portable driver

Type-3 driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls

directly or indirectly into the vendor-specific database protocol. Here all the database

connectivity drivers are present in a single server, hence no need of individual client-side

installation.

Type-3 drivers are fully written in Java, hence they are portable drivers.

No client side library is required because of application server that can perform many

tasks like auditing, load balancing, logging etc.

Network support is required on client machine.

Maintenance of Network Protocol driver becomes costly because it requires database-

specific coding to be done in the middle tier.

Type-4 driver

Type-4 driver is also called native protocol driver. This driver interact directly with database.

It does not require any native database library, that is why it is also known as Thin Driver.

Does not require any native library and Middleware server, so no client-side or server-

side installation.

It is fully written in Java language, hence they are portable drivers.

A Web database is a database application designed to be managed and accessed through the

Internet. Website operators can manage this collection of data and present analytical results

based on the data in the Web database application. Databases first appeared in the 1990s, and

have been an asset for businesses, allowing the collection of seemingly infinite amounts of

data from infinite amounts of customers

Cloudways Database Manager to manage your applications databases from within the

console.

Page 9: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

Cloudways Database Manager is not suitable for managing large databases (i.e. larger than

200MB). To manage large databases, please use other Cloudways supported methods such as

MySQL remote connections or SSH tunnel for MySQL clients.

Step 1: Go to Application Management

Log into the Cloudways Platform with your credentials. Click on Applications in the top

menu bar and then select your target application from the list.

Step 2: Launch the Database Manager

Under Application Management, click on Access Details and check the MySQL Access

option.

To launch the manager, click on Launch Database Manager.

The Database Manager is secured using a self-signed certificate. Although it is perfectly

valid, this will generate a warning on your browser that you can safely ignore (don’t ignore it

when connecting to other sites unless you know what you are doing).

Step 3: Database Manager

The Cloudways Database Manager will open in a new tab and you can start working with

your database.

10. What is EJB? Explain its types?

EJB is an acronym for enterprise java bean. It is a specification provided by Sun

Microsystems to develop secured, robust and scalable distributed applications.

To run EJB application, you need an application server (EJB Container) such as Jboss,

Glassfish, Weblogic, Websphere etc. It performs:

a. life cycle management,

b. security,

Page 10: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

c. transaction management, and

d. object pooling.

EJB application is deployed on the server, so it is called server side component also.

EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from

Java Bean, RMI and Web Services.

EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from

Java Bean, RMI and Web Services.

11. What are jar files? Explain its advantage? Write the command for creating jar

file?

JAR files are packaged with the ZIP file format, so you can use them for tasks such as

lossless data compression, archiving, decompression, and archive unpacking. These tasks are

among the most common uses of JAR files, and you can realize many JAR file benefits using

only these basic features.

Even if you want to take advantage of advanced functionality provided by the JAR file

format such as electronic signing, you'll first need to become familiar with the fundamental

operations.

To perform basic tasks with JAR files, you use the Java Archive Tool provided as part of the

Java Development Kit (JDK). Because the Java Archive tool is invoked by using

the jar command, this tutorial refers to it as 'the Jar tool'.

As a synopsis and preview of some of the topics to be covered in this section, the following

table summarizes common JAR file operations:

Common JAR file operation

Operation Command

To create a JAR file jar cf jar-file input-file(s)

12. Explain in detail the creation, instantiation and usage of java beans objects.

Create a java bean

public class SampleBean

{

private String firstName = "";

private String lastName = "";

public void setFirstName(String name)

{

firstName = name;

}

Page 11: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

public void setLastName(String name)

{

lastName = name;

}

public String getFullName()

{

return firstName + " " + lastName;

}

}

Use bean inside the jsp file

Instantiating Bean Objects The useBean standard JSP action can be used to instantiate a bean

object within a JSP document. Most of this subsection describes some of the common uses of

this action. First, though, let me mention that bean objects are often instantiated by servlets

rather than JSP documents and stored by the servlets as scoped variables, and in such cases

useBean is not needed. For example, the code; creates a TestBean object and assigns it to the

session attribute (scoped variable) testBean.

import my.TestBean; ...

HttpSession session = request.getSession();

TestBean testBean = new TestBean();

session.setAttribute("testBean", testBean);

If a JSP document is subsequently executed in the same session, then the EL expression

sessionScope.testBean provides a direct reference to the object without the need for a

useBean element. That said, there are times when useBean can be handy, so we’ll cover it

next. First, if an appropriate JavaBeans instance exists when useBean is invoked, then it will

generally do nothing. For instance, the markup will create the variable testBean (with session

rather than the default page scope) only if it does not already exist. If the testBean variable

already exists in the specified scope and refers to an instance of my.TestBean or to an object

that could be assigned to a my.TestBean variable, then this action does nothing. If the

variable exists but has a value that is not an object that can be assigned to a my.TestBean

variable, an error will occur. So if our previous example is modified to

13. Enlist the CallBack methods of Entity Bean.

public interface javax.ejb.EntityBean extends javax.ejb.EnterpriseBean {

public abstract void ejbRemove();

public abstract void ejbActivate();

public abstract void ejbStore();

public abstract void ejbPassivate(); public abstract void setEntityContext(EntityContext ctx);

public abstract void unsetEntityContext(); public abstract void ejbLoad();

}

14. How can I connect MySQL or Oracle with Java?

Page 12: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

//for MySQL {

try {

Class.forName ("com.mysql.jdbc.Driver");

con=DriverManager.getConnection ("jdbc: mysql://localhost:3306/dbanme", "username",

"password");

Statement st=con.createstatement ();

Resultset rs=st.executeQuery ("select * from user");

rs.next (); catch (ClassNotFoundException e) {

System.err.println ("ClassNotFoundException in get Connection," + e.getMessage()); }

catch (SQLException e) {

System.err.println ("SQLException in getConnection," + e.getMessage ()) ;}

//for oracle

{

try

{

Class.forName ("oracle.jdbc.driver.OracleDriver");

con= DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:dbname",

"username", "passw

ord");

Statement st=con.createstatement();

Resultset rs=st.executeQuery("select * from user");

Rs.next();

} catch (ClassNotFoundException e) {

System.err.println("ClassNotFoundException in get Connection," +e.getMessage()); }

catch (SQLException e) {

System.err.println("SQLException in getConnection, " + e.getMessage()); } return con; }

Page 13: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

Code explanation

Class.forName creates an instance of JDBC driver and register with DriverManager.

getConnection () method always establishes a connection to a database.

We need to create a Statement object from above connection object. The statement will return

resultset object. ResultSet.next () means If the result set is still returning row.

15. What is the limitation of PreparedStatement and how to overcome it?

One of the limitation of PreparedStatement is that we can’t use it directly with IN clause

statements. Some of the alternative approaches to use PreparedStatement with IN clause are;

1. Execute Single Queries – very slow performance and not recommended

2. Using Stored Procedure – Database specific and hence not suitable for multiple database

applications.

3. Creating PreparedStatement Query dynamically – Good approach but looses the benefit

of cached PreparedStatement.

4. Using NULL in PreparedStatement Query – A good approach when you know the

maximum number of variables inputs, can be extended to allow unlimited parameters by

executing in parts.

16. What does Java Database Connectivity Architecture (JDBC

Architecture) mean?

The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.

In the two-tier model, a Java application talks directly to the data source. This requires a

JDBC driver that can communicate with the particular data source being accessed. A user's

commands are delivered to the database or other data source, and the results of those

statements are sent back to the user. The data source may be located on another machine to

which the user is connected via a network. This is referred to as a client/server configuration,

with the user's machine as the client, and the machine housing the data source as the server.

The network can be an intranet, which, for example, connects employees within a

corporation, or it can be the Internet.

Page 14: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

In the three-tier model, commands are sent to a "middle tier" of services, which then sends

the commands to the data source. The data source processes the commands and sends the

results back to the middle tier, which then sends them to the user. MIS directors find the

three-tier model very attractive because the middle tier makes it possible to maintain control

over access and the kinds of updates that can be made to corporate data. Another advantage is

that it simplifies the deployment of applications. Finally, in many cases, the three-tier

architecture can provide performance advantages.

Figure 2: Three-tier Architecture for Data Access.

Until recently, the middle tier has often been written in languages such as C or C++, which

offer fast performance. However, with the introduction of optimizing compilers that translate

Java bytecode into efficient machine-specific code and technologies such as Enterprise

JavaBeans™, the Java platform is fast becoming the standard platform for middle-tier

development. This is a big plus, making it possible to take advantage of Java's robustness,

multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code,

the JDBC API is being used more and more in the middle tier of a three-tier architecture.

Some of the features that make JDBC a server technology are its support for connection

pooling, distributed transactions, and disconnected rowsets. The JDBC API is also what

allows access to a data source from a Java middle tier.

17. What are the main steps in java to make JDBC connectivity?

Answer : Another beginner level JDBC Interview question, mostly asked on telephonic

interviews. Here are main steps to connect to database.

1. Load the Driver: First step is to load the database specific driver which communicates

with database.

2. Make Connection: Next step is get connection from the database using connection

object, which is used to send SQL statement also and get result back from the

database.

3. Get Statement object: From connection object we can get statement object which is

used to query the database

Page 15: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

4. Execute the Query:Using statement object we execute the SQL or database query and

get result set from the query.

5. Close the connection:After getting resultset and all required operation performed the

last step should be closing the database connection.

18. What are different types of Statement?

Answer : This is another classical JDBC interview question. Variants are Difference between

Statement, PreparedStatemetn and CallableStatement in Java. Statement object is used to

send SQL query to database and get result from database, and we get statement object from

connection object.

There are three types of statement:

1. Statement: it’s a commonly used for getting data from database useful when we are using

static SQL statement at runtime. it will not accept any parameter.

Statement stmt = conn.createStatement( );

ResultSet rs = stmt.executeQuery();

2. PreparedStatement: when we are using same SQL statement multiple time its is useful and

it will accept parameter at runtime.

String SQL = "Update stock SET limit = ? WHERE stockType = ?";

PreparedStatement pstmt = conn.prepareStatement(SQL);

ResultSet rs = pstmt.executeQuery();

To learn more about PreparedStatement, see What is PreparedStatement in Java and Benefits

3. Callable Statement: when we want to access stored procedures then callable statement are

useful and they also accept runtime parameter. It is called like this

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

ResultSet rs = cs.executeQuery();

19. What are java beans explain with an example. Give properties of java beans.

A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.

o It should be Serializable.

Page 16: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

o It should provide methods to set and get the values of the properties, known as getter

and setter methods.

It is a reusable software component. A bean encapsulates many objects into one object so that

we can access this object from multiple places. Moreover, it provides easy maintenance.

Simple example of JavaBean class

//Employee.java

package mypack;

public class Employee implements java.io.Serializable{

private int id;

private String name;

public Employee(){}

public void setId(int id){this.id=id;}

public int getId(){return id;}

public void setName(String name){this.name=name;}

public String getName(){return name;}

}

To access the JavaBean class, we should use getter and setter methods.

package mypack;

public class Test{

public static void main(String args[]){

Employee e=new Employee();//object is created

e.setName("Arjun");//setting value to the object

System.out.println(e.getName());

}

}

JavaBean Properties

A JavaBean property is a named feature that can be accessed by the user of the object. The

feature can be of any Java data type, containing the classes that you define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features are

accessed through two methods in the JavaBean's implementation class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would be getFirstName() to

read that property. This method is called the accessor.

Page 17: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

2. setPropertyName ()

For example, if the property name is firstName, the method name would be setFirstName() to

write that property. This method is called the mutator.

Advantages of JavaBean

The following are the advantages of JavaBean

o The JavaBean properties and methods can be exposed to another application.

o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.

o Creating the setter and getter method for each property separately may lead to the

boilerplate code.

20. What is the difference between EJB and Java beans?

JavaBeans :

- JavaBeans may be visible or nonvisible at runtime.

- JavaBeans are intended to be local to a single process and are primarily intended to run on

the client side.

- Although one can develop server-side JavaBeans, it is far easier to develop them using the

EJB specification instead.

- JavaBean is a component technology to create generic java components that can be

composed together into applets and applications.

- JavaBeans have an external interface called the properties interface, which allows a builder

tool to interpret the functionality of the bean.

- JavaBeans may have BeanInfo classes,property editors or Customizers.

- JavaBeans have no types.

- No explicit support exists for transactions in JavaBeans.

- Component bridges are available for JavaBeans.

EJB :

Page 18: Q. No Question Description Course Mark Difficul Outcom s ...€¦ · 1. What are entity beans? CO4 2 Low 2. How can one EJB be called from within another EJB? CO4 2 Low 3. Define

UNIT- 4

- An EJB is a nonvisual, remote object.

- EJB's are remotely executable components or business objects that can be deployed only on

the server.

- Even though EJB is a component technology, it neither builds upon nor extends the original

JavaBean specification.

- EJBs have a deployment descriptor that describes its functionality to an external builder tool

or IDE.

- EJB's have no concept of BeanInfo classes, property editors or customizers and provide no

additional information other than that described in the deployment descriptor.

- EJBs are of two types - session beans and entity beans.

- EJB's may be transactional and the EJB servers provide the transactional support.

- An EJB cannot be deployed as an ActiveX control because ActiveX controls are intended to

run at the desktop and EJB's are server side components. However CORBA-IIOP

compatibility via the EJB-to-CORBA mapping is defined by the OMG