Академический Документы
Профессиональный Документы
Культура Документы
Ans: Most of the time this EJB interview questions is the first questions asked to interviewee, mostly
to check how he responds and how its is different than traditional Java beans. Enterprise java bean is
a server side component which runs on application server or we call container, developed for the
purpose of distributed and enterprise level application .container will provide support for system
level services like Transaction Management, security which make developer task easy and he can
focus on business logic.
This is another beginner level EJB interview questions mostly asked in telephonic interviews and
appeared in 2 to 3 years experience level interviews. Mainly three types of EJB, Entity Bean, Session
Bean and Message Driven Bean(MDB).
Types of EJB:
Entity Bean: it represents an entity which is mapped with database or we can say it makes OR object
Relational mapping with Database. Entity bean typically represent table in RDBMS and each instance
represent row in the table.
• CMP Entity bean: Container managed entity bean its responsibility of container to manage
the bean persistence behavior.
Session bean: Session bean is responsible for developing business logic it makes the client server
relationship so session beans exist till there is a session exist between client and server, it doesn’t
contain persistent business concept.
For example if we are validating the credit card we can use stateless session bean.
• Stateful session bean: stateful session bean maintain the conversational state of client over
the series of method call before the bean instance goes to passive state conversational state is saved
to persistence area like Hard disk and again when same client send a request and bean instance
come into the active state it will come out from hard disk to main memory.
For Example when we do online banking transaction ,online reservation we use stateful session
bean
Message Driven Beans: these beans are work as a listener for messaging services like JMS .
One for EJB interview questions which is asked in Junior level interviews. I have not seen this EJB
question appeared on more senior level interviews but its good to remember life cycle as here you
have chance to show how much EJB you know in depth.
First stage is Does Not Exist Stage t hen Container creates the instance of EJB and call
SetEntityContext() method which will set all entity context to bean and now it will become available
on pool ,to get a particular identity of an EJB object it has to move from Pooled stage to ready stage
which is done by calling the create () method which in turns call ejbCreate() and ejbPostCreate()
method .
There is another way by which directly entity bean can move to pooled stage to ready stage that’s is
call ejbActivate() method.now we are ready to invoke the business method of entity bean .After
completion of business method if we want to move again in pooled stage from ready stage we can
call remove() method which in turns call ejbRemove() or directly call ejbPassivate () method.
At the end container remove the instance of EJBfrom pool and call unSetEntityContext().
Life Cycle of Stateful Session Bean :
Stateful session beans life cycle starts when client call create() method.The container create the
instance of session bean and call setSessionContext() and ejbCreate() method
Now the stateful session bean is ready to serve the client request after serving the request if it is not
used after a long time container can move this bean to passive stage by calling the ejbPassivate()
method.similarly when bean is in passive stage and client invoke the business method the container
call ejbActivate() method to move bean from passive stage to active or ready stage.
At the end of life cycle client call remove() method and container will call ejbRemove() method and
bean is ready for garbage collection.
Stales session bean has short life cycle it can have two stage does not exist and ready stage. ejb
container create the instance of stateless session bean and call setSessionContext () and ejbCreate()
method.Now the bean is ready to invoke business method on this.it will not maintain the state so
remove () method is been called after completion of business method which in turns call ejbRemove
() and now its ready for garbage collection.
MDBs have same life cycle like stateless session bean. setMessageDrivenContext() method and
ejbCreate() method is called by container to create the instance of MDB.now its ready to receive
message .and at the end of lifecycle client will call remove () method
which in turns call ejbRemove () and now its ready for garbage collection.
This is one of the tricky EJB interview questions which makes you think and some time left you
stunned with feeling like “ Ah , I haven’t thought about it”.
Ans .Purpose of Static initializer block is to initialize some static fields before any execution of
constructor or method or we can say creation of object. According to EJB Spec it’s a violation if static
field are used and they are non final .
“EJB Spec”
Enterprise bean are not allowed to read or write the non final fields.
But technically,from the point of java its correct but if in EJB we use static initializer block to initialize
static field then because EJB components are used in distributed environment mean to say if single
JVM then it will be ok but if run on different JVM then it will be a problem if we change or update
the value in on environment then only the instance running on same JVM have new value .that’s
why static blocks are avoided and also all static field should be final.
Another tricky EJB interview question, I love to ask this kind of question because it shows real
knowledge of EJB which is important to avoid mistakes while writing enterprise Java application.
Ans: No, Not possible because EJBs are created and managed by container and if in ejbs we allow
threading containers life cycle methods will be interrupted by us and also the purpose of EJB is to
perform business logic not to controlling a system or implementation level functioning so container
will manage the thread and developer can concentrate on business logic.
This EJB interview question is neither tough nor easy, as most of Java programmer familiar with
concept of connection pooling that makes it easy but how EJB container does that is something you
want to hear from interviewee.
Ans: Connection pooling is one of the Advance feature of container which enhanced our application
performance .Using connection pooling mechanism client are not required to create every time
connection object to interact with database .Here in pool objects are already available Whenever a
client request for a database connection then an instance is picked from the connection pool to get
an access to database and when user complete with his work instance is returned to connection
pool. There is a limit specified by App server administrator for the availability of number of
connections and beyond a specified limit a predefined number increases numbers of connection
pool instances. When demand goes back to normal then access amount of connection pool instances
are removed.
Question 7: what is Session facade?
This is the most popular interview questions asked in EJB in connection of Session Bean. Session
facade not only touch concept of EJB but also it checks design patterns knowledge of interviewee.
Ans: Session Façade is one of the design pattern which is used in EJB component in this pattern
session beans are used as a wrapper classes for entity bean and using session bean we interact with
Entity bean .it will give clean approach towards client access to bean components and also reduce
network calls so as to make the whole system of high performance.
This kind of EJB questions mostly askedin telephonic interviews but believe me its not easy to
answer if you have not really used transaction management feature of EJB. Its easy to mug all these
transaction attribute and spill in interview but once interviewer asked cross question you will most
likely cripple.
Ans: Transaction is group of operation or work which should be performed either completely or
none to maintain the data integrity. All transaction must have ACID property(atomicity
,consistency,integrity,durability) so transaction can be said completed if we commit on successful
execution and rollback on unsuccessful execution.
Transaction Attribute conveys to the container the intended transactional behavior of the associated
EJB component's method.
Required: if required attribute is associated with Method then new Transaction context may or may
not be created, means if method is already associated with transaction context then no new
transaction context should be created.
Requires New: if Requires New attribute is associated with Method then always new Transaction
context may be created.
NotSupported:if Method is Associated with this Attribute then method is a not a part of transaction.
Supported:if a Method is Associated with this transaction Attribute then method will act as Not
supported if calling component is not associated with transaction and if calling component is
associated with transaction then act as a required Attribute.
Mandatory:if a method is Associated with this attribute then always be called from calling
component transaction context.
Never: if a method is Associated with this attribute then never be called from calling component
transaction context.
One more popular EJB interview question, not seen though it for some time but still an important
questions on EJB to prepare.
Ans:Both of these methods are used in context of entity bean for the purpose of synchronizing the
instance variable to corresponding value store in the database. ejbLoad method load or refresh the
instance variable from the database and ejbStore method writes variables value back to the
database.
Question 10: What is the difference between JNDI context, Initial context, session context and ejb
context.
JNDI questions most likely asked in any EJB interview so be prepare for that as well.
Ans:
Session Context:it has all the information available which is required to session bean from
container.
EjbContext:it contain information which is required to both session and entity bean.
1. Which of the beans available in EJB 3 are only called by clients ?
Session and Singleton (EJB 3.1) beans are the ones who encapsulate the business logic which is why
it is the only bean which is called by clients. Other beans like MDB and Entity beans are called by
session and singleton beans to complete the business requirement.
2. Why is it so to make the session beans into two parts one with interface and the other as
impl to the interface ? Or why session beans should be used through business interface ? ( EJB 3.0
Specific ).
This approach promotes loose coupling since implementation classes can easily be swapped out
without a lot of code changes.But in recent EJB 3.1 specification you don't need to implement a
business interface for faster development.
An interface through which a client invokes the bean is called a business interface. There are three
types of business interfaces available in EJB 3 : Local, Remote and WebService.
4. Now in latest version of EJB the dependency injection is available , Do we still need JNDI
lookups for getting the business interface ?
Yes, Our so called dependency Injection is actually a wrapper over JNDI lookups. The Injected object
is actually JNDI looked up by the container and injected to the desired place. What happens inside, is
that the same old JNDI lookup (which is done by the container) for our convenience.
There are places where you will have to use JNDI lookup , where container is not available. Means
that, if the container is not there then how would you get the remote object ? The only answer is
JNDI.
A life cycle method can be of any name and any specifier , a return type void and no argument ex :
private void cleanup();
Appropriate annotation should be used. ex: @PostConstruct, @PreDestory in case of stateless beans
and additional @PrePassivate and @PostActivate for stateful session beans.
It is not necessary to have a life cycle method declared in the business interfaces.Only
implementation in the business implemented classes (ie Bean classes) is required.
10
11
12
@EJB
helloUser.sayHello();
....
...
JSP however is not supported to inject. And moreover one should not call/invoke EJB in JSP , since it
violates design principles.But if one must then , following code should help :
10
11
12
13
14
15
16
17
foo.HelloWorldLocal" %>
<%!
//declare a "global" reference to an instance of the home interface of the session bean
HelloWorldLocal helloUser=null;
public void jspInit()
helloUser = (HelloWorldLocal)PortableRemoteObject.narrow(ref,HelloWorldLocal.class);
%>
<%
helloUser.sayHello("SomeName);
%>
The answer is NO. Not at least the EJB way. EJB doesn't retain information in stateless session bean.
However you can trick the container by using external class serialized with state information and
stored in the file system and upon the next call to the method ( where in you are expecting state of
earlier call) you can read the serialized data back.Also you need to make sure the data consistency
between client calls and so many other things. With this trick you will end up doing what EJB
container does for a stateful beans. If you still feel this trick is a good idea, be my guest .
Yes. A stateless session bean can have instance field, BUT not for storing state information as
opposed to Stateful beans. There may be a need of storing certain shareable resources like data
source , JMS source etc, which will be used in the exposed method. So it is perfectly safe to have
instance fields in the Stateless session beans
9. Can you inject Stateful beans into stateless session bean or Servlet ?
Yes!!. No body stops you to inject Stateful beans into stateless session bean or a Servlet. Lets take a
Servlet and inject (definitely as a field in Servlet) a Stateful bean; What happens ? Container creates
a single instance of a Servlet, so the instance field of Servlet ( which is a Stateful Bean ) injected , is
shared among clients.It will lead to drastic data inconsistency ( stored in Stateful bean ) being shared
by clients. And this is no different for a Stateful bean injected into stateless bean.So you must AVOID
injecting into stateless beans and Servlets. Please don't ask how do you access or make use of
Stateful bean in Stateless or Servlet.The answer is JNDI inside the methods of Stateless and doGet()
or doPost() of Servlet.
10. What could be wrong if instead of doing JNDI look up or EJB injection of a Bean named
UserRemoteBean I created the instance of the same in the follwing way UserRemoteBean urb=new
UserRemoteBean(); and started using it in the client application?
11. Can you pool stateful session beans ? Justify your answer.
This is because SOAP based Web Services are inherently stateless in nature
13.
Ans. Stateless session bean- An instance of these non-persistent EJBs provides a service without
storing an interaction or conversation state between methods. Any instance can be used for any
client.
Stateful session bean- An instance of these non-persistent EJBs maintains state across methods and
transactions. Each instance is associated with a particular client.
Entity bean- An instance of these persistent EJBs represents an object view of the data, usually rows
in a database. They have a primary key as a unique identifier. Entity bean persistence can be either
container-managed or bean-managed.
Message-driven bean- An instance of these EJBs is integrated with the Java Message Service (JMS) to
provide the ability for message-driven beans to act as a standard JMS message consumer and
perform asynchronous processing between the server and the JMS message producer.
Ans. A session bean is a non-persistent object that implements some business logic running on the
server. One way to think of a session object is as a logical extension of the client program that runs
on the server.
Session beans are used to manage the interactions of entity and other session beans,access
resources, and generally perform tasks on behalf of the client.
There are two basic kinds of session bean: stateless and stateful.
Stateless session beans are made up of business methods that behave like procedures; they operate
only on the arguments passed to them when they are invoked. Stateless beans are called stateless
because they are transient; they do not maintain business state between method invocations.Each
invocation of a stateless business method is independent from previous invocations. Because
stateless session beans are stateless, they are easier for the EJB container to manage, so they tend
to process requests faster and use less resources.
Stateful session beans encapsulate business logic and state specific to a client. Stateful beans are
called “stateful” because they do maintain business state between method invocations, held in
memory and not persistent. Unlike stateless session beans, clients do not share stateful beans.
When a client creates a stateful bean, that bean instance is dedicated to service only that client. This
makes it possible to maintain conversational state, which is business state that can be shared by
methods in the same stateful bean.
Ans. The entity bean is used to represent data in the database. It provides an object-oriented
interface to ____.
Ques 5. What is the difference between Container-Managed Persistent (CMP) bean and Bean-
Managed Persistent(BMP)?
Ans. Container-managed persistence (CMP) and bean-managed persistence (BMP). With CMP, the
container manages the persistence of the entity bean.
Ans. The bean class defines create methods that match methods in the home interface and business
methods that match methods in the remote interface. The bean class also implements a set of
callback methods that allow the container to notify the bean of events in its life cycle. The callback
methods are defined in the javax.ejb.EntityBean interface that is implemented by all entity
beans.The EntityBean interface has the following definition. Notice that the bean class implements
these methods.
public interface javax.ejb.EntityBean {
The setEntityContext() method provides the bean with an interface to the container called the
EntityContext. The EntityContext interface contains methods for obtaining information about the
context under which the bean is operating at any particular moment. The EntityContext interface is
used to access security information about the caller; to determine the status of the current
transaction or to force a transaction rollback; or to get a reference to the bean itself, its home, or its
primary key. The EntityContext is set only once in the life of an entity bean instance, so its reference
should be put into one of the bean instance’s fields if it will be needed later.
The unsetEntityContext() method is used at the end of the bean’s life cycle before the instance is
evicted from memory to dereference the EntityContext and perform any last-minute clean-up.
The ejbLoad() and ejbStore() methods in CMP entities are invoked when the entity bean’s state is
being synchronized with the database. The ejbLoad() is invoked just after the container has
refreshed the bean container-managed fields with its state from the database. The ejbStore()
method is invoked just before the container is about to write the bean container-managed fields to
the database. These methods are used to modify data as it’s being synchronized. This is common
when the data stored in the database is different than the data used in the bean fields.
The ejbPassivate() and ejbActivate() methods are invoked on the bean by the container just before
the bean is passivated and just after the bean is activated, respectively. Passivation in entity beans
means that the bean instance is disassociated with its remote reference so that the container can
evict it from memory or reuse it. It’s a resource conservation measure the container employs to
reduce the number of instances in memory. A bean might be passivated if it hasn’t been used for a
while or as a normal operation performed by the container to maximize reuse of resources. Some
containers will evict beans from memory, while others will reuse instances for other more active
remote references. The ejbPassivate() and ejbActivate() methods provide the bean with a
notification as to when it’s about to be passivated (disassociated with the remote reference) or
activated (associated with a remote reference).
Ans. Session and Entity EJBs consist of 4 and 5 parts respectively, a remote interface.
Ans. Yes. In some cases the data is inserted NOT using Java application.
Ans. If a developer doesn’t want a Container to manage transactions, it’s possible to implement all
database operations manually.
Ans. The transaction attribute specifies how the Container must manage transactions for a method
when a client invokes the method via the enterprise bean’s home or.
Ans. Enterprise java bean is a server side component which runs on application server or we call
container, developed for the purpose of distributed and enterprise level application .container will
provide support for system level services like Transaction Management, security which make
developer task easy and he can focus on business logic.
Ans. Mainly three types of EJB, Entity Bean, Session Bean and Message Driven Bean(MDB).
Types of EJB:
Entity Bean: it represents an entity which is mapped with database or we can say it makes OR object
Relational mapping with Database. Entity bean typically represent table in RDBMS and each instance
represent row in the table.
• CMP Entity bean: Container managed entity bean its responsibility of container to manage the
bean persistence behavior.
Session bean: Session bean is responsible for developing business logic it makes the client server
relationship so session beans exist till there is a session exist between client and server, it doesn’t
contain persistent business concept.
• Stateless session bean: when there is not need to maintain state of a particular client stateless
session bean is used .They alive for short period of time.
For example if we are validating the credit card we can use stateless session bean.
• Stateful session bean: stateful session bean maintain the conversational state of client over the
series of method call before the bean instance goes to passive state conversational state is saved to
persistence area like Hard disk and again when same client send a request and bean instance come
into the active state it will come out from hard disk to main memory.
For Example when we do online banking transaction ,online reservation we use stateful session bean
Message Driven Beans: these beans are work as a listener for messaging services like JMS .
There is another way by which directly entity bean can move to pooled stage to ready stage that’s is
call ejbActivate() method.now we are ready to invoke the business method of entity bean .After
completion of business method if we want to move again in pooled stage from ready stage we can
call remove() method which in turns call ejbRemove() or directly call ejbPassivate () method.
At the end container remove the instance of EJBfrom pool and call unSetEntityContext().
Stateful session beans life cycle starts when client call create() method.The container create the
instance of session bean and call setSessionContext() and ejbCreate() method
Now the stateful session bean is ready to serve the client request after serving the request if it is not
used after a long time container can move this bean to passive stage by calling the ejbPassivate()
method.similarly when bean is in passive stage and client invoke the business method the container
call ejbActivate() method to move bean from passive stage to active or ready stage.
At the end of life cycle client call remove() method and container will call ejbRemove() method and
bean is ready for garbage collection.
Stales session bean has short life cycle it can have two stage does not exist and ready stage. ejb
container create the instance of stateless session bean and call setSessionContext () and ejbCreate()
method.Now the bean is ready to invoke business method on this.it will not maintain the state so
remove () method is been called after completion of business method which in turns call ejbRemove
() and now its ready for garbage collection.
which in turns call ejbRemove () and now its ready for garbage collection.
Ans. Purpose of Static initializer block is to initialize some static fields before any execution of
constructor or method or we can say creation of object. According to EJB Spec it’s a violation if static
field are used and they are non final .
"EJB Spec":
Enterprise bean are not allowed to read or write the non final fields.
But technically,from the point of java its correct but if in EJB we use static initializer block to initialize
static field then because EJB components are used in distributed environment mean to say if single
JVM then it will be ok but if run on different JVM then it will be a problem if we change or update
the value in on environment then only the instance running on same JVM have new value .that’s
why static blocks are avoided and also all static field should be final.
Ans. No, Not possible because EJBs are created and managed by container and if in ejbs we allow
threading containers life cycle methods will be interrupted by us and also the purpose of EJB is to
perform business logic not to controlling a system or implementation level functioning so container
will manage the thread and developer can concentrate on business logic.
Ans. Connection pooling is one of the Advance feature of container which enhanced our application
performance .Using connection pooling mechanism client are not required to create every time
connection object to interact with database .Here in pool objects are already available Whenever a
client request for a database connection then an instance is picked from the connection pool to get
an access to database and when user complete with his work instance is returned to connection
pool. There is a limit specified by App server administrator for the availability of number of
connections and beyond a specified limit a predefined number increases numbers of connection
pool instances. When demand goes back to normal then access amount of connection pool instances
are removed.
Ans. Session Façade is one of the design pattern which is used in EJB component in this pattern
session beans are used as a wrapper classes for entity bean and using session bean we interact with
Entity bean .it will give clean approach towards client access to bean components and also reduce
network calls so as to make the whole system of high performance.
Ans. Transaction is group of operation or work which should be performed either completely or
none to maintain the data integrity. All transaction must have ACID property(atomicity
,consistency,integrity,durability) so transaction can be said completed if we commit on successful
execution and rollback on unsuccessful execution.
Transaction Attribute conveys to the container the intended transactional behavior of the associated
EJB component's method.
Required: if required attribute is associated with Method then new Transaction context may or may
not be created, means if method is already associated with transaction context then no new
transaction context should be created.
Requires New: if Requires New attribute is associated with Method then always new Transaction
context may be created.
NotSupported:if Method is Associated with this Attribute then method is a not a part of transaction.
Supported:if a Method is Associated with this transaction Attribute then method will act as Not
supported if calling component is not associated with transaction and if calling component is
associated with transaction then act as a required Attribute.
Mandatory:if a method is Associated with this attribute then always be called from calling
component transaction context.
Never: if a method is Associated with this attribute then never be called from calling component
transaction context.
Ans. Both of these methods are used in context of entity bean for the purpose of synchronizing the
instance variable to corresponding value store in the database. ejbLoad method load or refresh the
instance variable from the database and ejbStore method writes variables value back to the
database.
Ques 21. What is the difference between JNDI context, Initial context, session context and ejb
context?
Session Context:it has all the information available which is required to session bean from container.
EjbContext:it contain information which is required to both session and entity bean.
Ques 22. What are the two important TCP Socket classes?
ServerSocket is used for normal two-way socket communication. Socket class allows us to read and
write through the sockets. getInputStream() and getOutputStream() are the two methods available
in Socket class.
Ques 24. What is the difference between EJB and Java beans?
Ans. EJB is a specification for J2EE server, not a product; Java beans may be a graphical component
in IDE.
Ans. EJB technology is the core of J2EE. It enables developers to write reusable and portable server-
side business logic for the J2EE platform.
Ans. The process by which the contents in the memory of one physical m/c are replicated in all the
m/c in the cluster is called in-memory replication.
Ans. The process of propagating the changes in the properties of a server group during runtime to all
the associated clones is called Ripple Effect.
Ans. The copies of a server group are called Clones. But unlike a Server Group Clones are associated
with a node and are real server process running in that node.
Ans. There are two types of scaling: Vertical Scaling and Horizontal Scaling.
Vertical Scaling - When multiple server clones of an application server are defined on the same
physical m/c, it is called Vertical Scaling. The objective is to use the processing power of that m/c
more efficiently.
Horizontal Scaling - When Clones of an application server are defined on multiple physical m/c, it is
called Horizontal Scaling. The objective is to use more than one less powerful m/c more efficiently.
Ques 30. What is a Server Group?
Ans. A server group is a template of an Application Server(and its contents) i.e, it is a logical
representation of the application server. It has the same structure and attributes as the real
Application Server, but it is not associated with any node, and does not correspond to any real
server process running on any node.
Ans. Following are some of the main features supported in EJB 2.0:
3. Implement additional Business methods in Home interface which are not specific for bean
instance, EJB QL.
Ans. We can use the Java 2 Platform, Enterprise Edition Client Access Services (J2EETM CAS) COM
Bridge 1.0, currently downloadable from Sun.
Ques 33. What is the relationship between local interfaces and container-managed relationships?
Ans. Entity beans that have container-managed relationships with other entity beans, must be
accessed in the same local scope as those related beans, and therefore typically provide a local client
view. In order to be the target of a container-managed relationship, an entity bean with container-
managed persistence must provide a local interface.
Ans. EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related source files
from custom JavaDoc comments tags embedded in the EJB source file.
Ques 35. What is the difference between session and entity beans?
Ans. An entity bean represents persistent global data from the database; a session bean represents
transient user-specific data that will die when the user disconnects (ends his session). Generally, the
session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g.
Account.deposit, Account.withdraw)
Ans. EJB was originally designed around remote invocation using the Java Remote Method
Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these
calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without
consideration for the deployment scenario, and was a strong feature in support of a goal of
component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB
calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group
has created a local interface mechanism. The local interface may be defined for a bean during
development, to allow streamlined calls to the bean if a caller is in the same container. This does not
involve the overhead involved with RMI like marshalling etc. This facility will thus improve the
performance of applications in which co-location is planned. Local interfaces also provide the
foundation for container-managed relationships among entity beans with container-managed
persistence.
Ans. Yes. In some cases the data is inserted NOT using Java application, so you may only need to
retrieve the information, perform its processing, but not create your own information of this kind.
2. A home interface (used for creating objects and for declaring business methods),
3. A bean object (an object, which actually performs business logic and EJB-specific operations).
4. A deployment descriptor (an XML file containing all information required for maintaining the EJB)
or a set of deployment descriptors (if you are using some container-specific features).
Ans. Container-managed persistence beans are the simplest for the bean developer to create and
the most difficult for the EJB server to support. This is because all the logic for synchronizing the
bean’s state with the database is handled automatically by the container. This means that the bean
developer doesn’t need to write any data access logic, while the EJB server is supposed to take care
of all the persistence needs automatically. With CMP, the container manages the persistence of the
entity bean. A CMP bean developer doesn’t need to worry about JDBC code and transactions,
because the Container performs database calls and transaction management instead of the
programmer. Vendor tools are used to map the entity fields to the database and absolutely no
database access code is written in the bean class. All table mapping is specified in the deployment
descriptor. Otherwise, a BMP bean developer takes the load of linking an application and a database
on his shoulders.
The bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the
database as directed by the container. The bean uses a database API to read and write its fields to
the database, but the container tells it when to do each synchronization operation and manages the
transactions for the bean automatically. Bean-managed persistence gives the bean developer the
flexibility to perform persistence operations that are too complicated for the container or to use a
data source that is not supported by the container.BMP beans are not 100% database-independent,
because they may contain database-specific code, but CMP beans are unable to perform
complicated DML (data manipulation language) statements. EJB 2.0 specification introduced some
new ways of querying database (by using the EJB QL - query language).
1. create methods: To create a new instance of a CMP entity bean, and therefore insert data into the
database, the create() method on the bean’s home interface must be invoked. They look like this:
EntityBeanClass ejbCreateXXX(parameters), where EntityBeanClass is an Entity Bean you are trying
to instantiate, ejbCreateXXX(parameters) methods are used for creating Entity Bean instances
according to the parameters specified and to some programmer-defined conditions.
A bean’s home interface may declare zero or more create() methods, each of which must have
corresponding ejbCreate() and ejbPostCreate() methods in the bean class. These creation methods
are linked at run time, so that when a create() method is invoked on the home interface, the
container delegates the invocation to the corresponding ejbCreate() and ejbPostCreate() methods
on the bean class.
2. finder methods: The methods in the home interface that begin with “find” are called the find
methods. These are used to query the EJB server for specific entity beans, based on the name of the
method and arguments passed. Unfortunately, there is no standard query language defined for find
methods, so each vendor will implement the find method differently. In CMP entity beans, the find
methods are not implemented with matching methods in the bean class; containers implement
them when the bean is deployed in a vendor specific manner. The deployer will use vendor specific
tools to tell the container how a particular find method should behave. Some vendors will use
object-relational mapping tools to define the behavior of a find method while others will simply
require the deployer to enter the appropriate SQL command.
There are two basic kinds of find methods: single-entity and multi-entity. Single-entity find methods
return a remote reference to the one specific entity bean that matches the find request. If no entity
beans are found, the method throws an ObjectNotFoundException . Every entity bean must define
the single-entity find method with the method name findByPrimaryKey(), which takes the bean’s
primary key type as an argument.
The multi-entity find methods return a collection ( Enumeration or Collection type) of entities that
match the find request. If no entities are found, the multi-entity find returns an empty collection.
3. remove methods: These methods (you may have up to 2 remove methods, or don’t have them at
all) allow the client to physically remove Entity beans by specifying either Handle or a Primary Key
for the Entity Bean.
4. home methods: These methods are designed and implemented by a developer, and EJB
specification doesn’t have any requirements for them except the need to throw a RemoteException
is each home method.
Ques 41. When should I adopt BMP and when I should use CMP?
Ans. You can use CMP and BMP beans in the same applicatioN... obviously, a bean can be BMP or
CMP, not both at the same time (they are mutually exclusive).
There is a common approach that is normally used and considered a good one. You should start
developing CMP beans, unless you require some kind of special bean, like multi-tables, that cannot
be completely realized with a single bean. Then, when you realize that you need something more or
that you would prefer handling the persistence (performanbce issue are the most common reason),
you can change the bean from a CMP to a BMP.
Ques 42. Static variables in EJB should not be relied upon as they may break in clusters.Why?
Ans. Static variables are only ok if they are final. If they are not final, they will break the cluster.
What that means is that if you cluster your application server (spread it across several machines)
each part of the cluster will run in its own JVM.
Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that causes
value of the static variable to be increased to 101. On the subsequent call to the same EJB from the
same client, a cluster 2 may be invoked to handle the request. A value of the static variable in cluster
2 is still 100 because it was not increased yet and therefore your application ceases to be consistent.
Therefore, static non-final variables are strongly discouraged in EJBs.
Ques 43. Can I develop an Entity Bean without implementing the create() method in the home
interface?
Ans. As per the specifications, there can be ‘ZERO’ or ‘MORE’ create() methods defined in an Entity
Bean. In cases where create() method is not provided, the only way to access the bean is by knowing
its primary key, and by acquiring a handle to it by using its corresponding finder method. In those
cases, you can create an instance of a bean based on the data present in the table. All one needs to
know is the primary key of that table. i.e. a set a columns that uniquely identify a single row in that
table. Once this is known, one can use the ‘getPrimaryKey()’ to get a remote reference to that bean,
which can further be used to invoke business methods.
Ques 44. What is the need of Remote and Home interface. Why cant it be in one?
Ans. The main reason is because there is a clear division of roles and responsibilities between the
two interfaces. The home interface is your way to communicate with the container, that is who is
responsible of creating, locating even removing one or more beans. The remote interface is your link
to the bean, that will allow you to remotely access to all its methods and members. As you can see
there are two distinct elements (the container and the beans) and you need two different interfaces
for accessing to both of them.
Ans. EJBContext is an interface that is implemented by the container, and it is also a part of the
bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session
beans use a subclass called SessionContext. These EJBContext objects provide the bean class with
information about its container, the client using the bean and the bean itself. They also provide
other functions. See the API docs and the spec for more details.
Ques 47. How can I call one EJB from inside of another EJB?
Ans. EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the
other bean, then acquire an instance reference, and so forth.
Ans. In case of a stateless session bean it may not matter if we call or not as in both cases nothing is
done. The number of beans in cache is managed by the container.
In case of stateful session bean, the bean may be kept in cache till either the session times out, in
which case the bean is removed or when there is a requirement for memory in which case the data
is cached and the bean is sent to free pool.
Ans. EJB QL is a Query Language provided for navigation across a network of enterprise beans and
dependent objects defined by means of container managed persistence. EJB QL is introduced in the
EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with
container managed persistenceand is portable across containers and persistence managers. EJB QL is
used for queries of two types of finder methods: Finder methods that are defined in the home
interface of an entity bean and which return entity objects. Select methods, which are not exposed
to the client, but which are used by the Bean Provider to select persistent values that are maintained
by the Persistence Manager or to select entity objects that are related to the entity bean on which
the query is defined.
Ans. The primary key can’t be a primitive type–use the primitive wrapper classes, instead. For
example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a
primitive).
Ans. Step 1: Retrieve Home Object reference from Naming Service via JNDI.
• Web Designers
• Designing
• Home Businesses
Ans. The transaction attribute specifies how the Container must manage transactions for a method
when a client invokes the method via the enterprise bean’s home or component interface or when
the method is invoked as the result of the arrival of a JMS message. (Sun’s EJB Specification) Below is
a list of transactional attributes:
2. Required - bean’s method invocation is made within a transactional context. If a client is not
associated with a transaction, a new transaction is invoked automatically.
3. Supports - if a transactional context exists, a Container acts like the transaction attribute is
Required, else - like NotSupported.
5. Mandatory - if a transactional context exists, a Container acts like the transaction attribute is
Required, else it throws a javax.ejb.TransactionRequiredException.
Ques 53. How can I call one EJB from inside of another EJB?
Ans. EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the
other bean, then acquire an instance reference, and so forth.
Ques 54. What is the difference between Message Driven Beans and Stateless Session beans?
Ans. In several ways, the dynamic creation and allocation of message-driven bean instances mimics
the behavior of stateless session EJB instances, which exist only for the duration of a particular
method call. However, message-driven beans are different from stateless session EJBs (and other
types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages
asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans
have no home or remote interface, and therefore cannot be directly accessed by internal or external
clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS
Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean
instances and passing JMS messages to those instances as necessary. The Container maintains the
entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of
client requests or other API calls.
Ques 55. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change
a value in the HttpSession from inside an EJB?
Ans. You can pass the HttpSession as parameter to an EJB method, only if all objects in session are
serializable.This has to be consider as passed-by-value, that means that it’s read-only in the EJB. If
anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet
Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote
references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is
considered to be bad practice in terms of object-oriented design. This is because you are creating an
unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a
higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which
carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that
holds all the data you need to pass back and forth between front-end/back-end. Consider the case
where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be
flexible enough to support it.
Ques 56. What is the difference between find and select methods in EJB?
Ans. A select method can return a persistent field (or a collection thereof) of a related entity bean. A
finder method can return only a local or remote interface (or a collection of interfaces).
Because it is not exposed in any of the local or remote interfaces, a select method cannot be invoked
by a client. It can be invoked only by the methods implemented within the entity bean class. A select
method is usually invoked by either a business or a home method.
A select method is defined in the entity bean class. For bean-managed persistence, a finder method
is defined in the entity bean class, but for container-managed persistence it is not.
• Web Designers
• Features
• Performance Review
• Performances
• Antivirus Software
• Designing
Ans. A Java Bean is a software component written in the Java programming language that conforms
to the JavaBeans component specification. The JavaBeans APIs became part of the “core” Java APIs
as of the 1.1 release of the JDK.
The JavaBeans specification defines a Java-based software component model that adds a number of
features to the Java programming language. Some of these features include:
.introspection
.customization
.events
.properties
.persistence
Enterprise JavaBeans (EJBs) are Java-based software components that are built to comply with Java’s
EJB specification and run inside of an EJB container supplied by a J2EE provider. An EJB container
provides distributed application functionality such as transaction support, persistence and lifecycle
management for the EJBs.
Ans. Abstract schema is part of an entity bean’s deployment descriptor which defines the bean’s
persistent fields and their relationship. Abstract schema is specified for entity beans with container
managed persistence. We specify the name of the Abstract schema name in the deployment
descriptor. The queries written in EJB QL for the finder methods references this name. The
information provided in this Abstract Schema is used by the container for persistence management
and relationship management.
Ans. An EJB can use local client view only if it is really guaranteed that other enterprise beans or
clients will only address the bean within a single JVM. With local client view, you can do pass-by-
reference, which means your bean, as well as the client, will work directly with one copy of the data.
Any changes made by the bean will be seen by the client and vice versa. Pass-by-reference
eliminates time/system expenses for copying data variables, which provides a performance
advantage.
Ans. An MDB is essentially a message consumer that can listen to a message destination or a
message endpoint and gets activated when a message arrives. By design, MDBs are anonymous in
nature and hence cannot be directly invoked by a client. The only way to invoke an MDB is to send a
message to the destination or endpoint to which it is listening. As MDBs are stateless in nature and
are not related to any specific client, they can be pooled for concurrent processing of messages.
Ques 61. What are the services provided by container?
Ans. Container services are totally depends upon the “vendor implementation”. But more or less
most of the vendors suppots the basic services like,
The other services, if any will be in advanced versions, and depends on Vendor specific.
• Private
• Answers
• Email Address
• Job Openings
Ques 62. How many EJB Objects are created for a Bean?
Ans. For a Session bean - one EJB object for one bean instance.
For entity bean - it depends , if 2 users are accessing one row at time then one EJB object is used for
both the beans other wise for each bean one EJB object.
Ques 63. What is re-entrant. Is session beans reentrant. Is entity beans reentrant?
Ans. If we define the entity bean as being reentrant, multiple clients can connect to the Entity bean
& execute methods within the entity bean concurrently. Container takes care of synchronization. If
we define the entity bean as non-reentrant and many clients connect to it concurrently to execute a
method, exception is thrown .
Ques 64. What is the difference between EAR, JAR and WAR file?
2. Web Archives (WAR) WAR files are similar to JAR files, except that they are specifically for web
applications made from Servlets, JSPs, and supporting classes.
3. Enterprise Archives (EAR) ”An EAR file contains all of the components that make up a particular
J2EE application.
Ans. Lazy loading means not creating an object until the first time it is accessed. Lazy loading
typically looks like this:
if (this.data == null) {
return this.data;
This technique is most useful when you have large hierarchies of objects (such as a product catalog).
You can lazy-load subordinate objects as you navigate down the hierarchy, and thereby only create
objects when you need them.
• Web Designers
• Designing
Ans. No. Decorator design pattern, is the one which exhibits very low level runtime polymorphism,
for the specific and single object (Instance of the class), but not for atleast for a class. It is the stuff to
add specific functionality to a single & pointed object and leaves others like it unmodified. It is
having close similarities like aspectJ stuff, but not with EJB stuff.
Ans. Since EnterpriseBeans live in a managed container, the container is free to call your EJB
components methods at its leisure. The container houses the information like current status of
bean,security credentials of the user currently accessing the bean in one object is called EJBContext
Object. A context represents a way for beans to perform callbacks and modify their current status
Sessioncontext is EJB context for session bean Entitycontext is EJB context for entity bean Message
driven context is EJB context for message driven bean.
Ques 69. Does stateless Session bean create() method contain any parameters?
Ans. Stateless SessionBean create() method doesnot contain any parameters and the syntax is as
follows:
Ques 70. What is difference between EJB 1.1 and EJB 2.0?
Ans. The bulk of the changes in EJB 2.0 are found in the definition of a new CMP component model.
It’s radically different from the old CMP model because it introduces an entirely new participant, the
persistence manager, and a completely new way of defining container-managed fields, as well as
relationships with other beans and dependent objects.
Ans. The ejbCreate() methods is part of the bean’s lifecycle, so, the compiler will not return an error
because there is no ejbCreate() method.
• the home interface of a Stateless Session Bean must have a single create() method with no
arguments,
while the session bean class must contain exactly one ejbCreate() method, also without arguments.
• Stateful Session Beans can have arguments (more than one create method)
• Home Businesses
• Job Openings
Ans. The purpose of ejbPostCreate() is to perform clean-up database operations after SQL INSERTs
(which occur when ejbCreate() is called) when working with CMP entity beans. ejbCreate() is called
before database INSERT operations. You need to use ejbPostCreate() to define operations, like set a
flag, after INSERT completes successfully.
Ques 73. Why does EJB needs two interfaces(Home and Remote Interface)?
Home Interface is the way to communicate with the container which is responsible for creating ,
locating and removing beans and Remote Interface is the link to the bean that allows acces to all
methods and members.
Ans. WHERE and ORDERBY clauses are optional in EJB QL where as SELECT and FROM are required
clauses.
Ans. You shouldn’t. What will happen depends on the implementation, but the call will most likely
be ignored.
Ans. The remote client view specification is only available in EJB 2.0. The remote client view of an
enterprise bean is location independent. A client running in the same JVM as a bean instance uses
the same API to access the bean as a client running in a different JVM on the same or different
machine.
Remote interface: The remote interface specifies the remote business methods that a client can call
on an enterprise bean.
Remote home interface: The remote home interface specifies the methods used by remote clients
for locating, creating, and removing instances of enterprise bean classes.
• Job Openings
• Email Address
Ans. The local client view specification is only available in EJB 2.0. Unlike the remote client view, the
local client view of a bean is location dependent. Local client view access to an enterprise bean
requires both the local client and the enterprise bean that provides the local client view to be in the
same JVM. The local client view therefore does not provide the location transparency provided by
the remote client view. Local interfaces and local home interfaces provide support for lightweight
access from enterprise bean that are local clients. Session and entity beans can be tightly couple
with their clients, allowing access without the overhead typically associated with remote method
calls.
Ans. An EJB client JAR file is an optional JAR file that can contain all the class files that a client
program needs to use the client view of the enterprise beans that are contained in the EJB JAR file. If
you decide not to create a client JAR file for an EJB module, all of the client interface classes will be
in the EJB JAR file.
Ans. An EJB container is a run-time environment that manages one or more enterprise beans. The
EJB container manages the life cycles of enterprise bean objects, coordinates distributed
transactions, and implements object security. Generally, each EJB container is provided by an EJB
server and contains a set of enterprise beans that run on the server.
Ans. An EJB server is a high-level process or application that provides a run-time environment to
support the execution of server applications that use enterprise beans. An EJB server provides a
JNDI-accessible naming service, manages and coordinates the allocation of resources to client
applications, provides access to system resources, and provides a transaction service. An EJB server
could be provided by, for example, a database or application server.
EJB 2.x (Enterprise JavaBeans) is widely adopted server side component architecture for J2EE.
• EJB is a remote, distributed multi-tier system and supports protocols like JRMP, IIOP, and
HTTP etc.
• It enables rapid development of reusable, versatile, and portable business components (i.e.
across middleware), which are transactional and scalable.
• EJB is a specification for J2EE servers. EJB components contain only business logic and
system level programming and services like transactions, security, instance pooling, multi-threading,
persistence etc are managed by the EJB Container and hence simplify the programming effort.
Note: Having said that EJB 2.x is a widely adopted server side component, EJB 3.0 is taking ease of
development very seriously and has adjusted its model to offer the POJO (Plain Old Java Object)
persistence and the new O/R mapping model based on Hibernate. In EJB 3.0, all kinds of enterprise
beans are just POJOs. EJB 3.0 extensively uses Java annotations, which replaces excessive XML based
configuration files and eliminates the need for the rigid component model used in EJB 1.x, 2.x.
Annotations can be used to define the bean’s business interface, O/R mapping information, resource
references etc. So, for future developments look out for EJB 3.0 and/or Hibernate framework.
Both EJBs and JavaBeans have very similar names but this is where the similarities end.
JavaBeans
• The components built based on JavaBeans live in a single local JVM (i.e. address space) and
can be either visual (e.g. GUI components like Button, List etc) or non-visual at runtime.
• The Enterprise JavaBeans are non-visual distributable components, which can live across
multiple JVMs (i.e. address spaces).
• EJBs can be transactional and the EJB servers provide transactional support.
• EJBs are coarse-grained components that can be deployed as is or assembled with other
components into larger applications. EJBs must be deployed in a container that provides services like
instance pooling, multi-threading, security, life-cycle management, transactions etc
EJB Container:
EJBs are software components, which run in an environment called an EJB container. An EJB cannot
function outside an EJB Container. The EJB container hosts and manages an Enterprise JavaBean in a
similar manner that a Web container hosts a servlet or a Web browser hosts a Java Applet. The EJB
container manages the following services so that the developer can concentrate on writing the
business logic:
• Transactions
• Persistence
• Security
Design pattern:
EJBs use the proxy design pattern to make remote invocation (i.e. remote proxy) and to add
container managed services like security and transaction demarcation.
EJBContext:
Every bean obtains an EJBContext object, which is a reference directly to the container. The EJB can
request information about its environment like the status of a transaction, a remote reference to
itself (an EJB cannot use 'this' to reference itself) etc.
Deployment Descriptor:
The container handles all the above mentioned services declaratively for an EJB based on the XML
deployment descriptor (ejb-jar.xml). When an EJB is deployed into a container the deployment
descriptor is read to find out how these services are handled.
EJB:
• Session beans.
• Entity beans.
• Message-driven beans.
The session and entity beans are invoked synchronously by the client and message driven beans are
invoked asynchronously by a message container such as a Queue or a Topic.
Session Bean:
It is a non-persistent object that implements some business logic running on the server. Session
beans do not survive system shut down. There are two types of session beans
• Stateless session beans (i.e. each session bean can be reused by multiple EJB clients).
• Stateful session beans (i.e. each session bean is associated with one EJB client).
Entity Bean:
It is a persistent object that represents object views of the data, usually a row in a database. They
have the primary key as a unique identifier. Multiple EJB clients can share each entity bean. Entity
beans can survive system shutdowns. Entity beans can have two types of persistence
• Container-Managed Persistence (CMP) - The container is responsible for saving the bean’s
state.
• Bean-Managed Persistence (BMP) : The entity bean is responsible for saving its own state.
Message-driven Bean:
It is integrated with the Java Message Service (JMS) to provide the ability to act as a message
consumer and perform asynchronous processing between the server and the message producer.
Session Beans
• Session beans control the workflow and transactions of a group of entity beans.
• Life is limited to the life of a particular client. Handle database access for a particular client.
Entity Beans
• Domain objects with a unique identity (i.e.-primary key) shared by multiple clients.
• Persist across multiple invocations. Handles database access for multiple clients.
• Need not be activated or passivated since the beans are pooled and reused.
• Need to handle activation and passivation to conserve system memory since one session
bean object per client.
What is the difference between Container Managed Persistence (CMP) and Bean Managed
Persistence (BMP) entity beans ?
• The bean persistence is independent of its database (e.g. DB2, Oracle, Sybase etc). So it is
portable from one data source to another.
• The bean persistence is hard coded and hence may not be portable between different
databases (e.g. DB2, Oracle etc).
An EJB client should never access an EJB directly. Any access is done through the container. The
container will intercept the client call and apply services like transaction, security etc prior to
invoking the actual EJB.
How does an EJB interact with its container and what are the call-back methods in entity beans ?
Call-back Methods:
Every EJB implements an interface (extends EnterpriseBean) which defines several methods which
alert the bean to various events in its lifecycle. A container is responsible for invoking these
methods. These methods notify the bean when it is about to be activated, to be persisted to the
database, to end a transaction, to remove the bean from the memory, etc. For example the entity
bean has the following call-back methods:
EJBContext:
It provides methods for interacting with the container so that the bean can request information
about its environment like the identity of the caller, security, status of a transaction, obtains remote
reference to itself etc. e.g. isUserInRole(), getUserPrincipal(), isRollbackOnly(), etc
JNDI:
Java Naming and Directory Interface allows EJB to access resources like JDBC connections, JMS topics
and queues, other EJBs etc.
What is the difference between EJB 1.1 and EJB 2.0 ? What is the difference between EJB 2.x and EJB
3.0 ?
EJB 2.0 has the following additional advantages over the EJB 1.1
Local interfaces:
These are beans that can be used locally, that means by the same Java Virtual Machine, so they do
not required to be wrapped like remote beans, and arguments between those interfaces are passed
directly by reference instead of by value. This improves performance.
EJBHome methods:
Entity beans can declare ejbHomeXXX("") methods that perform operations related to the EJB
component but that are not specific to a bean instance. The ejbHomeXXX("") method declared in the
bean class must have a matching home method XXXX("") in the home interface.
It is a completely new enterprise bean type, which is designed specifically to handle incoming JMS
messages.
It is based on a new contract called the abstract persistence schema, which will allow the container
to handle the persistence automatically at runtime.
It is a SQL-based language that will allow the new persistence schema to implement and execute
finder methods. EJB QL also used in new query methods ejbSelectXXX(""), which is similar to
ejbFindXXXX("") methods except that it is only for the bean class to use and not exposed to the client
(i.e. it is not declared in the home interface)
The timer service provides coarse-grained, transactional, time-based event notifications to enable
enterprise beans to model and manage higher-level business processes.
Web Service support:
EJB 2.1 adds the ability of stateless session beans to implement a Web Service endpoint via a Web
Service endpoint interface.
EJB-QL:
Enhanced EJB-QL includes support for aggregate functions and ordering of results.
• You need to create several component interfaces and implement several unnecessary call-
back methods.
• EJB components are not truly object oriented, as they have restrictions for using inheritance
and polymorphism.
• EJB modules cannot be tested outside an EJB container and debugging an EJB inside a
container is very difficult.
Lifecycle Management:
Individual enterprise beans do not need to explicitly manage process allocation, thread
management, object activation, or object destruction. The EJB container automatically manages the
object lifecycle on behalf of the enterprise bean.
State Management:
Individual enterprise beans do not need to explicitly save or restore conversational object state
between method calls. The EJB container automatically manages object state on behalf of the
enterprise bean.
Security:
Individual enterprise beans do not need to explicitly authenticate users or check authorization levels.
The EJB container automatically performs all security checking on behalf of the enterprise bean.
Transactions:
Individual enterprise beans do not need to explicitly specify transaction demarcation code to
participate in distributed transactions. The EJB container can automatically manage the start,
enrolment, commitment, and rollback of transactions on behalf of the enterprise bean.
Persistence:
Individual enterprise beans do not need to explicitly retrieve or store persistent object data from a
database. The EJB container can automatically manage persistent data on behalf of the enterprise
bean.
EJB transactions are a set of mechanisms and concepts, which insures the integrity and consistency
of the database when multiple clients try to read/update the database simultaneously. Transaction
attributes are defined at different levels like EJB class, a method within a class or segment of a code
within a method. The attributes specified for a particular method take precedence over the
attributes specified for a particular EJB class. Transaction attributes are specified declaratively
through EJB deployment descriptors. Unless there is any compelling reason, the declarative
approach is recommended over programmatic approach where all the transactions are handled
programmatically. With the declarative approach, the EJB container will handle the transactions.
Isolation levels provide a degree of control of the effects one transaction can have on another
concurrent transaction. Since concurrent effects are determined by the precise ways in which, a
particular relational database handles locks and its drivers may handle these locks differently. The
semantics of isolation mechanisms based on these are not well defined. Nevertheless, certain
defined or approximate properties can be specified as follows:
TRANSACTION_SERIALIZABLE
Strongest level of isolation. Places a range lock on the data set, preventing other users from
updating or inserting rows into the data set until the transaction is complete. Can produce
deadlocks.
TRANSACTION_REPEATABLE_READ
Locks are placed on all data that is used in a query, preventing other users from updating the data,
but new phantom records can be inserted into the data set by another user and are included in later
reads in the current transaction.
TRANSACTION_READ_COMMITTED
Can't read uncommitted data by another transaction. Shared locks are held while the data is being
read to avoid dirty reads, but the data can be changed before the end of the transaction resulting in
non-repeatable reads and phantom records.
TRANSACTION_READ_UNCOMMITTED
Can read uncommitted data (dirty read) by another transaction, and nonrepeatable reads and
phantom records are possible. Least restrictive of all isolation levels. No shared locks are issued and
no exclusive locks are honored.
Isolation levels are not part of the EJB specification. They can only be set on the resource manager
either explicitly on the Connection (for bean managed persistence) or via the application server
specific configuration. The EJB specification indicates that isolation level is part of the Resource
Manager. As the transaction isolation level increases, likely performance degradation follows, as
additional locks are required to protect data integrity. If the underlying data does not require such a
high degree of integrity, the isolation level can be lowered to improve performance.
A Transaction (Refer Q43 in Enterprise section) is a series of actions performed as a single unit of
work in which either all of the actions performed as a logical unit of work in which, either all of the
actions are performed or none of the actions. A transaction is often described by ACID properties
(Atomic, Consistent, Isolated and Durable). A distributed transaction is an ACID transaction between
two or more independent transactional resources like two separate databases. For the transaction
to commit successfully, all of the individual resources must commit successfully. If any of them are
unsuccessful, the transaction must rollback in all of the resources. A 2-phase commit is an approach
for committing a distributed transaction in 2 phases.
• Phase 1 is prepare: Each of the resources votes on whether it’s ready to commit usually by
going ahead and persisting the new data but not yet deleting the old data.
• Phase 2 is committing: If all the resources are ready, they all commit after which old data is
deleted and transaction can no longer roll back. 2-phase commit ensures that a distributed
transaction can always be committed or always rolled back if one of the databases crashes. The XA
specification defines how an application program uses a transaction manager to coordinate
distributed transactions across multiple resource managers. Any resource manager that adheres to
XA specification can participate in a transaction coordinated by an XAcompliant transaction
manager.
A transaction can be doomed by the following method call ejbContext.setRollbackOnly(); The above
call will force transaction to rollback. The doomed transactions decrease scalability and if a
transaction is doomed why perform compute intensive operations? So you can detect a doomed
transaction as shown below:
if ( ejbContext.getRollbackOnly() ) {
} else {
performComplexOperation();
}
A stateful session bean is a resource which has an in memory state which can be rolled back in case
of any failure. It can participate in transactions by implementing SessionSynchronization.
• Enables the bean to act as a transactional resource and undo state changes on failure.
A System Exception is thrown by the system and is not recoverable. For example EJB container losing
connection to the database server, failed remote method objects call etc. Because the System
Exceptions are unpredictable, the EJB container is the only one responsible for trapping the System
Exceptions. The container automatically wraps any RuntimeException in RemoteException, which
subsequently gets thrown to the caller (i.e. client). In addition to intercepting System Exception the
container may log the errors.
Be aware that handling exceptions in EJB is different from handling exceptions in Java. The Exception
handling best practice tips are:
• If you cannot recover from System Exception let the container handle it.
• If you want to rollback a transaction on an application exception then catch the application
exception and throw an EJBException or use ctx.setRollbackOnly();
Pessimistic Concurrency
• A pessimistic design assumes conflicts will occur in the database tables and avoids them through
exclusive locks etc.
• EJB (also non-EJB) locks the source data until it completes its transaction.
• The pessimistic locking imposes high locking overheads on the server and lower concurrency.
Optimistic Concurrency
• An optimistic approach assumes conflicts won’t occur, and deal with them when they do occur.
• EJB (also non-EJB) implements a strategy to detect whether a change has occurred. Locks are
placed on the database only for a small portion of the time.
• The optimistic locking is used in the context of cursors. The optimistic locking works as follows:
• No locks are acquired while values in the current row are changed.
• When changes are saved, a copy of the row in the database is read in the locked mode.
• If the data was changed after it was read into the cursor, an error is raised so that the
transaction can be rolled back and retried.
How can we determine if the data is stale (for example when using optimistic locking) ?
o Carry the version number along with any data read into memory (through value object,
entity bean etc).
o Before performing any update compare the current version number with the database
version number.
o If the version numbers are equal update the data and increment the version number.
o If the value object or entity bean is carrying an older version number, reject the update and
throw an exception.
These techniques are also quite useful when implementing data caching to improve performance.
Data caches should regularly keep track of stale data to refresh the cache. These strategies are valid
whether you use EJB or other persistence mechanisms like JDBC, Hibernate etc.
In order to develop reliable and portable EJB components, the following restrictions apply to EJB
code implementation:
• Avoid using static non-final fields. Declaring all static fields in EJB component as final is
recommended. This enables the EJB container to distribute instances across multiple JVMs.
• Avoid starting a new thread (conflicts with EJB container) or using thread synchronization
(allow the EJB container to distribute instances across multiple JVMs).
• Avoid using AWT or Swing functionality. EJBs are server side business components.
• Avoid using file access or java.io operations. EJB business components are meant to use
resource managers such as JDBC to store and retrieve application data. But deployment descriptors
can be used to store .
• Avoid accepting or listening to socket connections. EJB components are not meant to
provide network socket functionality. However the specification lets EJB components act as socket
clients or RMI clients.
• Avoid using the reflection API. This restriction enforces Java security.
• Can't use custom class loaders.
EJB components operate inside a container environment and rely heavily on the container to provide
security. The four key services required for the security are:
• Authentication: To prove the identity one must present the credentials in the form of password,
swipe card, digital certificate, finger prints etc.
• Authorization (Access Control): Every secure system should limit access to particular users. The
common way to enforce access control is by maintaining security roles and privileges.
• Data Confidentiality: This is maintained by encryption of some sort. It is no good to protect your
data by authentication if someone can read the password. The EJB specification concerns itself
exclusively with authorization (access control). An application using EJB can specify in an abstract
(declarative) and portable way that is allowed to access business methods. The EJB container
handles the following actions:
• Check the EJB deployment descriptor to see if the identity is a member of a security role that
has been granted the right to call this business method.
• Make the identity and the security role information available for a fine grained
programmatic security check.
There are two types of information the EJB developer has to provide through the deployment
descriptor.
• Security roles
• Method permissions
• Use local interfaces that are available in EJB2.0 if you deploy both the EJB client and the EJB in the
same server. Use vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs
operate as local. [Extreme care should be taken not to affect the functionality by switching the
application, which was written and tested in pass-by-reference mode to pass-by-value without
analyzing the implications and re-testing the functionality.
• Wrap entity beans with session beans to reduce network calls and promote declarative
transactions. Where possible use local entity beans and session beans can be either local or remote.
Apply the appropriate EJB design patterns
• Cache ejbHome references to avoid JNDI look-up overhead using service locator pattern.
• Choose plain Java object over EJB if you do not want services like RMI/IIOP, transactions, security,
persistence, thread safety etc. There are alternative frameworks such as Hibernate, Spring etc.
• Choose Servlet’s HttpSession object rather than stateful session bean to maintain client state if
you do not require component architecture of a stateful bean.
What is the need of Remote and Home interface. Why cant it be in one?
The main reason is because there is a clear division of roles and responsabilities between the two
interfaces. The home interface is your way to communicate with the container, that is who is
responsable of creating, locating even removing one or more beans. The remote interface is your
link to the bean, that will allow you to remotely access to all its methods and members. As you can
see there are two distinct elements (the container and the beans) and you need two different
interfaces for accessing to both of them.
Can I develop an Entity Bean without implementing the create() method in the home interface?
As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined in an Entity Bean.
In cases where create() method is not provided, the only way to access the bean is by knowing its
primary key, and by acquiring a handle to it by using its corresponding finder method. In those cases,
you can create an instance of a bean based on the data present in the table. All one needs to know is
the primary key of that table. i.e. a set a columns that uniquely identify a single row in that table.
Once this is known, one can use the 'getPrimaryKey()' to get a remote reference to that bean, which
can further be used to invoke business methods.
What is the difference between Context, InitialContext and Session Context? How they are used?
javax.naming.Context is an interface that provides methods for binding a name to an object. It's
much like the RMI Naming.bind() method.
There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean
for the purpose of the EntityBean accessing the container details. In general, the EJBContext
(SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java
objects in knowing about its 'context' [environment in which they run], and to access particular
information and/or service. Whereas, the javax.naming.Context is for the purpose of 'NAMING' [by
the way of referring to] an object.
EJB 2.0 specification: "An onMessage call is always a separate transaction, because there is never a
transaction in progress when the method is called."
When a message arrives, it is passed to the Message Driven Bean through the onMessage() method,
that is where the business logic goes.
Since there is no guarantee when the method is called and when the message will be processed, is
the container that is responsible of managing the environment, including transactions.
Why are ejbActivate() and ejbPassivate() included for stateless session bean even though they are
never required as it is a nonconversational bean?
To have a consistent interface, so that there is no different interface that you need to implement for
Stateful Session Bean and Stateless Session Bean.
Both Stateless and Stateful Session Bean implement javax.ejb.SessionBean and this would not be
possible if stateless session bean is to remove ejbActivate and ejbPassivate from the interface.
Static variables in EJB should not be relied upon as they may break in clusters.Why?
Static variables are only ok if they are final. If they are not final, they will break the cluster. What
that means is that if you cluster your application server (spread it across several machines) each part
of the cluster will run in its own JVM.
Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that causes
value of the static variable to be increased to 101. On the subsequent call to the same EJB from the
same client, a cluster 2 may be invoked to handle the request. A value of the static variable in cluster
2 is still 100 because it was not increased yet and therefore your application ceases to be consistent.
Therefore, static non-final variables are strongly discouraged in EJBs.
EJB Transaction is automatically rolled back only when a SystemException (or a subtype of it) is
thrown.
no, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in fact,
designed to map a single table.
You shouldn't. What will happen depends on the implementation, but the call will most likely be
ignored.
Can a Session Bean be defined without ejbCreate() method?
The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error
because there is no ejbCreate() method.
• the home interface of a Stateless Session Bean must have a single create() method with no
arguments,
while the session bean class must contain exactly one ejbCreate() method, also without arguments.
• Stateful Session Beans can have arguments (more than one create method)
The EJB 2 Spec (10.8.3 - Special case: Unknown primary key class) says that in cases where the
PrimaryKeys are generated automatically by the underlying database, the bean provider must
declare the findByPrimaryKey method to return java.lang.Object and specify the Primary Key Class as
java.lang.Object in the Deployment Descriptor.
When defining the Primary Key for the Enterprise Bean, the Deployer using the Container Provider's
tools will typically add additional container-managed fields to the concrete subclass of the entity
bean class.
In this case, the Container must generate the Primary Key value when the entity bean instance is
created (and before ejbPostCreate is invoked on the instance.)
What is clustering?
Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value
in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method,only if all objects in session are
serializable. This has to be consider as "passed-by-value", that means that it's read-only in the EJB. If
anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet
Container.
If my session bean with single method insert record into 2 entity beans, how can know that the
process is done in same transaction (the attributes for these beans are Required)?
If your session bean is using bean-managed transactions, you can ensure that the calls are handled in
the same transaction by :
try{
tran=ctx.getUserTransaction();
tran.begin();
myBeanHome1.create(....);
myBeanHome2.create(...);
tran.commit();
}catch(...){}
You may want to check if you're already running in a transaction by calling tran.getStatus().
You can use CMP and BMP beans in the same application... obviously, a bean can be BMP or CMP,
not both at the same time (they are mutually exclusive).
There is a common approach that is normally used and considered a good one. You should start
developing CMP beans, unless you require some kind of special bean, like multi-tables, that cannot
be completely realized with a single bean. Then, when you realize that you need something more or
that you would prefer handling the persistence (performanbce issue are the most common reason),
you can change the bean from a CMP to a BMP.
1. What is EJB?
A server-side component, which manages the architecture for constricting enterprise applications
and managed is called Enterprise JavaBeans(EJB).
They are:
Entity Beans were presented in the earlier versions of EJB consisting of persistent data in distributed
objects.
EJB
They are:
• MANDATORY:
• REQUIRED
• REQUIRES_NEW
• SUPPORTS
• NOT_SUPPORTED
• NEVER
7. What are versions of EJB?
• EJB 3.1
• EJB 3.2
8. What is J2EE?
• Message Driven Beans (MDBs): messages are accepted from other sources besides JMS.
• EJB Timer Service: Mechanism based on an event to invoke EJBs at particular times.
• XML schema
• Message destinations
• Management of Session: Callback methods such as ejbStore (), ejbLoad () are used in the
Developer.
While both undergo activation and passivation; EB have ejbStore () callback to save state through
passivation and ejbLoad () callback to load state through activation. But in case of SS, this is not
needed because S.S.B fields are serialized through objects by containers.
If a conversational state is needed then, Stateful mode is preferred while Stateless paradigm is
preferred for a single business process.
When “one to one” mapping is involved, and the data is stored persistently is regional database,
CMP is preferred. But when no “one to one” mapping is there and data is retrieved from numerous
tables having a complex query, Bean Managed Persistence is used.
The data consistency is maintained by updating their fields every time a commitment of the
transaction is made.
EjbCreate () as being part of the bean’s lifecycle, therefore, it is not mandatory for ejbCreate ()
method to be present and there will be no errors returned by the compiler.
An EJBContext object, the SessionContext is used for accessing the information and container
services.
Yes, remove () can be a Stateless Session bean because the life remains the same till the method is
executed.
Public abstract void ejbActivate (); public abstract void setSessionContext(SessionContext ctx); public
abstract void ejbPassivate();
3
4
10
public abstract void ejbPassivate(); public abstract void setEntityContext(EntityContext ctx); public
abstract void unsetEntityContext(); public abstract void ejbLoad();
24. 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.
The interaction between the client and the bean is called conversational while where multi method
conversations are not held with clients it is known as non-conversational interactions.
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 ().
WAR files contain all servlets, web component pages, gif, html, beans, applets, classes and classes.
When data that did not existed before is inserted, it is read as phantom whereas when data that
already existed is changed, un-repeatable occurs.
• Atomicity: Operations that are bundled together and projected a single unit of job.
• Consistency: Guarantees that after a transaction has taken place, there will be consistency.
• Durability: Ensures durability by keeping a transitional log by which the permanent data be
recreated by again applying the steps involved.
The act of redeployment, deployment and un-deployment in Web logic when the server is running in
EJB is called Hot Deployment.
• Java Servlets
• CORBA
• The JDBCTM data access API.
When the contents having the memory of a single physical m/c are simulated in all m/c in that
cluster, that process is called memory replication.
During runtime, when the changes made in the various properties of server group, are propagated in
every associated clone, this process is known as Ripple Effect.
Server group copies are defined as clone. But unlike Server Groups, clones are linked by means of
nodes.
If the Container is not wanted by the developer for managing transactions, every database operation
can be implemented to write the suitable JDBC code.
A persistent field is returned by the select method of an entity bean that is related. A remote or
local interface is returned by the finder method.
An element of an entity’s bean’s deployment descriptor that defines the persistent fields of bean’s
and the relationship existing between them is known as Abstract Schema. It is specific for each entity
beans which has managed persistence of container.
40. What do you mean by re-entrant? Can you say that session beans as re-entrant? Can entity
beans be specified as re-entrant?
If the entity bean is defined as re-entrant, then it is possible by multiple clients to associate with the
Entity bean and get methods executed concurrently inside the entity bean. Synchronization is taken
care of by container. There is an exception thrown when an entity beam is defined as non-re-entrant
and numerous clients are connected to it concurrently to carry out a method.
• Entity Beans: Entity Beans were presented in the earlier versions of EJB consisting of
persistent data in distributed objects. They had the ability to be saved in different persistent data
stores.
42. Write the basic requirement of a CMP entity based class in 2.0 from EJB 1.1?
The basic requirement of a CMP is an abstract class which the container extends and gets the
methods implemented required for managing the relationships.
43. How can Enterprise JavaBeans be accessed from Active Server Pages?
• ‘Java 2 Platform’
• Enterprise Edition Client Access Services (J2EETM CAS) COM Bridge 1.0 which has been
currently downloaded from the Sun Microsystems.
It is legal technically, but static initializer blocks have been used in executing pieces of code before
the final execution of any method or constructor when a class is instantiated.
JavaDoc doclet, an open source is a doclet which generates good stuff related to EJB from comment
tags of custom JavaDoc, which are embedded in the source file of EJB.
A query language which provides navigation through a network comprising enterprise beans and
objects which are dependent and are defined by methods of container managed persistence. EJB 2.0
was the platform for introduction of EJB QL. It defines methods of finder which are used for entity
beans, which has container managed persistence and has portability across persistence managers
and containers. It is helpful in two kinds of finder methods: Finder methods, which have Home
interface and return objects of entity. Select methods, which remain unexposed for the client to see
but which the Bean provider uses.
Home Object reference is retrieved from the Naming Service via JNDI. Home Object reference is
returned to the client. The steps are:
Yes, it is allowed in cases where data is not inserted by using Java application.
Ans: Most of the time this EJB interview questions is the first questions asked to interviewee, mostly
to check how he responds and how its is different than traditional Java beans. Enterprise java bean is
a server side component which runs on application server or we call container, developed for the
purpose of distributed and enterprise level application .container will provide support for system
level services like Transaction Management, security which make developer task easy and he can
focus on business logic.
This is another beginner level EJB interview questions mostly asked in telephonic interviews and
appeared in 2 to 3 years experience level interviews. Mainly three types of EJB, Entity Bean, Session
Bean and Message Driven Bean(MDB).
Types of EJB:
Entity Bean: it represents an entity which is mapped with database or we can say it makes OR object
Relational mapping with Database. Entity bean typically represent table in RDBMS and each instance
represent row in the table.
• CMP Entity bean: Container managed entity bean its responsibility of container to manage
the bean persistence behavior.
Session bean: Session bean is responsible for developing business logic it makes the client server
relationship so session beans exist till there is a session exist between client and server, it doesn’t
contain persistent business concept.
• Stateless session bean: when there is not need to maintain state of a particular client
stateless session bean is used .They alive for short period of time.
For example if we are validating the credit card we can use stateless session bean.
• Stateful session bean: stateful session bean maintain the conversational state of client over
the series of method call before the bean instance goes to passive state conversational state is saved
to persistence area like Hard disk and again when same client send a request and bean instance
come into the active state it will come out from hard disk to main memory.
For Example when we do online banking transaction ,online reservation we use stateful session
bean
Message Driven Beans: these beans are work as a listener for messaging services like JMS .
Question 3: Explain the life cycle method of EJB?
One for EJB interview questions which is asked in Junior level interviews. I have not seen this EJB
question appeared on more senior level interviews but its good to remember life cycle as here you
have chance to show how much EJB you know in depth.
First stage is Does Not Exist Stage t hen Container creates the instance of EJB and call
SetEntityContext() method which will set all entity context to bean and now it will become available
on pool ,to get a particular identity of an EJB object it has to move from Pooled stage to ready stage
which is done by calling the create () method which in turns call ejbCreate() and ejbPostCreate()
method .
There is another way by which directly entity bean can move to pooled stage to ready stage that’s is
call ejbActivate() method.now we are ready to invoke the business method of entity bean .After
completion of business method if we want to move again in pooled stage from ready stage we can
call remove() method which in turns call ejbRemove() or directly call ejbPassivate () method.
At the end container remove the instance of EJBfrom pool and call unSetEntityContext().
Stateful session beans life cycle starts when client call create() method.The container create the
instance of session bean and call setSessionContext() and ejbCreate() method
Now the stateful session bean is ready to serve the client request after serving the request if it is not
used after a long time container can move this bean to passive stage by calling the ejbPassivate()
method.similarly when bean is in passive stage and client invoke the business method the container
call ejbActivate() method to move bean from passive stage to active or ready stage.
At the end of life cycle client call remove() method and container will call ejbRemove() method and
bean is ready for garbage collection.
Stales session bean has short life cycle it can have two stage does not exist and ready stage. ejb
container create the instance of stateless session bean and call setSessionContext () and ejbCreate()
method.Now the bean is ready to invoke business method on this.it will not maintain the state so
remove () method is been called after completion of business method which in turns call ejbRemove
() and now its ready for garbage collection.
MDBs have same life cycle like stateless session bean. setMessageDrivenContext() method and
ejbCreate() method is called by container to create the instance of MDB.now its ready to receive
message .and at the end of lifecycle client will call remove () method
which in turns call ejbRemove () and now its ready for garbage collection.
This is one of the tricky EJB interview questions which makes you think and some time left you
stunned with feeling like “ Ah , I haven’t thought about it”.
Ans .Purpose of Static initializer block is to initialize some static fields before any execution of
constructor or method or we can say creation of object. According to EJB Spec it’s a violation if static
field are used and they are non final .
“EJB Spec”
Enterprise bean are not allowed to read or write the non final fields.
But technically,from the point of java its correct but if in EJB we use static initializer block to initialize
static field then because EJB components are used in distributed environment mean to say if single
JVM then it will be ok but if run on different JVM then it will be a problem if we change or update
the value in on environment then only the instance running on same JVM have new value .that’s
why static blocks are avoided and also all static field should be final.
Another tricky EJB interview question, I love to ask this kind of question because it shows real
knowledge of EJB which is important to avoid mistakes while writing enterprise Java application.
Ans: No, Not possible because EJBs are created and managed by container and if in ejbs we allow
threading containers life cycle methods will be interrupted by us and also the purpose of EJB is to
perform business logic not to controlling a system or implementation level functioning so container
will manage the thread and developer can concentrate on business logic.
This EJB interview question is neither tough nor easy, as most of Java programmer familiar with
concept of connection pooling that makes it easy but how EJB container does that is something you
want to hear from interviewee.
Ans: Connection pooling is one of the Advance feature of container which enhanced our application
performance .Using connection pooling mechanism client are not required to create every time
connection object to interact with database .Here in pool objects are already available Whenever a
client request for a database connection then an instance is picked from the connection pool to get
an access to database and when user complete with his work instance is returned to connection
pool. There is a limit specified by App server administrator for the availability of number of
connections and beyond a specified limit a predefined number increases numbers of connection
pool instances. When demand goes back to normal then access amount of connection pool instances
are removed.
This is the most popular interview questions asked in EJB in connection of Session Bean. Session
facade not only touch concept of EJB but also it checks design patterns knowledge of interviewee.
Ans: Session Façade is one of the design pattern which is used in EJB component in this pattern
session beans are used as a wrapper classes for entity bean and using session bean we interact with
Entity bean .it will give clean approach towards client access to bean components and also reduce
network calls so as to make the whole system of high performance.
This kind of EJB questions mostly askedin telephonic interviews but believe me its not easy to
answer if you have not really used transaction management feature of EJB. Its easy to mug all these
transaction attribute and spill in interview but once interviewer asked cross question you will most
likely cripple.
Ans: Transaction is group of operation or work which should be performed either completely or
none to maintain the data integrity. All transaction must have ACID property(atomicity
,consistency,integrity,durability) so transaction can be said completed if we commit on successful
execution and rollback on unsuccessful execution.
Transaction Attribute conveys to the container the intended transactional behavior of the associated
EJB component's method.
Required: if required attribute is associated with Method then new Transaction context may or may
not be created, means if method is already associated with transaction context then no new
transaction context should be created.
Requires New: if Requires New attribute is associated with Method then always new Transaction
context may be created.
NotSupported:if Method is Associated with this Attribute then method is a not a part of transaction.
Supported:if a Method is Associated with this transaction Attribute then method will act as Not
supported if calling component is not associated with transaction and if calling component is
associated with transaction then act as a required Attribute.
Mandatory:if a method is Associated with this attribute then always be called from calling
component transaction context.
Never: if a method is Associated with this attribute then never be called from calling component
transaction context.
Ans:Both of these methods are used in context of entity bean for the purpose of synchronizing the
instance variable to corresponding value store in the database. ejbLoad method load or refresh the
instance variable from the database and ejbStore method writes variables value back to the
database.
Question 10: What is the difference between JNDI context, Initial context, session context and ejb
context.
JNDI questions most likely asked in any EJB interview so be prepare for that as well.
Ans:
Session Context:it has all the information available which is required to session bean from
container.
EjbContext:it contain information which is required to both session and entity bean.
These were 10 frequently asked EJB interview questions and answers from my collection. I usually
write down questions collected from my friends and collegue and tries to answers them, if don’t I try
to find it out. Its good to practice EJB questions before appearing in any interview even if you are
working or have worked on EJB.
EJB 3.0
How would EJB 3.0 simplify your Java development compared to EJB 1.x, 2.x ?
EJB 3.0 is taking ease of development very seriously and has adjusted its model to offer the POJO
(Plain Old Java Object) persistence and the new O/R mapping model inspired by and based on
Hibernate (a less intrusive model). In EJB 3.0, all kinds of enterprise beans are just POJOs. EJB 3.0
extensively uses Java annotations, which replace excessive XML based configuration files and
eliminate the need for rigid component model used in EJB 1.x, 2.x. Annotations can be used to
define a bean’s business interface, O/R mapping information, resource references etc. EJB 3.0 also
supports XML files for overriding default values and configuring external resources such as database
connections.
• In EJB 1.x, 2.x the container manages the behavior and internal state of the bean instances at
runtime. All the EJB 1.x, 2.x beans must adhere to a rigid specification. In EJB 3.0, all container
services can be configured and delivered to any POJO in the application via annotations. You can
build complex object structures with POJOs. Java objects can inherit from each other. EJB 3.0
components are only coupled via their published business interfaces hence the implementation
classes can be changed without affecting rest of the application. This makes the application more
robust, easier to test, more portable and makes it easier to build loosely coupled business
components in POJO. The business interface:
@Stateless
@Remote({Account.class})
//..
}
you can also specify multiple interfaces for a session bean. One for local clients and one for remote
clients.
• EJB 3.0 unlike EJB 1.x, 2.x does not have a home interface. The bean class may or may not
implement a business interface. If the bean class does not implement any business interface, a
business interface will be generated using the public methods. If only certain methods should be
exposed in the business interface, all of those methods can be marked with @BusinessMethod
annotation.
• EJB 3.0 defines smart default values. For example by default all generated interfaces are local, but
the @Remote annotation can be used to indicate that a remote interface should be generated.
• The EJB 3.0 (i.e, Inversion Of Control design pattern) container takes care of the creation, pooling
and destruction of the session bean instances and the application only works with the business
interfaces. But if the application needs a finer control over the session beans, for example to
perform database initialization when the container creates the session bean or close external
connection etc, you can implement lifecycle callback methods in the bean class. These methods are
called by the container at various stages(e.g. bean creation and destruction) of the bean’s lifecycle.
Unlike EJB 2.1, where all callback methods must be implemented even if they are empty, EJB 3.0
beans can have any number of callback methods (i.e. even no methods at all) with any method
name. In EJB 3.0, you can specify any bean method as a callback by annotating it with the following
annotations @PostConstruct, @PreDestroy, @PrePassivate, @PostPassivate, @PostActivate, @Init,
@Remove (only for stateful session beans) and @PostConstruct.
//...
@PostConstruct
@PreDestroy
• An MDB (Message Driven Bean) class must implement the MessageListener interface.
• EJB 3.0 makes use of dependency injection to make decoupled service objects and resources like
queue factories, queues etc available to any POJO. Using the @EJB annotation, you can inject an EJB
stub into any POJO managed by the EJB 3.0 container and using @Resource annotation you can
inject any resource from the JNDI.
// ..
• EJB 3.0 wires runtime services such as transaction management, security, logging, profiling etc to
applications at runtime. Since those services are not directly related to application’s business logic
they are not managed by the application itself. Instead, the services are transparently applied by the
container utilizing AOP (Aspect Oriented Programming). To apply a transaction attribute to a POJO
method using annotation:
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public getAccountDetails(){
//..
• In EJB 3.0, you can extend the container services by writing your own interceptors using the
@AroundInvoke annotation. You can specify any bean method as the interceptor method that will
execute before and after any other bean method runs.
@Stateful
// ..
@AroundInvoke
public Object log(InvocationContext ctx) throws Exception {
//..
• EJB 3.0 supports both unidirectional and bidirectional relationships between entity beans. To
create an entity bean, you only need to code a bean class and annotate it with appropriate metadata
annotations. The bean class is a POJO.
@Entity
@id (generate=AUTO)
return this.accountNumber;
//..
• EJB QL queries can be defined through the @NamedQuery annotation. You can also create regular
JDBC style queries using the EntityManager. POJOs are not persistent by birth and become
persistent once it is associated with an EntityManager.
JPA
Ans. Mapping between database tables and java objects called ORM (Object Relational Mapping).
JPA (Java Persistence API) provides and ORM facility for managing relational tables in Java
applications. It is a specification and few implementations are like Hibernate, JDO, EJB, Toplink. By
using JPA can be fetched data, insert, update etc.
Ans. When using JPA need persistence.xml and while using Hibernate API need hibernate.cfg.xml.
When using JPA or Hibernate not needed both xmls, need the xml configuration file according to JPA
or Hibernate.
Ans. Entity manager javax.persistence.EntityManager provides the operations from and to the
database, e.g. find objects, persists them, remove objects from the database, etc. Entities which are
managed by an EntityManager will automatically propagate these changes to the database (if this
happens within a commit statement). These objects are known as persistent object. If the Entity
Manager is closed (via close()) then the managed entities are in a detached state. These are known
as the detached objects. If you want synchronize them again with the database, the a Entity
Manager provides the merge() method. Once merged, the object(s) becomes perstent objects again.
The EntityManager is the API of the persistence context, and an EntityManager can be injected
directly in to a DAO without requiring a JPA Template. The Spring Container is capable of acting as a
JPA container and of injecting the EntityManager by honoring the @PersistenceContext (both as
field-level and a method-level annotation).
While insert, update or fetch record to or from the database we use entity as mapping with
relational tables.
JPA gives you most of the features of plain old Hibernate, except:
No criteria queries in JPA 2.0. Criteria query is a neat feature of Hibernate that constructs query
using Java-based combinators instead of alternate query language, getting the benefit of IntelliSense
and Eclipse’s refactoring tools.
Delete Orphan is a useful annotation that directs Hibernate to deletes entities in a collection if the
parent is deleted, preventing orphaning.
Ans. Entities may use persistent fields, persistent properties, or a combination of both. If the
mapping annotations are applied to the entity’s instance variables, the entity uses persistent fields.
If the mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties,
the entity uses persistent properties.
• Removed
Ans. If the entity class uses persistent fields, the Persistence runtime accesses entity-class instance
variables directly. All fields not annotated javax.persistence.Transient or not marked as Java
transient will be persisted to the data store. The object/relational mapping annotations must be
applied to the instance variables.
Ans. If the entity uses persistent properties, the entity must follow the method conventions of
JavaBeans components. JavaBeans-style properties use getter and setter methods that are typically
named after the entity class’s instance variable names. For every persistent property property of
type Type of the entity, there is a getter method getProperty and setter method setProperty. If the
property is a Boolean, you may use isProperty instead of getProperty. For example, if a Customer
entity uses persistent properties and has a private instance variable called firstName, the class
defines a getFirstName and setFirstName method for retrieving and setting the state of the
firstName instance variable.
Type getProperty()
The object/relational mapping annotations for persistent properties must be applied to the getter
methods. Mapping annotations cannot be applied to fields or properties annotated @Transient or
marked transient.
1) New / Transient: An object is instantiated but not yet associated with an Entity Manager and has
no representation in the database.
2) Managed / Persisted.
3) Detached: Detached entity objects are objects in a special state in which they are not managed by
any EntityManager but still represent objects in the database. Detached objects are often returned
from a persistence tier to the web layer where they can be displayed to the end-user in some form.
Changes can be made to a detached dobject, but these changes won\'t be persisted to the database
until the entity is reassociated with a persistence context (the entity is merged back to an
EntityManager to become managed again).
4) Removed.
- The merge method\'s major task is to transfer the state from an unmanaged entity (passed as the
argument) to its managed counterpart within the persistence context.
- merge deals with both new and detached entities. Merge causes either INSERT or UPDATE
operation according to the sub-scenario (on the one hand it is more robust, on the other hand this
robustness needn\'t be required.)
- persist always causes INSERT SQL operation is executed (i.e. an exception may be thrown if the
entity has already been inserted and thus the primary key violation happens.)
Ans. JPQL (Java Persistence Query Language) offers an object-oriented syntax for expressing query
that is very similar to SQL. The language is interpreted at runtime, which means you cannot use the
compiler to verify the correctness and integrity of a query. To adress this limitation, Hibernate
includes a Criteria API, which allows queries to be expressed programmatically.
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = \"categoryparticipant\")
@NamedQueries({
})
@EmbeddedId
@Basic(optional = false)
@Column(name = \"CreationDate\")
@Temporal(TemporalType.TIMESTAMP)
@ManyToOne(optional = false)
@ManyToOne(optional = false)
public Categoryparticipant() {
this.categoryparticipantPK = categoryparticipantPK;
}
public Categoryparticipant(CategoryparticipantPK categoryparticipantPK, Date creationDate) {
this.categoryparticipantPK = categoryparticipantPK;
this.creationDate = creationDate;
return categoryparticipantPK;
this.categoryparticipantPK = categoryparticipantPK;
return creationDate;
this.creationDate = creationDate;
this.participant = participant;
return category;
this.category = category;
@Override
int hash = 0;
return hash;
@Override
// TODO: Warning - this method won\'t work in the case the id fields are not set
return false;
}
return false;
return true;
@Override
return \"com.xchanging.entity.jpa.Categoryparticipant[categoryparticipantPK=\" +
categoryparticipantPK + \"]\";
• Registering
Ques 12. Give an example of Embeddable class for previous question Categoryparticipant entity.
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class CategoryparticipantPK implements Serializable {
@Basic(optional = false)
@Column(name = \"CategoryId\")
@Basic(optional = false)
@Column(name = \"ParticipantId\")
public CategoryparticipantPK() {
this.categoryId = categoryId;
this.participantId = participantId;
return categoryId;
this.categoryId = categoryId;
return participantId;
}
public void setParticipantId(int participantId) {
this.participantId = participantId;
@Override
int hash = 0;
return hash;
@Override
// TODO: Warning - this method won\'t work in the case the id fields are not set
return false;
if (this.categoryId != other.categoryId) {
return false;
if (this.participantId != other.participantId) {
return false;
return true;
}
@Override
Ans. @Override
@Transactional
try {
logger.info(\"Enter - create()\");
super.create(entity);
logger.info(\"Exit - create()\");
try {
logger.info(\"Enter - findByCategoryId()\");
lQuery.setParameter(\"categoryId\", intValue);
logger.info(\"Exit - findByCategoryId\");
return category;
logger.debug(exception.getCause().getStackTrace());
logger.error(\"CategoryDaoImpl::maxCategoryId()::REASON OF EXCEPTION=\" +
exception.getMessage() + exception.getCause());
} finally {
closeEntityManager();