Вы находитесь на странице: 1из 366

Enterprise JavaBeans (EJB) FAQ From jGuru

Generated Sep 13, 2005 1:25:42 PM

Location: http://www.jguru.com/faq/EJB
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.

When was EJB 1.1 defined?


Location: http://www.jguru.com/faq/view.jsp?EID=317
Created: Nov 4, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

EJB 1.1 is currently in Public Release 2, a non-final preliminary draft. Final release of
the specification is expect by the end of the 4th quarter.

How is Version 1.1 better than Version 1.0?


Location: http://www.jguru.com/faq/view.jsp?EID=318
Created: Nov 4, 1999 Modified: 2000-06-08 00:01:02.717
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

EJB 1.1 requires support for entity beans, which ensures a more consistent
programming model across vendors. In addition, EJB 1.1 addresses many of the
ambiguities and loopholes found in the previous specification. Specific differences
between EJB 1.1 and EJB 1.0 are addressed in the FAQ entry What's different in
Enterprise JavaBeans 1.1.

What's different in Enterprise JavaBeans 1.1?


Location: http://www.jguru.com/faq/view.jsp?EID=319
Created: Nov 4, 1999 Modified: 1999-11-29 15:08:06.607
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

The most significant changes are listed below:

• Entity bean support, both container- and bean-managed persistence, is


required.
• Java RMI-IIOP argument and reference types must be supported, but any
protocol can still be used including IIOP, JRMP, HTTP, or a proprietary protocol.
In other words, the client API must support the Java RMI-IIOP programming
model for portability, but the underlying protocol can be anything.
• The javax.ejb.depoyment package has been dropped in favor of a XML based
deployment descriptor
• Declarative security authorization (access control) has changed to be more
role driven. Also the runAs declarations have been eliminated.
• Declarative isolation levels are no longer available. Isolation levels are now
managed explicitly through JDBC (BMP), the database or other vendor specific
mechanisms.
• The bean-container contract as been enhanced to include a default JNDI
context for accessing properties, resources, (JDBC, JMS, etc), and other
beans.
• The basic EJB roles have been expanded and redefined to better separate
responsibilities involved in the development, deployment, and hosting of
enterprise beans.
Available On-line: A comprehensive examination of the changes made in EJB 1.1
This material is from "Appendix D" of the book Enterprise JavaBeans (O'Reilly 1999)

Does the new specification impact forward compatibility?


Location: http://www.jguru.com/faq/view.jsp?EID=320
Created: Nov 4, 1999 Modified: 1999-11-29 15:12:04.977
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

The new specification requires minor changes to ejbCreate method in container-


managed entity beans as well as changes in how enterprise beans access JDBC
connections, environment properties, and other beans. These changes impact
forward compatibility requiring small changes to any bean that relies on deprecated
EJB 1.0 conventions.

Available On-line:An article in JavaWorld magazine titled "Create forward-compatible


beans in EJB" addressees techniques for creating forward compatible beans.

Available On-line: A comprehensive examination of the changes made in EJB 1.1


This material is from "Appendix D" of the book Enterprise JavaBeans (O'Reilly 1999)

When was EJB 1.0 defined?


Location: http://www.jguru.com/faq/view.jsp?EID=321
Created: Nov 4, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

EJB 1.0 was released as a final specification in March 1997 at JavaOne '97 in San
Francisco.

Is Enterprise JavaBeans 1.0 still viable?


Location: http://www.jguru.com/faq/view.jsp?EID=322
Created: Nov 4, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

Several servers will avoid supporting EJB 1.1 until the new specification is finalized.
Those that do support EJB 1.1 are in beta or were just released. This make EJB 1.0
servers attractive, especially those that have been around a while. For this reason,
EJB 1.0 remains a viable choice for some EJB projects, but make sure you have a
transition plan to upgrade to EJB 1.1 servers when necessary.

Forward compatibly (going from EJB 1.0 to EJB 1.1) is a problem with EJB 1.0 which
is addressed in the FAQ entry Java:API:EJB:1.1: Does the new specification impact
forward compatibility

What is Enterprise JavaBeans?


Location: http://www.jguru.com/faq/view.jsp?EID=340
Created: Nov 5, 1999 Modified: 1999-11-29 14:38:13.752
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

The official Sun Definition:


The Enterprise JavaBeans architecture is a component architecture for the
development and deployment of component-based distributed business applications.
Applications written using the Enterprise JavaBeans architecture are scalable,
transactional, and multi-user secure. These applications may be written once, and
then deployed on any server platform that supports the Enterprise JavaBeans
specification.

Sun Microsystems, Enterprise JavaBeans™Specification, v1.1, published


1999

In Plain English:
Enterprise JavaBeans (EJB) is Sun Microsystems' specification for a distributed object
system similar to CORBA and Microsoft Transaction Server, but based on the Java
platform. EJB specifies how developers should build components that can be
accessed remotely and how EJB vendors should support those components. EJB
components, called enterprise beans, automatically handle transactions, persistence,
and authorization security, so that the developer can focus on the business logic.

What is an enterprise bean?


Location: http://www.jguru.com/faq/view.jsp?EID=341
Created: Nov 5, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

An enterprise bean is a server-side component -- defined in the Java technology --


which adheres to the Enterprise JavaBeans server-side component model. A server-
side component is business object that can be accessed remotely. Many server-side
component models exist: CORBA specifies CORBA objects; Microsoft Transaction
Server (MTS) defines COM/DCOM; and EJB specifies enterprise beans.

Enterprise beans can be developed to represent business concepts like Employee,


Order, TravelAgent, etc. Enterprise beans can be assembled into applications that
solve enterprise business problems.

EJB has two basic types of enterprise beans: Session and Entity. Depending on the
type of enterprise bean used, features like persistence, transactions, security, and
multiple concurrent access can be managed automatically.

Comments and alternative answers

Types of Enterprise JavaBeans


Author: Jayasree Suryadevara
(http://www.jguru.com/guru/viewbio.jsp?EID=713580), Jan 8, 2002

The new type of JavaBeans introduced in EJB 2.0 are Message Driven Beans (MDB)

Message-driven beans (MDBs) are stateless, server-side, transaction-aware


components for processing asynchronous JMS messages
What's so special about Enterprise JavaBeans?
Location: http://www.jguru.com/faq/view.jsp?EID=342
Created: Nov 5, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

Enterprise JavaBeans simplifies the task of developing distributed objects systems.


It's easier for developers to create transactional distributed object applications with
EJB than with any other Java based component architecture. With Enterprise
JavaBeans, transactions, security, and persistence can be handled automatically
allowing developer to focus on the business logic.

Enterprise JavaBeans has been adopted by most distributed object vendors and is
considered a standard for developing distributed object systems in Java. All EJB
vendors must implement the same EJB specification which guarantees a consistent
programming model across servers. In addition, because EJB is widely supported by
many vendors, corporations do not have to worry about vendor lock-in; enterprise
beans will run in any EJB compliant server.

Comments and alternative answers

I must take exception to the comment made: 'In ad...


Author: Jonathan Rasmusson (http://www.jguru.com/guru/viewbio.jsp?EID=1704),
Dec 2, 1999
I must take exception to the comment made: 'In addition, because EJB is widely
supported by many vendors, corporations do not have to worry about vendor lock-in;
enterprise beans will run in any EJB compliant server.' This simple is not true (today).
I have been performing EJB compatiblity tests between SynerJ (Suns application
server purchased recently in the Forte merger) and WebLogic. Because of differences
in deployment descriptor implementations, looseness and changes in the EJB spec,
you simply can not move an EJB from one app server to another. Even the
implementation of the EJB API itself may very from vendor to vendor (as was the
case with SynerJ and WebLogic - they both have different method signatures for the
ejbRemove() method of entity bean. As you probably know, Sun has taken steps to
tighten up the spec, to ensure vendors implement more compatible EJB containers.
Hopefully this time next year, after a few more iterations of the spec, we will be able
to move EJBs from one app server to another. You probably already know all this
already and I may have taken your FAQ out of context. I am just saying people should
be aware that due to the imaturity of the spec, EJBs simply are not portable between
the 40 odd vendors out there. Note: I am a big fan of this site and think you are all
doing an excellent job. Keep up the great work. Yours truly, Jonathan Rasmusson

I agree with Jonathan and I still see EJB in speci...


Author: Subramaniam Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=2599),
Jan 22, 2000
I agree with Jonathan and I still see EJB in specification mode. For enterprises like
mine it is mandatory that we use mature Products not an evolving (probably diverging
specifications). If EJB is not ready yet what is the alternative the Java camp provides
for Enterprise level distributed object computing. Feedback is appreciated.
Subramaniam Kumar

Re: I agree with Jonathan and I still see EJB in speci...


Author: Ravi Sinha (http://www.jguru.com/guru/viewbio.jsp?EID=507506), Oct
1, 2001
In my opinion considering Beans as immature is not a right thing. Though its not a
robust as it ought to be, but careful design and programming can sure get you
good results. Other thing that is not upto the mark, is, total flexibility and ease.
But again the argument comes into picture that how much time you have given
and feel necessary to think of some technology as mature. Obviously continuously
working with some technology as well as eliminating undesired features will sure
help in maturing the technology. I hope that will be taken care in future releases.

What is a session bean?


Location: http://www.jguru.com/faq/view.jsp?EID=730
Created: Nov 9, 1999 Modified: 1999-11-12 04:34:24.275
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

A session bean is a type of enterprise bean; a type of EJB server-side component.


Session bean components implement the javax.ejb.SessionBean interface and can
be stateless or stateful. Stateless session beans are components that perform
transient services; stateful session beans are components that are dedicated to one
client and act as a server-side extension of that client.

Session beans can act as agents modeling workflow or provide access to special
transient business services. As an agent, a stateful session bean might represent a
customer's session at an online shopping site. As a transitive service, a stateless
session bean might provide access to validate and process credit card orders.

Session beans do not normally represent persistent business concepts like Employee
or Order. This is the domain of a different component type called an entity bean.

Comments and alternative answers

A session bean corresponds to a client server session....


Author: Ashish Mital (http://www.jguru.com/guru/viewbio.jsp?EID=31523), Apr 4,
2000
A session bean corresponds to a client server session. The session bean is created
when a client requests some query on the database and exists as long as the client
server session exists.

Re: A session bean corresponds to a client server session....


Author: Sulam Reddy (http://www.jguru.com/guru/viewbio.jsp?EID=1133674),
Dec 12, 2003
A session been corresponds to a client server session.
The session bean is created(server may create new instance or it
may pick from the pool)on the client request. request need not be
related to database.
It is encouraged to use the session beans for business logic
rather for database operation.

Session Beans are generally tied to the lifetime of...


Author: vishal gupta (http://www.jguru.com/guru/viewbio.jsp?EID=1890), Aug 24,
2000
Session Beans are generally tied to the lifetime of a given client session. They are
relatively short-lived; stateful Session objects are created in response to a single
client's request,communicate exclusively with a single client, and die when the client
no longer needs them.

What is a stateful session bean?


Location: http://www.jguru.com/faq/view.jsp?EID=917
Created: Nov 12, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

A stateful session bean is an enterprise bean (EJB component) that acts as a server-
side extension of the client that uses it. The stateful session bean is created by a
client and will work for only that client until the client connection is dropped or the
bean is explicitly removed.

The stateful session bean is EJB component that implements the


javax.ejb.SessionBean interface and is deployed with the declarative attribute
"stateful". Stateful session beans are called "stateful" because they maintain a
conversational state with the client. In other words, they have state or instance fields
that can be initialized and changed by the client with each method invocation. The
bean can use the conversational state as it process business methods invoked by the
client.

Stateful session beans are usually developed to act as agents for the client,
managing the interaction of other beans and performing work on behalf of the client
application. An example is a shopping cart stateful session bean that tracks a client's
product choices and can execute a sale when requested. Below is partial example of
a stateful session bean that is used as a shopping cart.

public class ShoppingCartBean implements javax.ejb.SessionBean {

// instance fields; The conversational state


Vector products = new Vector( );
Customer customer;

// initializes bean with reference to customer bean


public void ejbCreate(Customer cust){
customer cust;
}

//add a product to shopping cart


public void addItem(Product item) {
products.addElement(item);
}

//charge customer for products and create a shipping order


public void executeSale(){

// get the customer's credit card object


CreditCard card = customer.getCreditCard( );

// calculate a total price from products chosen


double total;
for(int i = 0; i products.size(); i++){
Product product =
(Product)products.elementAt(i);
total += product.getPrice( );
}

// get reference to the CreditService bean and


process the customers charge
CreditService cardSwipper = ... get credit card
service bean
Charge charge = cardSwipper.charge(CreditCard,
total);

// get reference to the OrderHome and create a


new shipping order bean (record)
OrderHome orderHome = ... get the Order beans
Home object
Order order = orderHome.create(customer,
products, charge);
}
...
}

In the example above the ShoppingCartBean keeps track of the Customer and the
items chosen by the client application. This is the bean's conversational state. Once
the client application is ready to execute a sale, the ShoppingCartBean manages the
interactions of the Customer, Product, CreditServer, and Order beans in a
workflow that results in a charge against the customers credit card and the creation
of a shipping order. The ShoppingCartBean behaves as an agent for the client
managing the interaction of these other beans, tracking chosen items, and executing
the sale. The below table identifies the beans types used in the ShoppingCartBean
example above.
Bean Name Bean Type
ShoppingCartBean Stateful Session
CreditService Stateless Session
Customer Entity
Product Entity
Order Entity

From the clients perspective only the Customer and ShoppingCart beans are visible,
because the client application works with the bean's remote interface while the bean
itself resides on the server. This means that the client need only be concerned with
the business methods made public by the ShoppingCartBean. Below is an example
of the client applications view of the ShoppingCartBean. (Note: The client interacts
with the beans remote interface not the bean itself. The remote interface is called the
ShoppingCart.)

// somewhere in the client application (applet, servlet, etc.)

// obtain the home objects (factories) for the Customer and


ShoppingCart beans
CustomerHome custHm = ... get CustomerHome
ShoppingCartHome shpCrtHm = ... get ShoppingCartHome

// locate the bean representing the customer named, Bob Johnsten


Customer customer = custHome.findByName("Bob","Johnsten");

// create a new ShoppingCart initialized with the Bob Johnsten Customer


bean
ShoppingCart shoppingCart = shpCrtHm.create(customer);
...
Product product = ... get reference to bean representing the product
chosen
// add product to customer's shopping cart
shoppingCart.addItem(product);
...
//charge customer for products and create a shipping order
shoppingCart.executeSale( );

Session beans like the shoppingCartBean only live as long as the client maintains a
connection. In other words, they represent some aspect of the client's current
session with the system and die when the client ends that session. Session beans are
generally not fault tolerant. A system failure or shut down will result in the death of
session bean and a loss of any conversation state it maintained prior to the failure.
(This is a conceptual lifecycle of a session bean. Some vendors can make them more
fault tolerant and longer lasting).

Comments and alternative answers

Is it possible to show the database design? It would...


Author: Saryu Mehta (http://www.jguru.com/guru/viewbio.jsp?EID=264323), Dec 11,
2000
Is it possible to show the database design? It would be more helpful.

When to use Stateful session beans if it is not fault tolarent?


Author: Kumar Nagarajan (http://www.jguru.com/guru/viewbio.jsp?EID=201408),
Feb 7, 2002
If it is not possible to restore the state of a SFSB in the case of a system crash, when
to use it. How to get around this problem?

What is a stateless session bean?


Location: http://www.jguru.com/faq/view.jsp?EID=925
Created: Nov 12, 1999 Modified: 1999-11-12 11:36:23.253
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

A stateless session bean is an enterprise bean (EJB component) that provides a


stateless service to the client. Conceptually, the business methods on a stateless
session bean are similar to procedural applications or static methods; there is no
instance state, so all the data needed to execute the method is provided by the
method arguments.

The stateless session bean is an EJB component that implements the


javax.ejb.SessionBean interface and is deployed with the declarative attribute
"stateless". Stateless session beans are called "stateless" because they do not
maintain conversational state specific to a client session. In other words, the
instance fields in a stateless session bean do not maintain data relative to a client
session. This makes stateless session beans very lightweight and fast, but also limits
their behavior.

Stateless session beans are usually developed as a set of related and simple
services. Think of a session bean as a functional API where each business method
represents an isolated independent service. An example is a CreditService bean that
provides methods for making charges against different types of credit cards (MC,
Visa, Discovery, etc).

public class CreditService implements javax.ejb.SessionBean {

public Charge charge (String accountToCredit, CreditCard card,


double amount)
throws ValidationException, RemoteException{

// attempt to obtain Merchant bean representing the


retailer making the charge.
try{
MerchantHome mrchntHome = ... get VendorHome
reference
Merchant merchant =
mrchntHome.findByPrimaryKey(vendorToCredit);
}catch(ObjectNotFoundException onfe){
throw new ValidationException("Invalid
merchant account number");
}

// attempt to create a Charge bean based on the vendor,


amount, and credit card info
try{
ChargeHome chgHome = ... get ChargeHome reference
Charge charge = chgHome.create(merchant, card,
amount);
return charge;
}catch(CreateException ce){
throw new ValidationException(ce.getMessage());
}
}
...
}

In the above example the CreditService bean method charge( ) is completely


independent of the bean state or any other methods. The charge( ) method is a
stateless service and the CreditService bean is a stateless bean. The charge( )
method uses two other bean types to process the charge. Its normal for stateless
beans to use other beans but they can also access the database directly or even
other resources like proprietary connections. Below is a list the beans used in this
example.

Bean Name Bean Type


CreditService Stateless Session
Merchant Entity
Charge Entity

An example of how the CreditService bean could be used by a client application or


bean is shown in the FAQ entry Java:API:EJB:SessionBean:Stateful:What is a
stateful session bean?

Comments and alternative answers

What happens if remove( ) is never invoked on a session...


Author: Shibu TN (http://www.jguru.com/guru/viewbio.jsp?EID=18320), Feb 26,
2000
What happens if remove( ) is never invoked on a session bean?

Re: What happens if remove( ) is never invoked on a session...


Author: Pradip Khisti (http://www.jguru.com/guru/viewbio.jsp?EID=81675), Mar
26, 2002
The remove method on the Statless Bean is just a hint to the container by the
Client to remove it from the pool.It totally depends on the EJB Container how to
handle Instance pooling of session Beans.Hence it is safe not to invoke the remove
method

What is an entity bean?


Location: http://www.jguru.com/faq/view.jsp?EID=1075
Created: Nov 16, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

An entity bean is a type of enterprise bean; a type of EJB server-side component.


Entity bean components implement the javax.ejb.EntityBean interface and can be
container-managed (CMP) or bean-managed (BMP). Entity beans are designed to
represent data in the database; they wrapper data with business object semantics
and read and update data automatically.
Entity beans have identity, where each bean represents a unique set of data. An
entity bean of type Customer, for example, would have thousands of identities -- one
for each customer in the database. Entity beans can be safely shared by many
clients, so that several applications can access the same bean identity at the
concurrently.

A bean developer might choose to create a Customer bean to represent customer


data in the database. The bean developer decides what data from the database
represents a customer and how customers are uniquely identified. The bean
developer also decides what business methods the Customer bean expose and what
data can be changed or read. Below is the server-side component definition of a
Customer bean.

public class CustomerBean implements javax.ejb.EntityBean {

// persistent fields
public long customerNumber;
public Date lastActive;
public String lastName;
public String firstName;

// initialization method for creating a new customer


public CustomerKey ejbCreate(long id, PersonName name){
customerNumber = id;
setName(name);
lastActive = new Date();
return new CustomerKey(id);
}

// business methods
public PersonName getName( ){
return new PersonName(firstName, lastName);
}
public void setName(PersonName name){
lastName = name.getLastName();
fistName = name.getFirstName();
}
public Date lastActive( ){
return lastActive;
}
...
}
Note: Only a subset of the bean code normally implemented is shown here
for brevity. Ordinarily the bean would also implement special EJB specific
callback methods that are not important to this FAQ entry.

The ejbCreate( ) method is used only once in the life type of a bean identity when
its first created. In this case we initialize the bean with the customer's id number and
name. The lastActive value is set within the method. The ejbCreate( ) creates
and returns the customer bean's identity, which is called a primary key in EJB. A
primary key is a object that represents a unique identifier for a bean. In the case of
the Customer bean the primary key is the CustomerKey which is an object that
wrappers the customer's id. Primary keys can be as simple as a String value or more
be more complicated like a key that wraps several values that together represent a
unique index to the bean identity. Below is the definition of the CustomerKey object.

public class CustomerKey implements java.io.Serializable {


public long id;

public CustomerKey(long l)
{
id = l;
}
public int hashCode( ) {
return (int)id;
}
public boolean equals(Object otherKey){
if(otherKey instanceof CustomerKey)
return ((CustomerKey)otherKey).id == this.id;
else
return false;
}
}

You will notice that the business methods do not exactly match the persistent fields.
This illustrates that the persistent state of the bean need not map exactly to the
business methods, which provides more flexibility in how components are designed.
For example, instead of having an accessor for lastName and firstName, the
Customer bean uses a serializable PersonName to pass this information to and from
the bean's client. In addition, you will have noticed that the lastActive can only be
read by a bean client. The bean itself is responsible for updating this value.

In addition to the business methods and the ejbCreate( ) methods there are a
number of notification methods that the bean container (EJB server) uses to alert
that bean that some significant event in its lifecycle is about to, or just has, occurred.
Of particular importance are the two notification methods (ejbLoad( ) and
ejbStore( )) used to alert the bean when its being synchronized with the database.
The behavior of these methods changes depending on whether the bean is designed
for BMP or CMP. This is investigated in more detail under the FAQ entries
Java:API:EJB:EntityBean:BMP and Java:API:EJB:EntityBean:CMP.

Comments and alternative answers

Thx Richard; also thx for your EJB book. Something...


Author: Mark Lorenz (http://www.jguru.com/guru/viewbio.jsp?EID=118221), Aug 3,
2000
Thx Richard; also thx for your EJB book.

Something that has bothered me all along about Session and Entity beans is that
Entity beans are referred to as representing data. Rather, Entity beans should represent
concepts in my business domain (e.g. TradingCommunity or TradingHub), with the
database merely providing persistence for the business domain objects' state.
I could see Session beans being useful in the case of fat clients, but since our project
is all thin web clients I'm not even sure when I'd use a Session bean. E.g., in our
model a TradingHub "holds" TradingCommunities and can use findByXxx() methods
on the TradingCommunityHome as needed (e.g. if not already instantiated or not kept
in memory due to large #s of instances).

So, why would I pull business functionality out of these classes (e.g.
TradingHub.addCommunity() ) and put them into a Session bean? What have I gained
besides another class to maintain (and, which is bad, separation of behavior from the
class that should be responsible for it)?

TIA, Mark Lorenz

Mark Lorenz...
Author: Chetan Gadgil (http://www.jguru.com/guru/viewbio.jsp?EID=435319),
Jun 7, 2001
This has annoyed me also. Entities should not be used as just "struct"s. Actually
putting the business logic in the entities solve many of management issues. The
new "EJBLocal" interface will also help avoiding fine grained objects on the
client side. This can still be achieved with the older spec by simply NOT returning
fine grained Entity beans to the client. The main business entity "knows" how to
hide contained entities when needed, anyway.

Re: Thx Richard; also thx for your EJB book. Something...
Author: Ed Page (http://www.jguru.com/guru/viewbio.jsp?EID=786586), Mar 7,
2002
Mark: I just read your book-OO SWD, A PG; I am a novice in your world and am
sincerely trying to learn. It is unusually and immensely readable! I wonder if you
could please compare/contrast for me your method with RUP, XP and the "agile"
methods?

What is a CMP bean?


Location: http://www.jguru.com/faq/view.jsp?EID=1087
Created: Nov 16, 1999 Modified: 2000-04-11 11:39:36.811
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

CMP: Container-Managed Persistence


A CMP bean is an entity bean whose state is synchronized with the database
automatically. In other words, the bean developer doesn't need to write any explicit
database calls into the bean code; the container will automatically synchronize the
persistent fields with the database as dictated by the deployer at deployment time.

When a CMP bean is deployed, the deployer uses the EJB tools provided by the
vendor to map the persistent fields in the bean to the database. The persistence
fields will be a subset of the instance fields, called container-managed fields, as
identified by the bean developer in the deployment descriptor.

In the case of a relational database, for example, each persistent field will be
associated with a column in a table. A bean may map all its fields to one table or, in
the case of more sophisticated EJB servers, to several tables. CMP are not limited to
relational database. CMP beans can be mapped to object databases, files, and other
data stores including legacy systems.

With CMP, the bean developer doesn't need to write any database access logic into
the bean, but bean is notified by the container when its state is synchronized with
the database. The container notifies the bean using the ejbLoad( ) and
ejbStore( ) methods.

The ejbLoad( ) method alerts the bean that its container-managed fields have just
been populated with data from the database. This gives the bean an opportunity to
do any post processing before the data can be used by the business methods. The
ejbStore( ) method alerts the bean that its data is about to be written to the
database. This give the bean an opportunity to do any pre-processing to the fields
before they are written to the database. The below bean code demonstrates how
these method might be employed on a Customer CMP entity bean.

public class CustomerBean implements javax.ejb.EntityBean {

// container-managed fields
public long customerNumber;
public String lastName;
public String firstName;

// not a container-managed field


public PersonName name = null;

// business methods
public PersonName getName( ){
return name;
}
public void setName(PersonName name){
name = name;
}
// called just after container-managed fields are updated from
database
public void ejbLoad( ){
name = PersonName(firstName, lastName);
}
// called just before container-managed fields are written to
database
public void ejbStore( ){
lastName = name.getLastName( );
firstName = name.getFirstName( );
}
...
}
In the case of the Customer bean the ejbLoad( ) and ejbStore( ) are used to
wrapper the name fields (lastName and firstName) in a PersonName object which is
more user friendly for the bean client. The ejbLoad( ) method wrappers the fields
so that the getName( ) method access an up-to-date copy of the name data. The
ejbStore( ) method unwraps the name data and places them back into the
container-managed fields so that the database is updated with the most recent
changes.

The ejbLoad( ) and ejbStore( ) methods are typically called just before a
transaction begins and when a transaction is about to commit. This ensures that the
container-managed fields are synchronized with the database when the bean is in
use. Some EJB servers will optimize the container so that data is not written to the
database unless its dirty; that container-managed fields have been changed.

CMP is the most difficult EJB feature for vendors to support. It requires very
sophisticated tools for mapping bean fields to a data source and generating the
underlying stubs and skeletons to support this mapping. CMP, however, provide a
unique opporutnity for organizations developing distributed object systems. With
CMP, a shrink-wrapped bean ( a bean developed by a third party) can be deployed
and mapped into an organization's existing database. Obviously, this is an idyllic
scenario, but not unreasonable. CMP entity beans exemplify the spirit of component
technology; the reuse of components across projects, organizations, and industries.

Note: CMP beans use the ejbLoad( ) and ejbStore( ) callback methods differently than the Bean-
Managed Persistence (BMP) beans. See Java:API:EJB:EntityBean:BMP for details on how BMP beans use
these methods.

What is a BMP bean?


Location: http://www.jguru.com/faq/view.jsp?EID=1090
Created: Nov 16, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

BMP: Bean-Managed Persistence


A BMP bean is an entity bean that synchronizes its state with the database manually.
In other words, the bean developer must code explicit database calls into the bean
itself. BMP provides the bean developer with more flexibility in the how the bean
reads and writes its data than a container-managed persistence (CMP) bean. CMP
bean is limited to the mapping facilities provided by the EJB vendor, BMP beans are
only limited by skill of the bean developer.

The ability to code an entity bean's persistence logic explicitly is important when the
EJB container's CMP features are insufficient to meet the needs of the entity bean.
Entity beans that need to synchronize their state with several data sources are
excellent candidates for BMP. So are beans that need to access to data sources
(possibly legacy systems) that are not supported by CMP. In addition, BMP bean are
often employed when a vendors CMP facilities are not sophisticated enough to handle
complex Object-to-Relational mapping.

The BMP bean manages its own persistence, but relies on the container to coordinate
its reads and writes so that persistence is accomplished in a transactional safe
manner. Coordination with the container is accomplished through two mechanisms:
The persistence callback methods (ejbLoad( ) and ejbStore( )); and the
Environment Naming Context (EJB).

The ejbLoad( ) and ejbStore( ) methods notify a bean that its time to read and
write data to the database respectively. In a BMP entity bean the code for reading
and writing data to the database is done within these methods. The ejbLoad( ) is
called at the beginning of a transaction, just before any business methods are
executed, and the ejbStore( ) is called at the end of a transaction just before its
committed. This keeps the bean state in perfect synchronization with transactions
being executed, without the bean developer having to explicitly manage the
transactional operations.

When JDBC is used to for persistence, the Environment Naming Context (ENC) is a
JNDI namespace that provides the bean with access to database connections (among
other things). The database connections obtained from the JNDI ENC are managed
by the container, so that they are automatically enrolled in transactions and pooled.
(The extent to which this is supported depends largely on the EJB vendor.) The
container may also manage other data source APIs, but JDBC is standard.

Below is an example of an entity bean, the Customer bean that is designed to use
BMP to synchronize its own state with a CUSTOMER table in the database.

public class CustomerBean implements javax.ejb.EntityBean {

// persistent bean-managed fields


public long customerNumber;
public String lastName;
public String firstName;

// non-persistent context fields


public javax.naming.Context jndiContext;
public javax.ejb.EntityContext ejbContext;

// business methods
public PersonName getName( ){
return new PersonName(firstName, lastName);
}
public void setName(PersonName name){
firstName = name.getFirstName( );
lastName = name.getLastName( );
}
// called just before a business method can be invoked at the
beginning of a transaction
public void ejbLoad( ){
try{
javax.sql.DataSource ds =
(DataSource)jndiContext.lookup("java:comp/env/jdbc/Database");
java.sql.Connection con = ds.getConneciton( );
PreparedStatement ps =
con.prepareStatement("select lastname, firstname
from CUSTOMER where id = ?");
CustomerKey key = (CustomerKey)ejbContext.getPrimaryKey(
);
customerNumber = key.id;
ps.setLong(1, customerNumber);
java.sql.ResultSet result = ps.executeQuery( );
while(result.next()){
lastName = result.getString("lastname");
firstName = result.getString("firstname");
}
con.close();

}catch(Exception e){
throw new EJBException(e);
}
}

// called at the end of a transaction just before a commit is


attempted
public void ejbStore( ){
try{
javax.sql.DataSource ds =
(DataSource)jndiContext.lookup("java:comp/env/jdbc/Database");
java.sql.Connection con = ds.getConneciton( );
PreparedStatement ps =
con.prepareStatement("update CUSTOMER set lastname
= ?, firstname = ? where id = ?");
ps.setString(1, lastName);
ps.setString(2, firstName);
ps.setLong(3, customerNumber);
if( ps.executeUpdate( ) != 1)
throw new EJBException("SQL update failed.
ejbStore( ) failed");
con.close();

}catch(Exception e){
throw new EJBException(e);
}
}
...
}
Note: BMP beans use the ejbLoad( ) and ejbStore( ) callback methods differently than the
Container-Managed Persistence (CMP) beans. See Java:API:EJB:EntityBean:CMP for details on how CMP
beans use these methods.
Comments and alternative answers

I think this example works perfectly with J2EE server...


Author: Vallur Narasimhan (http://www.jguru.com/guru/viewbio.jsp?EID=50672),
May 17, 2000
I think this example works perfectly with J2EE server but mostly people use only
weblogic so please feel kind to attach source code that works with weblogic server
from GI Solutions India
Narasimhan.V.Vallur
Re: I think this example works perfectly with J2EE server...
Author: srini phani (http://www.jguru.com/guru/viewbio.jsp?EID=541467), Nov 7,
2001
I developed a statelesssession bean and successfuly deployed it to the
server.Counterfit I wrote the client code from which i am accessing the home and
remote interface. It throws me an error in the JNDI context the error is as follows :
javax.ejb.EJBException - with nested exception:
[javax.naming.NameNotFoundException: Unable to resolve comp/env/jdbc/ds
Resolved: 'comp/env' Unresolved:'j dbc' ; remaining name 'ds'] what is that we
have to give in the (java:comp/env/ ? / ?) !!!!!!!!!! I have mentioned ds since it is
the same name i have mentioned for the sql connection pool in the weblogic server.
Can you help me out. thanks Srini

Does anybody have the Deployment Descriptor for this...


Author: IQbal Khan (http://www.jguru.com/guru/viewbio.jsp?EID=283544), Jan 2,
2001
Does anybody have the Deployment Descriptor for this bean? I am particularly
interested in the JDBC resource settings.

Are Enterprise JavaBeans and JavaBeans the same thing?


Location: http://www.jguru.com/faq/view.jsp?EID=1109
Created: Nov 17, 1999 Modified: 2000-04-26 23:45:08.617
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

Enterprise JavaBeans and JavaBeans are not the same thing; nor is one an extension
of the other. They are both component models, based on Java, and created by Sun
Microsystems, but their purpose and packages (base types and interfaces) are
completely different.

JavaBeans
The original JavaBeans specification is based on the java.beans package which is a
standard package in the JDK. Components built on the JavaBeans specification are
intraprocess components that live in one address space and are typically used for
Graphical User Interface (GUI) as visual widgets like buttons, tables, HTML viewers,
etc.

Enterprise JavaBeans
The EJB specification is based on the javax.ejb package, which is a standard
extension package. Components built on the EJB specification are interprocess
components that live in multiple address spaces as distributed object. These
components are used as transactional business objects that are accessed as remote
objects.

Comments and alternative answers

I think the following paragraph illustrates better...


Author: Ramu Meda (http://www.jguru.com/guru/viewbio.jsp?EID=280486), Dec 18,
2000
I think the following paragraph illustrates better the difference:

JavaBeans components are small-grained application bits. You can use JavaBeans to
assemble larger-grained components or to build entire applications. JavaBeans,
however, are development components and are not deployable components. You
typically do not deploy a JavaBean because a JavaBean is not a complete application;
rather, JavaBeans help you construct larger software that is deployable. And because
they cannot be deployed, JavaBeans do not need a runtime environment in which to
live. JavaBeans do not need a container to instantiate them, to destroy them, and to
provide other services to them because the application itself is made up of JavaBeans.
By way of comparison, the Enterprise JavaBeans (EJB) standard defines a component
architecture for deployable components called enterprise beans. Enterprise beans are
larger, coarser-grained application components that are ready to be deployed. They
can be deployed as is, or they can be assembled with other components into larger
application systems. Deployable components must be deployed in a container that
provides runtime services to the components, such as services to instantiate
components as needed.

I disagrre
Author: Iain Kerr (http://www.jguru.com/guru/viewbio.jsp?EID=981384), Nov 27,
2002
I think the former paragraph illustrates better. The key piece of understanding is
that a JavaBean runs in its own address spaces. I think its vital that this is
understood to fully understand JavaBeans.

Re: I disagrre
Author: capsvikas sharma
(http://www.jguru.com/guru/viewbio.jsp?EID=1110954), Aug 26, 2003
well guys its a comparision between Client side javabeans and EJB. Can we
compare server side javabeans with EJB

thanks

Vikas

coarser-grained
Author: praveen chandra (http://www.jguru.com/guru/viewbio.jsp?EID=1237281),
Apr 8, 2005

Hi,

Can you please exaplain what is coarser-grained and fine grained in detail with
examples? Thanks, Chandra
What is passivation and activation?
Location: http://www.jguru.com/faq/view.jsp?EID=1195
Created: Nov 22, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

Passivation and activation are two phases of a resource management technique that
reduces the number of bean instances needed to service all clients. Passivation is the
process of disassociating a bean instance from its EJB object so that the instance can
be reused or evicted to conserve memory. Activation is the process of associating a
bean instance with an EJB object so that it can service a request. Beans are
passivated when there is a lull in their use and activated when the EJB object
receives a client request.

The java.ejb.SessionBean and javax.ejb.EntityBean interface include two


callback methods that notify a bean instance when it is about to passivated or
activated. The ejbPassivate( ) method notifies a bean that it is about to
passivated; the ejbActivate( ) method notifies a bean that it is about to activated.

The mechanisms employed in passivation and activation change depending on the


bean type. Stateful beans are usually evicted, while entity beans and stateless beans
are pooled. A more detailed account of how different bean types passivated and
activated is found under the FAQs for that type.

Comments and alternative answers

A little correction. java.ejb.SessionBean appered...


Author: Ning Wu (http://www.jguru.com/guru/viewbio.jsp?EID=251003), Nov 13,
2000
A little correction. java.ejb.SessionBean appered in the article should be
javax.ejb.SessionBean

SLSB and passivation.


Author: Sanjeev Dhiman (http://www.jguru.com/guru/viewbio.jsp?EID=1089967),
May 31, 2004
Stateless Session beans are never passivated :)

How does passivation work in stateful session beans?


Location: http://www.jguru.com/faq/view.jsp?EID=1196
Created: Nov 22, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

Unlike entity beans and stateless session beans, stateful session bean are usually
evicted from memory when they are passivated. This is not true of all vendors but
this view serves as good model for understanding the concepts of passivation in
session beans.

When a stateful bean experiences a lull in use -- between client invocations and
transactions -- the container may choose to passivate the stateful bean instance. To
conserve resources the bean instance is evicted from memory (dereferenced and
garbage collected). When the EJB object receives a new client request, a new
stateful instance is instantiated and associate with the EJB object to handle the
request.

Stateful beans maintain a conversational state, which must be preserved before the
bean instance is evicted from memory. To accomplish this, the container will write
the conversational state of the bean instance to a secondary storage (usually disk).
Only the non-transient serializable instance fields are preserved. When the bean is
activated the new instance is populated with the preserved state. References to live
resources like the EJBContext, DataSource, JNDI ENC, and other beans must also be
maintained somehow -- usually in memory -- by the container.

The javax.ejb.SessionBean interface provides two callback methods that notify the
bean instance it is about to passivated or was just activated. The ejbPassivate( )
method notifies the bean instance that it is about have its conversational state
written to disk and be evicted from memory. Within this method the bean developer
can perform operations just prior to passivation like closing open resources. The
ejbActivate( ) method is executed just after a new bean instance has been
instantiated and populated with conversational state from disk. The bean developer
can use the ejbActivate( ) method to perform operations just prior to servicing
client request, like opening resources.

Comments and alternative answers

excellent description..
Author: puru naktode (http://www.jguru.com/guru/viewbio.jsp?EID=36717), Apr 18,
2000
excellent description..

It is even more complicated


Author: Kirill Fakhroutdinov (http://www.jguru.com/guru/viewbio.jsp?EID=501201),
May 7, 2002
The non-serializable issue for me is that according to EJB 1.0 and 1.1 specifications
"Declaring the enterprise Bean’s fields as “transient” is, in general,
discouraged." So, if I do not want something to be passivated what should I do?

Even worse, if I do have some fields that are not serializable by design (say, from
security or performance reasons) - again, according to specifications "The container
may destroy an instance if the instance is not serializable after ejbPassivate."
Because serialization is checked dynamically we can have stateful instances just
simply destroyed by container if some instance variables happened not to be
serializable.

So, for transient by design fields instead of declaring them transient, we have to
assign them null in ejbPassivate() (to prevent EJB instance from being destroyed
when attempting to serialize), and in ejbActivate() we need to recreate these transient
fields ourselves.
EJB STATEFUL SESSION PASSIVATION
Author: bhanu kiran (http://www.jguru.com/guru/viewbio.jsp?EID=1039587), Dec
19, 2002
Since the state is stored in Hard disk if system/server crashes can we maintain the
state once it restored

How does a client application create a transaction object?


Location: http://www.jguru.com/faq/view.jsp?EID=2566
Created: Dec 14, 1999 Modified: 2000-08-03 22:25:31.928
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

How you gain access to UserTransaction objects varies depending on the type of
client. Enterprise JavaBeans provides two types of transaction management:

• Container-managed transactions. As the name implies, the EJB container


makes the decisions (based on the deployment descriptor's trans-attribute
setting) regarding how to bundle operations into transactions and then works
with the transaction manager, which manages the transaction processing.
• Bean-managed transactions. In this case, a session bean obtains the
UserTransaction object via the EJBContext using the
getUserTransaction() method.

JMS clients can bundle several messages in a transaction simply by using a


transactional session--a UserTransaction object is not required. To create a
transactional session, use either QueueConnection.createQueueSession() or
TopicConnection.createTopicSession() with true as the first argument. (Some
JMS implementations support JTA, so that it's also possible to obtain a
UserTransaction object from the JMS server.)

In other environments, for example, a web server that supports servlets and/or
JavaServer Pages (JSP), a JMS server, and others, you obtain a UserTransaction
object via JNDI. Of course, for a servlet to obtain a UserTransaction object, there
must be a JTS-capable server to deliver the object.

Typically, the server provides the JNDI look-up name either directly or via a system
or server property. For example, with the WebLogic server, you would use a code
segment similar to the following:

...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction)
c.lookup("javax.jts.UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...

With J2EE implementations, you obtain the UserTransaction object with a code
segment similar to the following:
...
Context c = new InitialContext();
UserTransaction ut = (UserTransaction)
c.lookup("java:comp/UserTransaction");
ut.begin();
// perform multiple operations...
ut.commit()
...

If the environment provides the UserTransaction object via a system property, you
would use a code segment similar to the following:

...
String transName = System.getProperty("jta.UserTransaction");
Context c = new InitialContext();
UserTransaction ut = (UserTransaction) c.lookup(transName);
ut.begin();
// perform multiple operations...
ut.commit()
...

JNDI remote look-up names and property names vary, of course, across
servers/environment.

Comments and alternative answers

WebLogic does it differently


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 14, 2003
In WebLogic 6.1, the JNDI name of the UserTransaction is either
javax.transaction.UserTransaction
or
weblogic.transaction.UserTransaction
I have found that the standard (?) JNDI name "java:comp.UserTransaction" or
"java:comp/UserTransaction" does not always work.

WebSphere 5.0
Author: Christoph Ernst (http://www.jguru.com/guru/viewbio.jsp?EID=1106402),
Aug 6, 2003
In WebSphere 5.0 the JNDI-Lookup works like
UserTransaction ut = (UserTransaction)
ctx.lookup("jta/usertransaction");
See e.g. http://www-
3.ibm.com/software/webservers/appserv/doc/v30/ae/web/doc/ent_beans/atswpgec.htm

Re: WebSphere 5.0


Author: Ralf Taugerbeck (http://www.jguru.com/guru/viewbio.jsp?EID=1119711), Oct 6, 2003

The link above is a bit outdated (from WAS 3.0 documentation). Check the current Infocenter for detai
support in WAS 5.0:
http://publib.boulder.ibm.com/infocenter/wasinfo/index.jsp?topic=/com.ibm.websphere.base.doc/info/a

The lookup "jta/usertransaction" is still supported for J2EE apps with a spec level of 1.2 or lower. But
1.3 or later "java:comp/UserTransaction" is demanded.

Re[2]: WebSphere 5.0


Author: William Koscho
(http://www.jguru.com/guru/viewbio.jsp?EID=1148721), Feb 24, 2004
I am familiar with looking up the JNDI reference, but I am having trouble
defining the UserTransaction in Websphere. Can someone help me to set it up?
How do I create a javax.transaction.UserTransaction object and map it to
"java:comp/UserTransaction"? I am using WSAD 5.1 - any help is appreciated.
Thanks, Bill

Re[3]: WebSphere 5.0


Author: Donato Marrazzo
(http://www.jguru.com/guru/viewbio.jsp?EID=1179813), Jun 18, 2004

You don't need set up nothing. java:comp/UserTransaction is implicitly


defined, just use it!

From J2EE 1.3 specs: "The J2EE platform must provide an object
implementing the javax.transaction.UserTransaction interface to all web
components. The platform must publish the UserTransaction object in the
Java™ Naming and Directory Interface (JNDI) name space available to
web components under the name java:comp/UserTransaction."

Re[4]: WebSphere 5.0


Author: himanshu Sharma
(http://www.jguru.com/guru/viewbio.jsp?EID=1241678), Apr 29, 2005
We have a set of interface programs that use Open Adaptor framework for
interfacing with external apps using MQ Series, JMS & Databases . The
interface programs run in seperate JVMs and most of the time access at
least two resources such as MQ and Database tables. Therefore it is
neccesary to provide a two phase commit to preserve transacttion integrity
across interface boundaries. In order to meet this requirement we need to
understand how we can use WAS 5.1.1 (JTS impl) for XA compliant
Datasources and JMS queues.

I also feel that accessing WAS (Transaction Manager or UserTransaction


object advertised over JNDI) is prohibited for client applications (seperate
JVMs) other than the web apps.
using java:comp/UserTransaction
Author: Radhakrishnan Nariangadu
(http://www.jguru.com/guru/viewbio.jsp?EID=752623), Aug 4, 2005

Can I use the J2EE JNDI lookup even within a EJB container?

I'm developing a Hibernate based DB component that will provide a uniform


transactional interface anywhere,ie, J2EE container or normal JVM. Therefore within
a Bean managed Session bean, rather than obtaining UserTransaction from the
EJBContext will everything work smoothly if I obtain the UserTransaction using the
JNDI lookup?

I'm planning to switch to a non-managed configuration based on whether I can create


an InitialContext. This will allow the same code to be unit tested in eclipse without
having to run it within a App server.

...thanks in advance

Do JTS implementations support nested transactions?


Location: http://www.jguru.com/faq/view.jsp?EID=2569
Created: Dec 14, 1999 Modified: 2000-08-03 22:05:39.612
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

A JTS transaction manager must support flat transactions; support of nested


transactions is optional. If a client begins a transaction, and within that transaction
begins another transaction, the latter operation will throw a NotSupportedException
if the JTS implementation does not support nested transactions.

Keep in mind that even if the JTS implementation supports nested transactions, this
transaction manager-level support does not guarantee support for nested
transactions in an application. For example, the EJB 1.1 specification does not
support nested transactions.

Why would a client application use JTA transactions?


Location: http://www.jguru.com/faq/view.jsp?EID=2576
Created: Dec 14, 1999 Modified: 2000-08-03 22:03:56.209
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

One possible example would be a scenario in which a client needs to employ two (or
more) session beans, where each session bean is deployed on a different EJB server
and each bean performs operations against external resources (for example, a
database) and/or is managing one or more entity beans. In this scenario, the client's
logic could required an all-or-nothing guarantee for the operations performed by the
session beans; hence, the session bean usage could be bundled together with a JTA
UserTransaction object.
In the previous scenario, however, the client application developer should address
the question of whether or not it would be better to encapsulate these operations in
yet another session bean, and allow the session bean to handle the transactions via
the EJB container. In general, lightweight clients are easier to maintain than
heavyweight clients. Also, EJB environments are ideally suited for transaction
management.

Comments and alternative answers

Why would a client application use JTA transactions?


Author: Mayank Jain (http://www.jguru.com/guru/viewbio.jsp?EID=791863), Mar
12, 2002
Do you think this would be a good approach? The client can have a Facade Session
Bean in which the server could handle all the Transactions.

How does a session bean obtain a JTA UserTransaction object?


Location: http://www.jguru.com/faq/view.jsp?EID=2577
Created: Dec 14, 1999 Modified: 2000-08-03 22:19:19.481
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

If it's necessary to engage in explicit transaction management, a session bean can be


designed for bean-managed transactions and obtain a UserTransaction object via
the EJBContext using the getUserTransaction() method. (It may also use JNDI
directly, but it's simpler to use this convenience method.)

Comments and alternative answers

Do you mean "use JNDI" or "use JTA&...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 3, 2000
Do you mean "use JNDI" or "use JTA"? How would you do it with JNDI?

Why would a session bean use bean-managed transactions?


Location: http://www.jguru.com/faq/view.jsp?EID=2578
Created: Dec 14, 1999
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

In some situations, it's necessary for a (stateful) session bean to selectively control
which methods participate in transactions, and then take over the bundling of
operations that form a logical unit of work.

Comments and alternative answers

Good explanation
Author: Santosh Malpekar (http://www.jguru.com/guru/viewbio.jsp?EID=30121),
Mar 30, 2000
Good explanation
Comments
Author: Suresh S (http://www.jguru.com/guru/viewbio.jsp?EID=320716), Apr 10,
2001
If some scenarios would have given, it would be better to understand. Thanks

How does an enterprise bean that uses container-managed transactions


obtain a JTA UserTransaction object?
Location: http://www.jguru.com/faq/view.jsp?EID=2579
Created: Dec 14, 1999 Modified: 2000-08-03 21:49:20.023
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

It doesn't! By definition, container-managed transaction processing implies that the


EJB container is responsible for transaction processing. The session bean has only
limited control of transaction handling via the transaction attribute.

Is it possible for a stateless session bean to employ a JTA UserTransaction


object?
Location: http://www.jguru.com/faq/view.jsp?EID=2580
Created: Dec 14, 1999 Modified: 2000-08-03 22:06:23.29
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

Yes, but with restrictions. By definition, a stateless session bean has no state; hence,
each method invocation must be independent. (The bean can be "swapped out"
between method invocations.) Thus, a stateless session bean can obtain a
UserTransaction object via the EJBContext using the getUserTransaction()
method, but it must start and finish each transaction within the scope of a method
invocation.

How do you configure a session bean for bean-managed transactions?


Location: http://www.jguru.com/faq/view.jsp?EID=2581
Created: Dec 14, 1999 Modified: 2000-08-24 18:54:58.201
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

You must set transaction-type in the deployment descriptor.

Comments and alternative answers

What do you set transaction-type to?


Author: Vikas Gholba (http://www.jguru.com/guru/viewbio.jsp?EID=126575), Aug
14, 2000
What do you set transaction-type to?

Re: What do you set transaction-type to?


Author: Sukanya Subramanian
(http://www.jguru.com/guru/viewbio.jsp?EID=382541), Mar 21, 2001
Bean

Bean Managed
Author: Rajeev Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=334960), Feb
23, 2001
Bean Managed

How do you configure the transaction characteristics for a session bean with
container-managed transactions?
Location: http://www.jguru.com/faq/view.jsp?EID=2582
Created: Dec 14, 1999 Modified: 2000-08-24 18:55:27.106
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

You must set trans-attribute in the deployment descriptor.

Comments and alternative answers

Set it to what? Can we have some sample code for the...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 3, 2000
Set it to what? Can we have some sample code for the DD?

Re: Set it to what? Can we have some sample code for the...
Author: Damodara Rao (http://www.jguru.com/guru/viewbio.jsp?EID=428922),
May 26, 2001
Within one transaction one row has to be inserted in oracle database throuh CMP
EntityBean and the visibility of that row has to be made for inserting some other
row in some other table because of constraints.How to make it visible within the
transaction?

Re[2]: Set it to what? Can we have some sample code for the...
Author: selva raju (http://www.jguru.com/guru/viewbio.jsp?EID=594229),
Dec 23, 2001
I am not how you have the Entity Bean Design for that.But I think the
following will be the Solution for you. Create one Method in Session Bean
with the transaction Attribute as "Required" and call the Both the Entity Beans
from that method.Here I have assumed that you two different entity beans to
represent the two different tables.And specity the transaction attribute for the
create method of the Entity Beans as "Supports" or "Required".

How does an entity bean obtain a JTA UserTransaction object?


Location: http://www.jguru.com/faq/view.jsp?EID=2583
Created: Dec 14, 1999 Modified: 2000-08-03 21:59:28.181
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

It doesn't. Entity beans do not employ JTA transactions; that is, entity beans always
employ declarative, container-managed transaction demarcation. Entity beans, by
definition, are somewhat tightly coupled (via the EJB container and server) to a
datastore; hence, the EJB container is in the best position to manage transaction
processing.
Comments and alternative answers

The entity bean is not tightly coupled to the unde...


Author: gaurav sharma (http://www.jguru.com/guru/viewbio.jsp?EID=210078), Sep
19, 2000
The entity bean is not tightly coupled to the underlying persistence framework. In fact
the components are loosely coupled and are tightly cohesive with the interface. The
container transaction API's enable the binding of components to the data interface
layer transparently to the implementation of the component.

Is it necessary for an entity bean to protect itself against concurrent access


from multiple transactions?
Location: http://www.jguru.com/faq/view.jsp?EID=2584
Created: Dec 14, 1999 Modified: 2000-08-03 22:26:36.274
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

No. One of the motivations for using a distributed component architecture such as
Enterprise JavaBeans is to free the business logic programmer from the burdens that
arise in multiprogramming scenarios.

Comments and alternative answers

The answer to this question is really misleading in...


Author: dan benanav (http://www.jguru.com/guru/viewbio.jsp?EID=8173), Jan 25,
2000
The answer to this question is really misleading in my opinion.

It is true that calls to the bean instance's methods are serialized, however calls to the
entity
object are not. That means from the client's perspective calls to the methods can
occur concurrently.
The bean provider also has to be aware of and code for that.

For example, suppose you have a bean that has a qty field and a method called
updateQuantity.
Then you could define updateQuantity in the bean class as

public void updateQty(int q){ qty -=q; }

However this could lead to incorrect behavior because the container is free to create
several
instances of the bean to process method requests. Calls to these methods (on two
different beans) can occur
concurrently and that is the problem. So for example each instance gets the qty from
the database
and could start out with the same qty. When the qty is decreased in each of two calls
in two
transactions each bean would decrease it's qty and store it back to the database. Here
is a better picture,

Transaction 1 calls updateQty. Container uses bean1 to process request.


Transaction 2 calls updateQty on the same entity object. Container uses bean2 to
process request.
Container calls ejbLoad on bean1 which gets qty from a database. Value is 1.
Container calls ejbLoad on bean2 which gets qty from a database. Value is 1.
Container calls bean1 updateQty. qty field in bean1 becomes 0.
Container calls bean2 updateQty. qty field in bean2 becomes 0.
Container calls ejbStore on bean1 which stores 0 into the database.
Container calls ejbStore on bean2 which stores 0 into the database.

This of course is the wrong answer. I should store -1 into the db.

There is a common misconception that since the container serializes calls to the bean
instance that calls to the bean object are serialized. Hence the programmer must
either serialize calls to the object or must use features of the database to handle the
above situation. Serializing calls to the entity and session objects does not happen
automatically. For session objects the container will throw an exception if the calls
happen concurrently. Even many companies that develop ejb servers hold these
misconceptions.

Re: The answer to this question is really misleading in...


Author: Mayank Jain (http://www.jguru.com/guru/viewbio.jsp?EID=791863), Mar
12, 2002
hi dan, If your answer is with respect to EJB 1.0 or EJB 1.1 specifications then
you may be right... But as far as I know according to EJB 2.0 specifications... the
client may or may not serialize his calls to an entity bean.... it is the container's
responsibility to serialize the transactions (in case of Commit option A) or allow
shared access to instances(in case of Commit Option B or Commit Option C).

With respect to the comment given by dan henany -- The...


Author: Vallur Narasimhan (http://www.jguru.com/guru/viewbio.jsp?EID=50672),
May 17, 2000
With respect to the comment given by dan henany --
The instance methods of the beans are serialized with respect to transactions but not
individually with respect to methods. So just declarative knowledge is enough.

Is an EJB, JMS, or general-purpose Java application server a transaction


manager?
Location: http://www.jguru.com/faq/view.jsp?EID=2586
Created: Dec 14, 1999 Modified: 2000-08-03 22:04:29.484
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)
It depends on the server implementation. The JTA and JTS specifications define
client-, application-, and transaction manager-level operations. There is nothing to
prevent a Java application server from implementing, JMS, EJB, and JTS functionality.
On the other hand, it could (if available) obtain transaction manager services
indirectly from another server.

How do beans manage resource connections to back-end services other


than databases ?
Location: http://www.jguru.com/faq/view.jsp?EID=2990
Created: Dec 20, 1999
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

While EJB 1.1 provides the JNDI ENC for managing standard resources like URL,
JDBC, JavaMail and JMS, connections to other types of resources are not addressed
by EJB 1.0 or EJB 1.1, but there are solutions. Below is a list of some strategies that
can provide access to "back-ends" besides relational databases.

Leveraging the instance fields:


Each EJB vendor implements resource management differently. In EJB servers where
the instance is pooled and reused it may be possible to allow a back-end resource
connection to be maintained through passivation. The back-end connection might
wrapped in a CORBA or Java RMI object, accessed by a raw network socket, or some
other connection facility.

This strategy works in stateless session beans and entity beans in EJB servers that
pool and reuse these bean types. In stateless beans you can simply reference the
resources using the instance fields -- stateless beans are not passivated in EJB. In
entity beans you can also reference the connections using instance fields but the field
used must not be declared as a container-managed field in the deployment
descriptor.

In both stateless and entity beans there are methods can be used safely to open and
close resource connections at the beginning and end of the beans life.

In stateless session beans long-lived resources should be opened in the


setSessionContext( ) method and closed in the ejbRemove( ) method. These
methods are invoked at the beginning and end of a stateless session instance's life;
when it's first instantiated and before its evicted form the container.

In entity beans long-lived resource should be opened in the setEntityContext( )


method and closed in the unsetEntityContext( ) method. These methods are
invoked at the beginning and end of an entity instance's life; when it's first
instantiated and before its evicted form the container.

CORBA or Java RMI Services:


CORBA objects or Java RMI objects can be created that wrapper usual resources and
expose them to the bean. These types of remote references will need to be handled
with care as they can be affected by passivation, but the remote objects themselves
are not part an EJB container and therefor are not passivated.
In stateful session beans the references will need to be released and re-constituted
when the bean is activated using some kind of naming facility native to the reference
type.

With stateless and entity beans the above strategy, Leveraging the instance fields
works well with this strategy.

JNDI references:
It may be possible to access a JNDI service directly from the bean and to attach live
resources to the JNDI service. This depends on the JNDI service provider and your
EJB vendor.

Wait for EJB 2.0:


The next version of EJB, which may be branded EJB 2.0, is supposed to include a
Connection specification that details how connections to non-standard resources can
be make available to beans at run time. If this is done correctly it will solve this
problem, but who knows when or if it will be incorporated into the specification. Don't
hold your breath.

How can I access my EJBs from COM environments such as VB?


Location: http://www.jguru.com/faq/view.jsp?EID=4551
Created: Jan 11, 2000 Modified: 2001-01-29 17:04:31.597
Author: Damian Mehers (http://www.jguru.com/guru/viewbio.jsp?EID=4550)

Note: This question was answered by the vendor.

[One possible solution is J-Integra]


The J-Integra pure Java-COM bridge can be used to access EJBs running in any
Application Server, in any JVM on any machine from COM clients such as Visual Basic
or Microsoft Transaction Server.

See the Step-by-Step EJB example at: http://www.linar.com/jintegra/doc/

Please also see the following FAQ for more products.

Comments and alternative answers

this is also a good idea but i want to know how you...


Author: Shoubhik Chakraborty
(http://www.jguru.com/guru/viewbio.jsp?EID=47506), May 10, 2000
this is also a good idea but i want to know how you can access simple java .class files
, its thru wrapper idl classes frm VC but for that u need 'javatlb' tool of java , where to
find it plz. mail me to shoubhik_c@hotmail.com

Re: this is also a good idea but i want to know how you...
Author: sridhar yeragorla (http://www.jguru.com/guru/viewbio.jsp?EID=507726),
Oct 1, 2001
Hi chkraborty, now javatlb is outdated. we got a separate integration toll jactivex.
you can enter the name jactivex in msdn search and get the step by step procedure.
Re[2]: this is also a good idea but i want to know how you...
Author: Sarit Seal (http://www.jguru.com/guru/viewbio.jsp?EID=1005041),
Sep 27, 2002
You can have a Com Client a C++ program and then connect to java class
using JNI.

What are the constraints or drawbacks of container managed EJB's ?


Location: http://www.jguru.com/faq/view.jsp?EID=5072
Created: Jan 15, 2000 Modified: 2000-01-16 06:05:55.869
Author: Sameer Tyagi (http://www.jguru.com/guru/viewbio.jsp?EID=4381)

CMP in beans depends a lot on the EJB vendor implementation and utilities. With
some implementations container-managed entity beans can only by mapped to one
table, while other implemenations offer Multiple table mappings to a single bean. The
bottom line,It depends on the container provider being used.
Comments and alternative answers

Container Managed EJB's


Author: Nick Knight (http://www.jguru.com/guru/viewbio.jsp?EID=464493), Jul 30,
2001
Many implementations do not handle querying very well when a large result set is
expected. Using CM beans causes a large number of bean instances to be created.
Instead, session beans should be used with the use of a JDBC driver and a vector to
store the results.

What are the constraints or drawbacks of container managed EJB's ?


Author: Rajeev Hans (http://www.jguru.com/guru/viewbio.jsp?EID=1180311), Jun
21, 2004
CMP can't be used if your back-end is not a relational database (e.g. any legacy ERP
system ) atleast at the time of my writing this comment.

Is entity data persisted at the end of a transaction or at any time?


Location: http://www.jguru.com/faq/view.jsp?EID=5115
Created: Jan 16, 2000 Modified: 2000-08-03 22:08:10.663
Author: Sameer Tyagi (http://www.jguru.com/guru/viewbio.jsp?EID=4381)

Depends on what you mean by "persisted". Data that is part of a transaction like
database rows are persisted depending on the success of the transaction. If the
transaction manager determines that the transaction was successful or there were no
problems during any of the steps invoved in it, the data is committed, or otherwise
rolled back.

The container, on the other hand, invokes certain state transition lifecycle methods to
conserve resources. This involves passivation and activation of the bean or instance
swapping. This happens independent of the transaction since the client never
interacts directly with the bean instance but with the server's implementation of the
EJBObject.
Comments and alternative answers

So I think the answer is: The data is written to...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 3, 2000
So I think the answer is:

The data is written to the database after every change (which means potentially after
every method call), but in a state determined by the transaction level. Later, when the
transaction is complete, the data may be committed or rolled back.

How can my JSP page communicate with an EJB Session Bean?


Location: http://www.jguru.com/faq/view.jsp?EID=5314
Created: Jan 17, 2000 Modified: 2000-01-20 10:56:07.612
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

The following is a code snippet that demonstrates how a JSP page can interact with
an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of
the session bean
AccountHome accHome=null;

public void jspInit() {


//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>
Comments and alternative answers

It is a good practise to use as little Java code as...


Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479),
Apr 15, 2000
It is a good practise to use as little Java code as possible in a JSP as possible. In the
above example, the JSP page designer has to deal with and understand the mechanics
of accessing an EJB. Instead encapsule the EJB mechanics in a Mediator and expose
the EJB methods as methods of the Mediator. Use the Mediator in the JSP. The
Mediator is usually written by the EJB developer. The Mediator can provide
additional value like attribute caching etc.

Re: It is a good practise to use as little Java code as...


Author: Chris Pearson (http://www.jguru.com/guru/viewbio.jsp?EID=1140678),
Jan 23, 2004
Can a EJB initiate a call to the JSP first?

There's also the ejbutils tag library available from...


Author: Joseph Ottinger (http://www.jguru.com/guru/viewbio.jsp?EID=37791), Apr
19, 2000
There's also the ejbutils tag library available from Orion, which makes this very easy
to do.

I wonder if there are any EJB Vendors that create Beans...


Author: Gautam Bajekal (http://www.jguru.com/guru/viewbio.jsp?EID=54828), May
23, 2000
I wonder if there are any EJB Vendors that create Beans for you whenever EJB's are
deployed. The Beans would encapsulate the EJB Session bean creation and methods.
That would be a neat feature to have.

See also What is the most efficient approach for i...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 29,
2000
See also What is the most efficient approach for integrating EJB with JSP?

Another way of communicating between a JSP and a S...


Author: Nagaraj shyagale (http://www.jguru.com/guru/viewbio.jsp?EID=29160), Dec
1, 2000
Another way of communicating between a JSP and a Session Bean is through
Servlets. That is, to follow the MVC architecture using the Model as EJB, Controller
as a Servlet and the View as a JSP.

this all is very exiting ...can you just give the ...
Author: pinak vedalankar (http://www.jguru.com/guru/viewbio.jsp?EID=269419),
Mar 15, 2001
this all is very exiting ...can you just give the example of the above case... any one ex
...in which jsp page calls java bean and which in turn called EJB

What are all the different kinds of servers? (Such as Web Servers,
Application Servers, etc)
Location: http://www.jguru.com/faq/view.jsp?EID=5917
Created: Jan 20, 2000 Modified: 2000-12-20 10:06:49.031
Author: Paul Danckaert (http://www.jguru.com/guru/viewbio.jsp?EID=5801)

The servers involved in handling and processing a user's request break down into a
few basic types, each of which may have one or more tasks it solves. This flexibility
gives developers a great deal of power over how applications will be created and
deployed, but also leads to confusion over what server is able to, or should, perform
a specific task.

Starting at the basic level, a user is typically submitting a request to a system


through a web browser. (We are conveniently ignoring all other types of clients (RMI,
CORBA, COM/DCOM, Custom, etc..) for the time being for purposes of clarity.) The
web request must be received by a Web Server (otherwise known as an HTTP
Server) of some sort. This web server must handle standard HTTP requests and
responses, typically returning HTML to the calling user. Code that executes within the
server environment may be CGI driven, Servlets, ASP, or some other server-side
programming language, but the end result is that the web server will pass back
HTML to the user.

The web server may need to execute an application in response to the users request.
It may be generating a list of news items, or handling a form submission to a guest
book. If the server application is written as a Java Servlet, it will need a place to
execute, and this place is typically called a Servlet Engine. Depending on the web
server, this engine may be internal, external, or a completely different product. This
engine is continually running, unlike a traditional CGI environment where a CGI
script is started upon each request to the server. This persistance gives a servlet
connection and thread pooling, as well as an easy way to maintain state between
each HTTP request. JSP pages are usually tied in with the servlet engine, and would
execute within the same space/application as the servlets.

There are many products that handle the web serving and the servlet engine in
different manners. Netscape/iPlanet Enterprise Server builds the servlet engine
directly into the web server and runs within the same process space. Apache requires
that a servlet engine run in an external process, and will communicate to the engine
via TCP/IP sockets. Other servers, such as MS IIS don't officially support servlets,
and require add-on products to add that capability.

When you move on to Enterprise JavaBeans (and other J2EE components like JMS
and CORBA) you move into the application server space. An Application Server is
any server that supplies additional functionality related to enterprise computing -- for
instance, load balancing, database access classes, transaction processing,
messaging, and so on.

EJB Application Servers provide an EJB container, which is the environment that
beans will execute in, and this container will manage transactions, thread pools, and
other issues as necessary. These application servers are usually stand-alone
products, and developers would tie their servlets/JSP pages to the EJB components
via remote object access APIs. Depending on the application server, programmers
may use CORBA or RMI to talk to their beans, but the baseline standard is to use
JNDI to locate and create EJB references as necessary.

Now, one thing that confuses the issue is that many application server providers
include some or all of these components in their product. If you look at WebLogic
(http://www.beasys.com/) you will find that WebLogic contains a web server, servlet
engine, JSP processor, JMS facility, as well as an EJB container. Theoretically a
product like this could be used to handle all aspects of site development. In practice,
you would most likely use this type of product to manage/serve EJB instances, while
dedicated web servers handle the specific HTTP requests.

See also: What is the difference between an Application Server and a Web Server?

Comments and alternative answers

The following link provides a list of all available...


Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14), Feb 3,
2000
The following link provides a list of all available web servers (HTTP servers). It also
offers detailed information regarding the functionality offered by each of them.

http://serverwatch.internet.com/webservers.html

Here's a great comparison chart listing all the Java...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 12, 2000
Here's a great comparison chart listing all the Java application servers:
http://www.flashline.com/Components/appservermatrix.jsp

There are three types of servlet engines: 1) StandAlone...


Author: Shuchi Agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=30635), May
2, 2000
There are three types of servlet engines: 1) StandAlone Servlet Engine: It is a web
server that includes built in support for servlets.For eg Java Web Server etc. 2) Add on
Servlet Engine:It functions as a plug-in for an existing server,a server that was not
originally designed with servlets in mind.For eg JServ, JRun,IBM WebSphere etc. 3)
Embeddable Servlet Engine:It is a lightweight server deployment platform that can be
embeddable in another application. That application becomes the true server.For eg
JavaServerEngine etc.

what are all the different web servers that support...


Author: krishna murthy (http://www.jguru.com/guru/viewbio.jsp?EID=274676), Dec
21, 2000
what are all the different web servers that support servlet 2.0 technology ?

how to decide up on the which servlet enebled web server to use for developing a web
based application ?

Good Response Paul Danckaert !


Author: Jeevie S (http://www.jguru.com/guru/viewbio.jsp?EID=3836), Sep 5, 2001
I came across this response after a long time from it's post date, but it's very good.

How do enterprise beans access native libraries?


Location: http://www.jguru.com/faq/view.jsp?EID=8831
Created: Jan 25, 2000 Modified: 2000-01-26 05:15:13.433
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by telmo sa (http://www.jguru.com/guru/viewbio.jsp?EID=5055

In short, they don't.

The EJB 1.1 Specification, section 18.1.2 (Programming Restrictions) lists some
things that enterprise beans cannot do. In particular:

• The enterprise bean must not attempt to load a native library.

This function is reserved for the EJB Container. Allowing the enterprise bean to load
native code would create a security hole.

The EJB 1.1 specification is available for download from


http://java.sun.com/products/ejb/docs.html.

Comments and alternative answers

They cannot access JNI portably. Basically, given...


Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4), May 3, 2000

They cannot access JNI portably. Basically, given comments recently made by Mark
Hapner, it seems that the "must not" is not a hard constraint but rather a "must not do
if you want the EJB to be portable."

Certainly, IMHO, the security issue trumps the portability issue so it's a moot point.
:-)

Of course, if you want to write unportable/unsecure...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 5, 2000
Of course, if you want to write unportable/unsecure EJBs, a good place to start is the
jGuru JNI FAQ.

Can I extend the discussion here a little? The security...


Author: Mark Hagan (http://www.jguru.com/guru/viewbio.jsp?EID=103511), Jul 17,
2000
Can I extend the discussion here a little? The security issue confuses me a bit. What
would be an example of a security breach?

Also, not that it's relevant to security but, I was planning on having my EJB call out to
other java classes which contained the static loading and native method calls. Any
reason why this wouldn't work?

Thanks.

The reason why the EJB spec does not supports this...
Author: harish ganesan (http://www.jguru.com/guru/viewbio.jsp?EID=347623), Mar
8, 2001
The reason why the EJB spec does not supports this interface to native libraries is
that: 1.The EJB compoenents we develop should be in intention of true distribution
2.the application developers should not develop bean components that are not
resuable and portable to different EJb containers because it ties u up to single ejb
vendor

I'm also somewhat confused by this restriction. For...


Author: Richard Steele (http://www.jguru.com/guru/viewbio.jsp?EID=343953), Mar
13, 2001
I'm also somewhat confused by this restriction. For example, how would type 2 JDBC
drivers work if the bean cannot load native libraries?

I have to create an EJB for a system that's accessible through a C library. My initial
reaction was to create a JNI implementation of the client interface, called by the EJB.
But this means it won't be portable, though from the comments here it might still
work.

So, can it be done or not?


Author: Ralph Cook (http://www.jguru.com/guru/viewbio.jsp?EID=3483), Apr 11,
2001
All the FAQs and specs and google searches just say that EJB's can't load native
libraries (the container needs to do that) but they don't say much about using native
functions. We want to put a servlet/EJB front on some legacy code. Realizing that it
may not be the most "standard" or "portable", is it possible?

Robustness is sacrificed as well


Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602), Oct 6,
2001

I was faced with the issue of calling a native application from an EJB on a recent
project. In the process of investigating various alternatives, we attempted using JNI
(under WebLogic 5.1 running on Solaris 2.7). It worked, at least in that WebLogic
allowed it to happen and the calls worked. However, in testing the robustness of the
solution we had the native code perform a divide-by-zero. The resulting exception
crashed WebLogic.

So even if your particular application server allows the EJB to load and call a native
library, and even if you don't care about portability or security (and I'm not sure I
understand the security issue here), you better really trust your C code 'cause it's not
just going to take down a single transaction.

Also, an earlier response asked about having a non-EJB class do the loading of the
native library. The EJB spec states that the restrictions on EJBs apply to all classes
running in the EJB container. So it's all the same.
BTW, we solved our issue by modifying the native application to run as a persistent
service and then communicated with it through a socket. If you do this, the native app
has to be the socket listener as EJBs aren't allowed to listen to ports (for obvious
reasons).

How do I implement a logging system in my beans?


Location: http://www.jguru.com/faq/view.jsp?EID=8993
Created: Jan 26, 2000 Modified: 2000-05-29 11:46:07.715
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

Using java.io is prohibited


Using the java.io package from within a bean is prohibited. The EJB 1.1
Specification, section 18.1.2 (Programming Restrictions) states the following:
An enterprise bean must not use the java.io package to attempt to access files
and directories in the file system.

The file system APIs are not well-suited for business components to access data.
Business components should use a resource manager API, such as JDBC API, to
store data.

The EJB 1.1 specification is available for download from


http://java.sun.com/products/ejb/docs.html

Alternative Solutions
To perform logging operations you must you a resource connection supported by the
EJB programming model. EJB servers may support several resource connection
options, which can be used to log events as shown below:

• JDBC (javax.sql.DataSource) : Write log events in to a relational database.


• URL (java.net.URL) : Write log events to a custom logging server or post
them to a web server.
• JavaMail (javax.mail.Session) : E-mail log events to a special account
• JMS (javax.jms.QueueConnectionFactory |
javax.jms.TopicConnectionFactory) : Send the log events as messages.

Comments and alternative answers

Some other common alternative solutions include si...


Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362), Apr
10, 2000
Some other common alternative solutions include singleton RMI or CORBA servers.
All of these alternatives are potentially expensive...
Author: John Huang (http://www.jguru.com/guru/viewbio.jsp?EID=231461), Oct 18,
2000
All of these alternatives are potentially expensive operations in terms of performance.
I like to know what is the consequence if using java.io package. Is it scalibility issue,
robusness issue or else? EJB 1.1 Specification does not tell you why. I can understand
why it is not good to store business data in file system.

My reading of the EJB spec is that it doesn't preclude...


Author: Mark Wutka (http://www.jguru.com/guru/viewbio.jsp?EID=7136), Nov 20,
2000
My reading of the EJB spec is that it doesn't preclude using System.out to log
messages. It doesn't ban java.io altogether, just the use of java.io to access files
and directories in the file system.

I think the reasoning behind the restriction is that there's an assumption that the file
access storage/retrieval must be transactionable and the file system isn't. Writing the
System.out isn't really the same as storing data, so you could argue that it doesn't
violate the restriction.

You could argue this one either way and I'd like to see Sun clarify it. I have noticed
that several of Sun's example EJB's make use of System.out, though, which leads me
to believe that it's legal.

logging: consider using log4j


Author: Geert Mergan (http://www.jguru.com/guru/viewbio.jsp?EID=382575),
Mar 20, 2001
I suggest doing logging with log4j, a wonderful logging framework:

• Logging to System.out is not forbidden by the ejb spec so at least for that
log4j is usable.
• I will also log to files. I know this does violate the EJB spec, but certain
parts of EJB spec can be broken without too many problems. And I can
always switch off logging to files if it turns out to mess things up.

Log4j is Apache open source: www.log4j.org

Re: logging: consider using log4j


Author: Eibhlis Ni She (http://www.jguru.com/guru/viewbio.jsp?EID=920094),
Jul 22, 2002
Hi there I am trying to extend our use of the log4j framework. I would like to
use the NDC class to uniquely stamp each request but I am finding it difficult to
find examples of implementations on the web. Do you have any suggestions?
Cheers Eibhlis

Re: logging: consider using log4j


Author: Jim Shain (http://www.jguru.com/guru/viewbio.jsp?EID=16877), Feb
24, 2003
The post is old so this question will be retorical. If certain parts of the EJB spec
can be broken, then why do the authors use the words "must not" instead of
"should not". This sounds a little like Bill Clinton, define "is". Maybe the
authors should have referenced RFC 2119. In there it states:
2. MUST NOT This phrase, or the phrase "SHALL NOT", mean that
the definition is an absolute prohibition of the specification.
Then maybe we could debate the term absolute. Speaking of absolute, I think
I'll go have a drink.

Re: My reading of the EJB spec is that it doesn't preclude...


Author: Greg Duclos (http://www.jguru.com/guru/viewbio.jsp?EID=477365), Aug
15, 2001
I'm pretty sure I read somewhere that you can use java.io in an EJB because the
EJB container might not have a filesystem, ie. if the container is a database.

Re: My reading of the EJB spec is that it doesn't preclude...


Author: ahmedyaser ahmedyaser
(http://www.jguru.com/guru/viewbio.jsp?EID=897758), May 30, 2002
EJBs support non-transactional operations as well, so to me, file system being non-
transactional can't be a reason.

I think we need a concrete explanation for this. We have a scenario in which we


need to read a database and generate files in a certain format, for interfacing with
external systems. How is this possible in a pretty way without doing file I/O from
EJBs?

Re[2]: My reading of the EJB spec is that it doesn't preclude...


Author: michael lu (http://www.jguru.com/guru/viewbio.jsp?EID=923019),
Jun 21, 2002
Basically what EJB wants to resolve is the transaction system. Typically that'll
be OLTP system involving heavy database access. Because there's SQL
standard for Relational database system, it's easy for EJB to standardize on
that model. However, both semantics and implemenations of different file
systems (UFS, JFS, NTFS, EXT2FS, whatever, even virtually there are no
standard locking mechnism for them) tend to be quite different AND that
really hurts one important goal of EJB - Portability. So if you base your
application heavily on file system access, then EJB will be an overkill for it
probably. However, I DO think it's only not recommended to do file
manipulation in EJB while it's still legitimate to do some simple file
operations. Otherwise, how can you dump debug info to System.out and
System.err streams? But I'd like to say that relying on file access in EJB could
become a very tricky programming practice. So even if you can do that, use
that at your own risk. Besides, JDK prior to 1.4 (even including 1.4) provides
only limited file operating capability IMHO.

Custom request context passed through from Client


Author: Gordon Sim (http://www.jguru.com/guru/viewbio.jsp?EID=513657), Oct 8,
2001
On the subject of logging, is there a nice way to attach custom context info to a
request on a bean, so that client side logs can be more easily related to server side
logs?

i.e. I want to have a sessionid in every log entry, but dont want to have to make this a
parameter of every call. One option may be to use the caller principal, since I dont
actually require the use of this for security.

Log4j and other logging solutions


Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382), Aug 4,
2002
http://jakarta.apache.org/log4j/

http://jakarta.apache.org/commons/logging/

java.util.logging
http://java.sun.com/j2se/1.4/docs/guide/util/logging/

Protomatter Syslog
http://protomatter.sourceforge.net/

What is a container?
Location: http://www.jguru.com/faq/view.jsp?EID=9876
Created: Jan 29, 2000
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

Enterprise beans are software components that run in a special environment called
an EJB container. The container hosts and manages an enterprise bean in the same
manner that a Java WebServer hosts a Servlet or an HTML browser hosts a Java
applet. An enterprise bean cannot function outside of an EJB container. The EJB
container manages every aspect of an enterprise bean at run time including remote
access to the bean, security, persistence, transactions, concurrency, and access to
and pooling of resources.

The container isolates the enterprise bean from direct access by client applications.
When a client application invokes a remote method on an enterprise bean, the
container first intercepts the invocation to ensure persistence, transactions, and
security are applied properly to every operation a client performs on the bean. The
container manages security, transactions, and persistence automatically for the bean,
so the bean developer doesn't have to write this type of logic into the bean code
itself. The enterprise bean can focus on encapsulating business rules, while the
container takes care of everything else.
Containers will manage many beans simultaneously in the same fashion that a Java
WebServer manages many Servlets. To reduce memory consumption and processing,
containers pool resources and manage the lifecycles of all the beans very carefully.
When a bean is not being used a container will place it in a pool to be reused by
another client, or possibly evict it from memory and only bring it back when its
needed. Because client applications don't have direct access to the beans -- the
container lies between the client and bean -- the client application is completely
unaware of the containers resource management activities. A bean that is not in use,
for example, might be evicted from memory on the server, while its remote reference
on the client remains intact. When the client invokes a method on the remote
reference, the container simply re-incarnates the bean to service the request. The
client application is unaware of the entire process.

An enterprise bean depends on the container for everything it needs. If an enterprise


bean needs to access a JDBC connection or another enterprise bean, it does so
through the container; if an enterprise bean needs to access the identity of its caller,
obtain a reference to itself, or access properties it does so through the container. The
enterprise bean interacts with its container through one of three mechanisms:
callback methods, the EJBContext interface, or JNDI.

Callback Methods: Every bean implements a subtype of the EnterpriseBean


interface which defines several methods, called callback methods. Each callback
method alerts the bean of a different event in its lifecycle and the container will
invoke these methods to notify the bean when it's about to pool the bean, persist its
state to the database, end a transaction, remove the bean from memory, etc. The
callback methods give the bean a chance to do some housework immediately before
or after some event. Callback methods are discussed in more detail in other sections.
EJBContext: Every bean obtains an EJBContext object, which is a reference directly
to the container. The EJBContext interface provides methods for interacting with the
container so that that bean can request information about its environment like the
identity of its client, the status of a transaction, or to obtain remote references to
itself.
JNDI: Java Naming and Directory Interface is a Java extension API for accessing
naming systems like LDAP, NetWare, file systems, etc. Every bean automatically has
access to a special naming system called the Environment Naming Context (ENC).
The ENC is managed by the container and accessed by beans using JNDI. The JNDI
ENC allows a bean to access resources like JDBC connections, other enterprise
beans, and properties specific to that bean.

The EJB specification defines a bean-container contract, which includes the


mechanisms (callbacks, EJBContext, JNDI ENC) described above as well as a strict
set of rules that describe how enterprise beans and their containers will behave at
runtime, how security access is checked, transactions are managed, persistence is
applied, etc. The bean-container contract is designed to make enterprise beans
portable between EJB containers so that enterprise beans can be developed once
then run in any EJB container. Vendors like BEA, IBM, and Gemstone sell application
servers that include EJB containers. Ideally, any enterprise bean that conforms to the
specification should be able to run in any conformant EJB container.
Portability is central to the value that EJB brings to the table. Portability ensures that
a bean developed for one container can be migrated to another if another brand
offers more performance, features, or savings. Portability also means that the bean
developer's skills can be leveraged across several EJB container brands, providing
organizations and developers with better opportunities.

In addition to portability, the simplicity of the EJB programming model makes EJB
valuable. Because the container takes care of managing complex tasks like security,
transactions, persistence, concurrency and resource management the bean
developer is free to focus attention on business rules and a very simple programming
model. A simple programming model means that beans can be developed faster
without requiring a Ph.D. in distributed objects, transactions and other enterprise
systems. EJB brings transaction processing and distributed objects development into
the mainstream.

How do I introspect a bean at run time to discover its type(s) and available
methods?
Location: http://www.jguru.com/faq/view.jsp?EID=10610
Created: Feb 1, 2000 Modified: 2000-02-01 07:11:58.411
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)
Question originally posed by Srilekha Mudumbai
(http://www.jguru.com/guru/viewbio.jsp?EID=5112

Client applications or beans can access meta data about a bean from its
EJBMetaData object. The EJBMetaData object is obtained from the bean's EJB home
reference using the EJBHome.getEJBMetaData( ) method as shown below:

AccountHome acctHome = ... get a reference to the bean's EJB home.

EJBMetaData ejbMetaData = acctHome.getEJBMetaData( );

The EJBMetaData object implements the javax.ejb.EJBMetaData interface which


defines methods for obtaining the class of the bean's remote interface, home
interface, bean type (entity, stateful or stateless session), and the primary keys type
(entity only). A reference to the bean's EJB home can also be obtained. Below is the
interface definition of EJBMetaData.

package javax.ejb;

public interface EJBMetaData {


// Obtain the home interface of the enterprise Bean.
public EJBHome getEJBHome();
//Obtain the home interface of the enterprise Bean.
java.lang.Class getHomeInterfaceClass();
//Obtain the Class object for the enterprise Bean's home interface.
java.lang.Class getPrimaryKeyClass();
//Obtain the Class object for the enterprise Bean's primary key
class.
java.lang.Class getRemoteInterfaceClass();
//Obtain the Class object for the enterprise Bean's remote interface.
boolean isSession();
//Test if the enterprise Bean's type is "session".
boolean isStatelessSession();
}

Once a client application has a reference to bean's remote and home interface
classes, normal Java reflection can be used to introspect the methods avaiable to
client. Below is an example:

Class remoteClass = ejbMetaData.getRemoteInterfaceClass();

java.lang.reflect.Method [] methods = remoteClass.getDeclaredMethods();

for(int i = 0; i methods.length; i++){


System.out.println(methods[i].getName());

There are no mechanisms a client can use to introspect on a the bean class itself.
This makes sense since a bean, as a component, is represented by its remote and
home interfaces. The bean class itself should not be visible to the client.

The EJBMetaData is designed to be used by IDEs and other builder tools that may
need generic methods for obtaining information about a bean at runtime.

What makes a Java class an enterprise bean?


Location: http://www.jguru.com/faq/view.jsp?EID=10622
Created: Feb 1, 2000 Modified: 2000-02-01 07:14:47.937
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)
Question originally posed by sharma MR
(http://www.jguru.com/guru/viewbio.jsp?EID=4939

An enterprise bean is composed of many parts, not just a single class. Essentially, an
enterprise bean is constructed with a bean class, remote interface, home interface
and deployment descriptor. These constituents are discussed below.

A bean class is the implementation class of the bean that defines its business,
persistence, and passivation logic. The bean class implements either the
javax.ejb.EntityBean or javax.ejb.SessionBean interface and runs inside the
EJB container. Instances of the bean class service client request indirectly; instances
of the bean class are not visible to the client.
The remote interface defines the business methods that will be visible to the
client's that use the enterprise bean. The remote interface extends the
javax.ejb.EJBObject interface and is implemented by a remote (distributed object)
reference. Client applications interact with the enterprise bean through its remote
interface.
The home interface defines the create, delete (remove), and query methods for
an enterprise bean type. The home interface extends the javax.ejb.EJBHome
interface and is implemented by a remote (distributed object) reference. The client
application will use the home interface to create beans, find existing beans, and
remove specific beans.
The deployment descriptor is used to describe the enterprise bean's runtime
behavior to the container. Among other things the deployment descriptor allows the
transaction, persistence, and authorization security behavior of a bean to be defined
using declarative attributes. This greatly simplifies the programming model when
developing beans.

An enterprise bean represents the sum of all these parts (remote, home, bean class,
and deployment descriptor) as one component. An enterprise bean is not an
enterprise bean if any one of these parts is missing. A change to anyone of these
parts -- changing even one attribute in the deployment descriptor for example --
creates an entirely new enterprise bean.

Comments and alternative answers

EJB
Author: Anitha Rathanam (http://www.jguru.com/guru/viewbio.jsp?EID=448785), Jul
3, 2001
The implementation of Session bean or the Entity bean interfaces makes the plain
java class an Enerprise bean.

Message Driven Bean does neither have remote nor home interfaces. Even then
how does we say that it is still an EJB?
Author: Navin Sidhaye (http://www.jguru.com/guru/viewbio.jsp?EID=720474), Jan
15, 2002
According to the explaination given above and ejb has to have home, remote and bean
class. In addition to that it also need to have a deployment descriptor which will
dectate the bean's behavior at run time. But the Message Driven Bean does neither
have remote nor home interfaces. Even then how does we say that it is still an EJB?

Re: Message Driven Bean does neither have remote nor home interfaces.
Even then how does we say that it is still an EJB?
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Jan 15, 2002
Navin,
When this FAQ was created, the Message Driven Bean wasn't part of the standard
EJB specifications.
The MDB has, in fact, appeared with EJB 2.0

Re[2]: Message Driven Bean does neither have remote nor home
interfaces. Even then how does we say that it is still an EJB?
Author: Seetesh H (http://www.jguru.com/guru/viewbio.jsp?EID=1038574),
Dec 17, 2002
MDB implements MessageDrivenBean and so it does become a part of your
Enterprise bean and not a simple java class. Seetesh

While deploying CMP entity beans, which fields in the bean are container-
managed and how are they identified?
Location: http://www.jguru.com/faq/view.jsp?EID=11096
Created: Feb 3, 2000 Modified: 2000-08-24 18:55:46.998
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by M J Thatipamala
(http://www.jguru.com/guru/viewbio.jsp?EID=4718

Container-managed fields may be specified in the bean's deployment descriptor. An


entity bean, for example, has an XML deployment descriptor containing elements
similar to the following:<br/>

<enterprise-beans>
<entity>
<description>This entity bean models an audio compact
disc.</description>
<ejb-name>MusicCDBean</ejb-name>
<home>musicstore.MusicCDHome</home>
<remote>musicstore.MusicCD</remote>
<ejb-class>musicstore.MusicCDBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>musicstore.MusicCDPK</prim-key-class>
<reentrant>False</reentrant>

<cmp-field><field-name>upc</field-name></cmp-field>
<cmp-field><field-name>title</field-name></cmp-field>
<cmp-field><field-name>artist</field-name></cmp-field>
<cmp-field><field-name>type</field-name></cmp-field>
<cmp-field><field-name>price</field-name></cmp-field>
</entity>
</enterprise-beans>
In the above deployment descriptor, the container-managed fields are specified to be
upc, title, artist, type, and price.

While the deployment descriptor provides information about the container-managed


fields for use during deployment, the details of how these fields are mapped into the
database (or other persistent storage mechanism) are controlled by the container-
specific deployment process itself. To learn more about the container-specific
deployment process, you will need to consult your container vendor's documentation.

Comments and alternative answers

can you please give info about deploying CMP in weblogic


Author: kathar meera (http://www.jguru.com/guru/viewbio.jsp?EID=1192060), Aug
10, 2004
can you please more eloborate on the deployment descriptor
and could you please provide info about configuring CMP in Weblogic
beans
Author: anil patel (http://www.jguru.com/guru/viewbio.jsp?EID=1235783), Mar 31,
2005
Its also there in Beans.. u can also get it from the beans..

What newsgroups and mailing lists are available to learn more about EJBs?
Location: http://www.jguru.com/faq/view.jsp?EID=11099
Created: Feb 3, 2000 Modified: 2000-02-03 12:47:08.327
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by John Mitchell PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=4

Sun manages two EJB-related mailing list:

The EJB-INTEREST mailing list is for discussion of Enterprise JavaBeans


development. A searchable archive of this list can be found at
http://archives.java.sun.com/archives/ejb-interest.html.

The J2EE-INTEREST mailing list is for discussion of Sun's Java 2 Enterprise Edition
platform and for users of Sun's J2EE Reference Implementation. A searchable archive
of this list can be found at http://archives.java.sun.com/archives/j2ee-interest.html.

You may subscribe or unsubscribe to either of these lists by following the links on the
above archive pages.

When can we hope to see a comprehensive security spec for EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=11178
Created: Feb 3, 2000 Modified: 2000-02-03 14:53:59.52
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)
Question originally posed by Roisin Parkes
(http://www.jguru.com/guru/viewbio.jsp?EID=5237

Currently the EJB security model supports authorization level security. Authorization
security or access control allows control over which users can invoke what methods
on a bean. Access control in EJB is declarative, which simplifies the programming
model.

Its possible that authentication security, which validates the identities of users
accessing the system, will be defined in EJB 2.0. Its likely that the Java
Authentication and Authorization security service will be used, but this is not definite.
If this authentication is added to EJB, it will provide a standard and portable model
for authenticating (login) of users.

Secure communication, which is commonly implemented with technologies like SSL,


may also be defined in EJB 2.0, but this is less likely since it's more of a value added
vendor feature than a requirement for portability.

The release date for EJB 2.0 (as of this writing) has not been determined. It seems
likely that EJB 2.0 will become final sometime in late 2001 or 2002.

Does the EJB programming model support inheritance?


Location: http://www.jguru.com/faq/view.jsp?EID=11504
Created: Feb 4, 2000 Modified: 2000-02-04 14:41:34.909
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)
Question originally posed by James Webster
(http://www.jguru.com/guru/viewbio.jsp?EID=8615

Inheritance is supported in EJB in a limited fashion. Enterprise beans are made up of


several parts including: a remote interface; a home interface, a bean class
(implementation); and a deployment descriptor (see the FAQ What makes a Java
class an enterprise bean? ).

The remote interface, which extends javax.ejb.EJBObject can be a subtype or a


super-type of remote interfaces of other beans. This is also true of the home
interface, which extends javax.ejb.EJBHome. The bean class, which implements
either javax.ejb.EntityBean or javax.ejb.SessionBean can also be a subtype or
super-type of the bean class used by another enterprise bean. Deployment
descriptors are XML files, so there is no Object-Oriented (OO) inheritance in the
deployment descriptor.

Because an enterprise bean is not one object -- its the composition of several parts
-- traditional OO inheritance is not possible. The constituent Java parts (remote,
home, bean class) of an enterprise bean may themselves subtype or serve as super-
type, but the bean as a whole (the sum of its parts) doesn't support inheritance.

Comments and alternative answers

There's a bug in J2EE RI which prevents you from having...


Author: Patrick Wendel (http://www.jguru.com/guru/viewbio.jsp?EID=14423), Feb
15, 2000
There's a bug in J2EE RI which prevents you from having a remote interface B which
derives from A which derives from EJBObject. You could use several interfaces
instead, I suppose, as a workaround.

I know Websphere supports inheritance. Does WebLogic...


Author: jun hong (http://www.jguru.com/guru/viewbio.jsp?EID=121053), Aug 16,
2000
I know Websphere supports inheritance. Does WebLogic 4.5 support inheritance of
EJB?

How do I perform I/O operations from a bean?


Location: http://www.jguru.com/faq/view.jsp?EID=12638
Created: Feb 9, 2000 Modified: 2000-05-29 12:02:04.075
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)

Using java.io is prohibited


Using the java.io package from within a bean is prohibited. The EJB 1.1
Specification, section 18.1.2 (Programming Restrictions) states the following:
An enterprise bean must not use the java.io package to attempt to access files
and directories in the file system.

The file system APIs are not well-suited for business components to access data.
Business components should use a resource manager API, such as JDBC API, to
store data.
The EJB 1.1 specification is available for download from
http://java.sun.com/products/ejb/docs.html

Alternative Solutions
To perform I/O operations you must use a resource connection supported by the EJB
programming model. EJB servers may support several resource connection options,
which can be used to log events as shown below:

• JDBC (javax.sql.DataSource) : Write I/O data in to a relational database.


• URL (java.net.URL) : Write I/O data to a custom server or post them to a
web server.
• JavaMail (javax.mail.Session) : E-mail I/O data to a special account
• JMS (javax.jms.QueueConnectionFactory |
javax.jms.TopicConnectionFactory) : Send the I/O data as messages.

Comments and alternative answers

What about JNDI? JNDI is a J2EE API, one could quite...


Author: James Webster (http://www.jguru.com/guru/viewbio.jsp?EID=8615), Feb 12,
2000
What about JNDI? JNDI is a J2EE API, one could quite easily write a JNDI SPI for
accessing the filesystem (in fact, I think there is such an SPI included in the Sun JNDI
downloads). I think this part of the specification is ill- concieved anyway, and forces
developers to jump through hoops if they want their beans to work with files (what if
I want to encapsulate the generation of an interface file in a session bean? sounds like
a good idea to me!). And what is the spirit of this part of the spec: 1. Developers
should AVOID writing beans that contain direct references to java.io packages
(therefore, using the JNDI example I gave above would be okay?), but really, no one
is going to stop them... OR 2. Container developers should INTERCEPT ANY
requests to java.io classes and throw Security Exceptions if such an access occurrs?
The latter seems a bit harsh to me!

Does the io access just refer to the EJB itself calling...


Author: dee dee (http://www.jguru.com/guru/viewbio.jsp?EID=95806), Aug 15, 2000
Does the io access just refer to the EJB itself calling the file system or can a bean use
a helper class to do the io and pick up the generated file from the system?

The EJB-Interest mailing list has some recent threads...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Nov 27,
2000
The EJB-Interest mailing list has some recent threads that discuss this further: Writing
files with EJBs and File I/O in EJB.

Is this restriction still applicable ?


Author: Kunal Parikh (http://www.jguru.com/guru/viewbio.jsp?EID=1178680), Jun
14, 2004
Just wanted to know if the IO restriction is still applicable. Also, what about using a
Helper class to do fileIO ? TIA, Kunal

How should complex find operations be implemented?


Location: http://www.jguru.com/faq/view.jsp?EID=13332
Created: Feb 11, 2000 Modified: 2000-05-29 12:05:40.71
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)
Question originally posed by Joe McDaniel
(http://www.jguru.com/guru/viewbio.jsp?EID=5292

In bean-managed persistence (BMP) complex find operations are not difficult to


implement, because you have complete control over how a find operation works
through the ejbFind methods in the bean class. ejbFind methods in BMP entities can
span multiple tables and even different data sources to locate the right entity beans.

With container-managed persistence (CMP) its more difficult because you are
dependent on the versatility of the EJB vendor. In other words, if the vendor does not
support sophisticated find operations or syntax, its more difficult to declare complex
find operations at deployment time. With CMP you have a couple options:

• Convert the CMP bean to a BMP bean and hand code the ejbFind
methods yourself. This is a classic scenario for using BMP over CMP; when
the EJB vendor is not sophisticated enough to support a bean's data access
needs.
• Use a session bean to obtain the data you need. When a search
operation becomes to complex to implement in a single bean its a good
indication that the search operation is not appropriate for a find method.
Search operations that span the data encapsulated by several different entity
beans should be placed in a session bean with the emphasis on returning only
the data needed, not necessarily bean references. Data can be returned in
tabular format instead of bean references.

NOTE:
A common design error is to implement search operations that filter results of multi-
entity find requests implemented by other entity beans. This should be avoided. If
you can not find the entity beans in one find request, then you should use a search
method in a session bean.

Should synchronization primitives be used on bean methods?


Location: http://www.jguru.com/faq/view.jsp?EID=14274
Created: Feb 14, 2000 Modified: 2000-02-15 06:31:50.898
Author: Greg Boettcher (http://www.jguru.com/guru/viewbio.jsp?EID=14271)
Question originally posed by suresh ramamoorthi
(http://www.jguru.com/guru/viewbio.jsp?EID=13144

No. The EJB specification specifically states that the enterprise bean is not allowed to
use thread primitives. The container is responsible for managing concurrent access
to beans at runtime.
Can I use Threads in a enterprise bean?
Location: http://www.jguru.com/faq/view.jsp?EID=14648
Created: Feb 15, 2000 Modified: 2000-05-22 12:57:17.2
Author: Aravind Naidu (http://www.jguru.com/guru/viewbio.jsp?EID=12326)
Question originally posed by sanath sarma
(http://www.jguru.com/guru/viewbio.jsp?EID=13815

No. The thread management is done by the container for you. As a bean developer
you are not allowed to use threads.

Section 18.1.2 of the EJB 1.1 specification states:

• The enterprise bean must not attempt to manage threads. The enterprise
bean must not attempt to start, stop, suspend, or resume a thread; or to
change a thread’s priority or name. The enter-prise bean must not attempt to
manage thread groups.

These functions are reserved for the EJB Container. Allowing the enterprise bean to
manage threads would decrease the Container’s ability to properly manage the
runtime environment.

Related FAQs:

• http://www.jguru.com/jguru/faq/view.jsp?EID=15893

Comments and alternative answers

usage of threads inside beans.


Author: rajeev hans (http://www.jguru.com/guru/viewbio.jsp?EID=1056849), Feb 14,
2003
I agree with the fact that we should not try to alter anything with the current threads.
But is it possible to start a new thread from a bean ?

Re: usage of threads inside beans.


Author: anand andrew (http://www.jguru.com/guru/viewbio.jsp?EID=813206),
Apr 17, 2003
your question>"But is it possible to start a new thread from a bean ?" Yes.But it is
not recommended by EJB specs/containers. Anand Andrew

Why are beans not allowed to create their own threads?


Location: http://www.jguru.com/faq/view.jsp?EID=15893
Created: Feb 19, 2000 Modified: 2000-02-20 15:30:42.767
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)
Question originally posed by dan benanav
(http://www.jguru.com/guru/viewbio.jsp?EID=8173

Enterprise beans exist inside a container at run time. The container is responsible for
managing every aspect of the enterprise bean's life including: transactions, access
control, persistence, resource pooling, etc. In order for the container to manage the
runtime environment of a bean, it must have complete control over the threads that
access and run within a bean. This means that beans can not start or manage their
own threads. Containers deny enterprise beans the privilege to manage threads for
three basic reasons: Resource management, security, and thread-sensitive storage.

Resource Management
Containers manage every aspect of the runtime environment used by enterprise
beans including transactions, access control, life cycle, resource connections, VM
security, class loading, and threads. This allows the container to conserve as many
resources as possible, which is important when there are hundreds of enterprise
beans servicing thousands of clients. Without strict management of resources like
memory and threads, EJB systems might consume to many resources (memory and
cycles), which would result in a slow system, a prospect that is untenable in a high-
transaction environment. Threads started and managed by enterprise beans would
not be managed by the container, which would make it difficult to conserve
resources.

Security
There is no way for a container system to know in advance that a bean's use of
threads is benign. While intentions may be sincere it is possible -- probably inevitable
-- that developers would create malignant beans that spawn so many threads that
the entire system slows down. One bean instance's misuse of threads or the
commutative effect of many instances could cause a system slowdown. This is an
insurgent denial of service, where the beans themselves sabotage a system's ability
to respond to client requests. Security is a very good reason for denying bean's the
privilege of starting and managing their own threads.

Thread-Specific Storage
Thread-Specific Storage (TSS) is an established and common technique employed by
vendors to propagate and track client requests through the container system. It
involves associating data with a thread. The data may be information about the
client's identity, the transaction context, and other information, which can be
accessed by any part of the container without having to pass the data explicitly. This
is especially useful when enterprise beans invoke other enterprise beans or access
resources, because it provides a convenient and transparent mechanism for
transferring information about the who is making the request and under what
circumstances. Each vendor will use the TSS technique differently according to the
mechanics of their server. Threads started and managed by the enterprise bean
explicitly would not have the proper TSS -- that would require intimate knowledge
and access to the vendors container system. Without the right TSS the enterprise
bean's threads can not operate within the container system properly. This is another
reason why bean are not allowed to start and manage their own threads, it would
short-circuit the vendor's use of TSS.

Related FAQs:

• Can I use Threads in an enterprise bean?


• What is a container?

Comments and alternative answers


The following is a quote from Mark Hapner, Sun's l...
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16),
Feb 28, 2000
The following is a quote from Mark Hapner, Sun's lead enteprise Java architect.

"Although conflict with the container is one of the reasons why EJBs are not allowed
to create threads, there is a more important reason.

A major objective of EJB is to achieve the creation of a multi-user service by


implementing single threaded components. Writing robust, multi-threaded code is
hard and eliminating the [requirement] that this skill to be mastered in order to
implement a middle-tier service is one of the main benefits of EJB.

The goal is to delegate all responsibility for managing concurrency to a container and
its resources (DBMSs, etc). EJB 1.1 succeeds in doing this for many types of
applications. EJB 2.0 will significantly expand the EJB app domain by adding support
for asynchronous invocation (JMS integration).

So, the question is not what you can do within your container it is what your container
can do for you :>). Why should you be worrying about creating threads if you can get
the container to handle all of that complexity?"

-- Mark Hapner, EJB-INTEREST mailing list post "Re: Threads question (Concrete
examples?)"

I had a requirement of asynchronous method invocat...


Author: Sathish Srinivasan (http://www.jguru.com/guru/viewbio.jsp?EID=46492),
May 9, 2000
I had a requirement of asynchronous method invocation. What should I do with
EJB1.1 Container( apart from waiting for my particular EJB2.0 complaint app
server )?

I knew I could create a queue and write another bean/ process to do the job.But for
my scenario, I thought, it is too much overhead.

I went ahead with Threads. Any thoughts on how I should have proceeded.?

How does EJB support polymorphism?


Location: http://www.jguru.com/faq/view.jsp?EID=18807
Created: Feb 28, 2000 Modified: 2000-05-29 12:14:12.899
Author: Daniel Chong (http://www.jguru.com/guru/viewbio.jsp?EID=18540)
Question originally posed by sachin mahishi
(http://www.jguru.com/guru/viewbio.jsp?EID=4437
Because an EJB consists of multiple "parts", inheritance is achievable in a rather
limited fashion (see FAQ answer on inheritance here). There have been noteworthy
suggestions on using multiple inheritance of the remote interface to achieve
polymorphism, but the problem of how to share method signatures across whole
EJBs remains to be addressed. The following is one solution to achieving
polymorphism with Session Beans. It has been tried and tested on WebLogic Apps
Server 4.50 with no problems so far.

We will use an example to show how it's done. Say, there are 2 session beans, Tiger
and Lion, that share some method signatures but provide different implementations
of the methods.

• AnimalHome and Animal are the home and remote interfaces. The signatures
of the polymorphic methods are in Animal.
• AnimalBean is the base implementation bean.
• TigerBean and LionBean extend from AnimalBean. They may override the
methods of AnimalBean, implementing different behaviors.
• Deploy Tiger and Lion beans, specifying AnimalHome and Animal as their
home and remote interfaces. Note that Tiger and Lion should have different
JNDI lookup names.

Comments and alternative answers

Any other polymorphism options?


Author: Dan Broadway (http://www.jguru.com/guru/viewbio.jsp?EID=424378), May
18, 2001
Can anyone point to any other discussions of implementing polymorphism with EJB?
Our current design is polymorphism heavy and we are searching for options.

Thanks in advance

What classes does a client application need to access EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=20865
Created: Mar 6, 2000 Modified: 2000-08-11 12:13:21.15
Author: Sameer Tyagi (http://www.jguru.com/guru/viewbio.jsp?EID=4381) Question
originally posed by Sukumar Subbiah
(http://www.jguru.com/guru/viewbio.jsp?EID=1871

It is worthwhile to note that the client never directly interacts with the bean object
but interacts with distributed object stubs or proxies that provide a network
connection to the EJB container system.

The mechanhism is as follows.

1. The client uses the JNDI context to get a remote reference (stub) to the home
object ( the EJBHome).
2. It uses the home to get a remote reference (stub) to the EJBs remote object
(the EJBObject)
3. It then invokes business methods on this remote object.
The client needs the remote interface, the home interface, the primary key( if it is an
entity bean).

In addition to these, the client would need the JNDI factory implementation, and the
remote and home stubs. In some EJB servers the Factory and/or stubs can be
dynamically loaded at run time. In other EJB servers they must be in the classpath of
the client application.

See also:

• Which, if any, of the automatically generated stub & skeleton class files does
one need to include in a JAR file to be used when creating stand-alone clients?

Comments and alternative answers

In which packages are these classes.


Author: Florian Binder (http://www.jguru.com/guru/viewbio.jsp?EID=446574), Dec
4, 2001
In which packages are the classes, which I need to connect to an ejb.

Which servers, and how?


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 10, 2001
"In some EJB servers the Factory and/or stubs can be dynamically loaded at run time.
" -- which servers? and how are the classes actually loaded? via a URLClassLoader or
what?

What is an EJB primary key? How is it implemented when the database


doesn't have a primary key?
Location: http://www.jguru.com/faq/view.jsp?EID=20875
Created: Mar 6, 2000 Modified: 2000-08-15 06:31:37.383
Author: Sameer Tyagi (http://www.jguru.com/guru/viewbio.jsp?EID=4381) Question
originally posed by Igor Mandrosov
(http://www.jguru.com/guru/viewbio.jsp?EID=12762

A primary key is an object that uniquely identifies the entity bean. According to the
specification, the primary key must be unique for each entity bean within a container.
Hence the bean's primary key usually maps to the PK in the database (provided its
persisted to a database).

You may need to create a primary key in the database for the sake of referential
integrity. This does not, however, mean you NEED a primary key in the database. As
long as the bean's primary key (which maps to a column or set of columns) can
uniquely identify the bean it should work.

[with minor correction from Amit Chawla.]

See also:

• Can a primary key have more than one field?


• How do I automatically generate primary keys?
• Can the primary key in the entity bean be a Java primitive type such as int?

Comments and alternative answers

What if the value of a compound primary key change...


Author: Sesh Jalagam (http://www.jguru.com/guru/viewbio.jsp?EID=41326), Apr 27,
2000
What if the value of a compound primary key changes?

What I mean here is, let's say that a table has columns Name and Balance and we
made a primary key by combining both of these columns. What happens if I have a
set method that changes the Balance column. Am I not changing the EB (since an EB
is identified by its primary key). Does this mean I am creating a new instance of the
EB? Thank you Sesh

No, you are not creating a new instance of the EB ...


Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), May
11, 2000
No, you are not creating a new instance of the EB (entity bean). If you have a set
method that changes the Balance column, what it means is that your bean has (for
example) a setBalance(float balance) method. When this method is called, the new
value is stored in the balance field of the entity bean and the container then persists
this value with the column and row this bean represents in the database and will then
update the new value in the database. There will not be a new instance of the entity
bean created.

What's an .ear file?


Location: http://www.jguru.com/faq/view.jsp?EID=21087
Created: Mar 6, 2000 Modified: 2000-08-04 13:26:17.953
Author: Mobushir Hingorjo (http://www.jguru.com/guru/viewbio.jsp?EID=11910)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

An .ear file is an "Enterprise Archive" file. The file has the same format as a regular
.jar file (which is the same as ZIP, incidentally). The .ear file contains everything
necessary to deploy an enterprise application on an application server. It contains
both the .war (Web Archive) file containing the web component of the application as
well as the .jar file. In addition there are some deployment descriptor files in XML.
http://java.sun.com/j2ee/j2sdkee/techdocs/guides/ejb/html/Overview.fm.html
contains additional information.
Comments and alternative answers

Should the .ear be enough to deploy an enterprise bean...


Author: Benoit Xhenseval (http://www.jguru.com/guru/viewbio.jsp?EID=3363), Apr
18, 2000
Should the .ear be enough to deploy an enterprise bean in any EJB Server?
Re: Should the .ear be enough to deploy an enterprise bean...
Author: MURALIDHAR KALAVACHARLA
(http://www.jguru.com/guru/viewbio.jsp?EID=735059), Jan 25, 2002
Frankly speaking I did not use this packaging method as yet. But there seem to be
some issues that I came across to know while reading about java packaging. Here
is an excerpt from one of those I want to share with the community...

" Currently, the J2EE 1.3 specification defines an enterprise application packaging
unit to be a JAR file with an .ear extension. EAR files can contain one or more:

- EJB modules (.jar extension)

- Web application modules(.war extension)

- JCA resource adapter modules (.rar extension)

- Application client modules (.jar extension)

Since most web-based J2EE applications are composed of web and EJB
applications, the EAR file meets the basic requirements for packaging an
application. However, it is lacking in capability for packaging complicated J2EE
applications. For example, the following components are often used in a J2EE
application, but cannot be declared in an EAR file:

- Some JMS consumers that run within an application server, such as a


MessageConsumer that runs as part of a ServerSession

- JDBC DataSource objects

- JMS ConnectionFactory and Destination objects

- JMX MBeans

- Startup and shutdown classes (admittedly, a propriety extension provided by


vendors, but generally unilaterally supplied by all vendors)

Currently, all of these components of an application have to be manually


configured and deployed through a vendor's administration interface. As the usage
of the items listed above increases over time, it will become more important for
EAR files to natively support packaging of these components to achieve true J2EE
application portability."

Benoit: Not all EJB servers support deployment of ...


Author: Taylor Goetz (http://www.jguru.com/guru/viewbio.jsp?EID=123153), Aug
11, 2000
Benoit:
Not all EJB servers support deployment of applications packaged as .ear files. And, as
far as I can tell, this functionality is not a requirement for EJB 1.1 certification.

WebLogic is one server that does not support deployment of .ear files.

Orion is another EJB container that does support .ear files. I have found Orion to be
very true to the specification, and very similar to the reference implementation.

Re: Benoit: Not all EJB servers support deployment of ...


Author: Billie Goodson (http://www.jguru.com/guru/viewbio.jsp?EID=1237349),
Apr 8, 2005
The link for WebLogic should be http://www.bea.com not beai.com

Can beans use stored procedures in a database?


Location: http://www.jguru.com/faq/view.jsp?EID=22905
Created: Mar 10, 2000 Modified: 2000-03-10 12:53:56.824
Author: Richard Monson-Haefel (http://www.jguru.com/guru/viewbio.jsp?EID=16)
Question originally posed by Anil Datt
(http://www.jguru.com/guru/viewbio.jsp?EID=20887

Stored procedures can be used by session beans that access the database using
JDBC and bean-managed entity beans that use JDBC to manage their own
persistence. JDBC provides a call interface for using stored procedures. An example
is provided below:
InitialContext cntx = new InitialContext( );
DataSource dataSource = (DataSource)
cntx.lookup("java:comp/env/jdbc/mydatabase");
Connection con = dataSource.getConnection( );

CallableStatement storedProcedure = con.prepareCall("{? = call someprocedure


[(?,?)]}");

Comments and alternative answers

Some advanced CMP Object/Relational mapping tools also...


Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362), Apr
12, 2000
Some advanced CMP Object/Relational mapping tools also allow the use of stored
procedures in the persisting of Entity Beans. Hopefully a standard approach will be
forthcoming in the upcoming EJB 2.0 specification

Re: Some advanced CMP Object/Relational mapping tools also...


Author: V Shah (http://www.jguru.com/guru/viewbio.jsp?EID=226807), Oct 23,
2001
Hi, Do you know this can be achieved using webgain ? I need to call a stored
procedure for every insert/update/delete and I'm using CMP bean. Any idea, how
would I go about doing this ?
Implment JTA?
Author: Neo Gigs (http://www.jguru.com/guru/viewbio.jsp?EID=748386), May 9,
2002
Hi there,

Can JTA being implemented if I have a series of stored procedure calls?

How? (source code)

Tq

Neo

Is method overloading allowed in EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=28118
Created: Mar 24, 2000 Modified: 2000-04-03 00:08:44.325
Author: sachin mahishi (http://www.jguru.com/guru/viewbio.jsp?EID=4437)
Question originally posed by Daniel Weimer
(http://www.jguru.com/guru/viewbio.jsp?EID=25540

Yes you can overload methods.

How can JMS be used from EJB 1.1?


Location: http://www.jguru.com/faq/view.jsp?EID=28553
Created: Mar 25, 2000 Modified: 2000-03-29 06:21:56.666
Author: Jason Vanguard (http://www.jguru.com/guru/viewbio.jsp?EID=27748)
Question originally posed by Jon Finanger
(http://www.jguru.com/guru/viewbio.jsp?EID=1625

The same as any client would use JMS. At this point there is no integration, but it is
planned for a future release of the EJB spec.
Comments and alternative answers

Could you please expand: Can a bean be a JMS subscriber...


Author: Benoit Xhenseval (http://www.jguru.com/guru/viewbio.jsp?EID=3363), Apr
18, 2000
Could you please expand: Can a bean be a JMS subscriber and "sit" there in memory
waiting for a JMS event? How could we guarantee that this bean stays active in
memory?

EJB 1.1 specification doesn't allow an enterprise bean...


Author: Alessandro Alinone (http://www.jguru.com/guru/viewbio.jsp?EID=14810),
Apr 27, 2000
EJB 1.1 specification doesn't allow an enterprise bean to receive messages
asynchronously. You can only pull messages through the receive() method. The
asynchronous delivery will be made possible by EJB 2.0 specification. Here is a quote
from JMS 1.0.2 specification (sec. 1.4.3 on page 18): "The current EJB specification
defines beans that are invoked synchronously via method calls from EJB clients. A
future release of EJB will add a form of asynchronous bean that is invoked when a
JMS client sends it a message."

Can primary keys contain more than one field?


Location: http://www.jguru.com/faq/view.jsp?EID=30244
Created: Mar 30, 2000 Modified: 2000-08-15 06:29:45.532
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by Harish Somisetty
(http://www.jguru.com/guru/viewbio.jsp?EID=27358

Yes, a primary key can have as many fields as the developer feels is necessary, just
make sure that each field you specify as the primary key, you also specify a
matching field in the bean class. A primary key is simply one or more attributes
which uniquely identify a specific element in a database. Also, remember to account
for all fields in the equals() and hashCode() methods.
Comments and alternative answers

There's a bug in the current version of the J2EE r...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 6, 2000
There's a bug in the current version of the J2EE reference EJB server (the one you run
by typing "j2ee" from the command line) -- it won't deploy a bean with a complex
primary key unless that key is actually a CMP property (public instance variable) of
the Bean.

Is there a J2EE server for RedHat Linux 6.1?


Location: http://www.jguru.com/faq/view.jsp?EID=32032
Created: Apr 4, 2000 Modified: 2000-04-04 10:35:49.086
Author: sachin mahishi (http://www.jguru.com/guru/viewbio.jsp?EID=4437)
Question originally posed by Sanjay Mistry
(http://www.jguru.com/guru/viewbio.jsp?EID=17764

There are couple of EJB servers Check this website


http://www.flashline.com/Components/appservermatrix.jsp?sid=954859879375-
3501378072-150
Comments and alternative answers

The Inprise application server also runs on RedHat...


Author: Thomas Kirsch (http://www.jguru.com/guru/viewbio.jsp?EID=47333), May
10, 2000
The Inprise application server also runs on RedHat Linux 6.1

How does Container Managed Persistence work with automatically


generated database ID fields? Should I map the ID field explicitly or leave it
unspecified?
Location: http://www.jguru.com/faq/view.jsp?EID=33146
Created: Apr 6, 2000 Modified: 2000-04-10 11:21:41.876
Author: sachin mahishi (http://www.jguru.com/guru/viewbio.jsp?EID=4437)
Question originally posed by sachin mahishi
(http://www.jguru.com/guru/viewbio.jsp?EID=4437

In the Deployment Descriptor, map the normal fields appropriately, but don't specify
the auto-id field as one of the container managed fields.
Comments and alternative answers

But you still have to specify the primary key field...


Author: Andrei Iarnykh (http://www.jguru.com/guru/viewbio.jsp?EID=224922), Mar
1, 2001
But you still have to specify the primary key field in the entity bean, don't you? So
how to work it around?

How can one have non-client specific state in stateless session beans?
Location: http://www.jguru.com/faq/view.jsp?EID=33182
Created: Apr 6, 2000 Modified: 2000-04-10 10:36:43.271
Author: sachin mahishi (http://www.jguru.com/guru/viewbio.jsp?EID=4437)
Question originally posed by Alex Stouffs
(http://www.jguru.com/guru/viewbio.jsp?EID=23864

You can use the Environment to get a pointer to a somewhat global state, that's
shared among all EJBs:
public class test implements SessionBean
{
private transient SessionContext ctx;
static final float PIE=3.14 ;
private transient Properties myprops;

//all the SessionBean methods


public void setSessionContext(SessionContext ctx) {
this.ctx = ctx;
myprops = ctx.getEnvironment();
}

Let's assume I use a JavaBean as a go-between a JSP and an EJB, and have,
say, 50 concurrent clients that need to access the EJB functionality. Will the
JSP container actually instantiate 50 instances of the bean, or can it reuse a
single instance to access the EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=35052
Created: Apr 11, 2000 Modified: 2000-08-14 11:26:53.146
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14) Question
originally posed by Garth Dyck
(http://www.jguru.com/guru/viewbio.jsp?EID=34850

It depends on the scope you associate with the JavaBean. If you assign the bean
with page (which is the default) scope or request scope, a new bean will be
instantiated for each incoming request.
If you assign the bean with session scope, you will still have 50 instances loaded in
memory (assuming each incoming request is triggered by a distinct client), although
some may have been instantiated from an earlier request from the same client.
However, you may not want to use the session scope for a high-volume site as these
beans will continue to reside in memory, long after the request has been serviced,
consuming valuable resources until they are invalidated either explicitly or due to a
session timeout.

You can also assign the bean with application scope, in which case it is instantiated
just once before being placed into the servlet context of the container. It can then be
accessed at a later time, as long as the server is up and running. Although this may
sound like an attractive proposition, do note that you will have to contend with
significant multithreading issues. For instance, you'll have to ensure that the bean is
accessed in a thread-safe manner from each of the JSP files. While you can do this
using explicit synchronization from within the JSP file, do note that your application
may take a significant performance hit because of this - especially if you expect tens
or hundreds of concurrent clients accessing your pages.

So, in short, your best bet may be to assign the bean with request scope.

Comments and alternative answers

Is it viable to have JSP in one Server,servlet in ...


Author: Rangarajan Mangudi Parthasarathy
(http://www.jguru.com/guru/viewbio.jsp?EID=347775), Mar 16, 2001
Is it viable to have JSP in one Server,servlet in another,and EJB in other. If possible
send some example code. JSP pages invokes the business methods,to the
servlet,which in turn forwards it to the EJB.

Re: Is it viable to have JSP in one Server,servlet in ...


Author: ravi vedala (http://www.jguru.com/guru/viewbio.jsp?EID=1177955), Jun
11, 2004
I dont see any problem with that, as long as you are not expecting all these to be
part of a cluster.

What happens when two users access an Entity Bean concurrently?


Location: http://www.jguru.com/faq/view.jsp?EID=35269
Created: Apr 12, 2000 Modified: 2000-08-03 22:23:01.884
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by seema guptha
(http://www.jguru.com/guru/viewbio.jsp?EID=32228

Taken from Enterprise JavaBeans by Richard Monson-Haefel, "EJB, by default,


prohibits concurrent access to bean instances. In other words, several clients can be
connected to one EJB object, but only one client thread can access the bean instance
at a time. If, for example, one of the clients invokes a method on the EJB object, no
other client can access that bean instance until the method invocation is complete."

So, to answer your question, two users will never access an Entity Bean concurrently.
If you wish to know more about this issue, I would suggest downloading and reading
the white paper from Sun: http://java.sun.com/products/ejb/docs.html . Some entity
beans may require loopback calls, where bean A is invoked, in turn invoking bean B,
which then invokes a method call on bean A. This kind of concurrency is tricky and is
best avoided.

As a side note, the use of 'synchronized' is not permitted in EJB. (You must leave all
that up to the server.)

Comments and alternative answers

I disagree with the statement "two users will...


Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362), Apr
17, 2000
I disagree with the statement "two users will never access an Entity Bean
concurrently."

Referring to the section 9.1.11 of the EJB 1.1 specification - "Concurrent access from
mulitple transactions" states that the container can allow for concurrent access to an
Entity Bean. This functionality is extremely vital for high transactional systems.
Having serialized access to an Entity Bean can cause deadlocks and hanging clients.

A high end EJB container, such as the Inprise Application Server supports this
enterprise level functionality. In this case, the transactional synchronization is left up
to the database and JDBC connection specified by the transaction isolation.

This can provide many benefits, consider Client A that accesses a Customer Entity
Bean - CBean. Client A is in a transaction but doesnt change CBean, Client B can
access and change CBean and does not have to wait for Client A to finish reading.

You may now ask "well then Client B is seeing an out of date CBean", This is exactly
how transaction isolation on a database works and is dependent on the transaction
isolation specified on the JDBC connection.

I believe that this depends on whether you look at...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Apr 24, 2000
I believe that this depends on whether you look at transactional concurrency, or at
threadwise concurrency. The spec allows transactional concurrency (as Mr. Castaneda
points out) but not threadwise concurrency. The key in Monson-Haefel's quote is
'...until the method invocation is complete' This indicates to me that he (and the
original poster) were discussing concurency from a threading point of view, not from
the transactional point of view that Mr Castaneda brings up.

In Entity bean deployment descriptor, we can define...


Author: Archana Karnik (http://www.jguru.com/guru/viewbio.jsp?EID=68139), Jul
13, 2000
In Entity bean deployment descriptor, we can define whether the bean is-reentrant or
non-reentrant. 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 .

Re: In Entity bean deployment descriptor, we can define...


Author: Kalpeshkumar Soni
(http://www.jguru.com/guru/viewbio.jsp?EID=916018), Jul 2, 2002
can somebody throw more light on this reentrant thing ? how to specify isolation
levels for session/entity beans in weblogic and any other ap server. what about
oracle9iAS

Re: In Entity bean deployment descriptor, we can define...


Author: Seetesh H (http://www.jguru.com/guru/viewbio.jsp?EID=1038574), Dec
17, 2002
Have u tried this Archana? If yes which app server r u using?
Seetesh

What's the reason for having two interfaces -- EJBHome for creating, finding
& removing and EJBObject for implementing business methods. Why not
have an single interface which supports both areas of functionality?
Location: http://www.jguru.com/faq/view.jsp?EID=35558
Created: Apr 12, 2000 Modified: 2000-04-14 08:44:05.104
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by rajesh kkkkkkkkk
(http://www.jguru.com/guru/viewbio.jsp?EID=16780

This design reflects the common "Factory" Design pattern. The EJBHome interface is
the Factory that creates EJBObjects. EJBObject instances are the product of the
factory. The reason for having two interfaces is because they are both responsible for
different tasks. The EJBHome is responsible for creating and finding EJBObjects,
whilst the EJBObject is responsible for the functionality of the EJB.
Comments and alternative answers

Suppose Both the methods of Home, Remote are in single...


Author: Uma Sankar ramaraju (http://www.jguru.com/guru/viewbio.jsp?EID=36320),
Apr 14, 2000
Suppose Both the methods of Home, Remote are in single interface EJBxyz. and the
ejbinterface for our ejb is like this
interface MyEJBInterface extends EJBxyz
{
// create or initalization methods
create(args1);
create(args1);
// biz methods
operation1(...);
operation2(....);
}
the ejbean is implemented in MyEJB.java. A client can access MyEJB in the below
manner.
InitialContext ctx = new IntialContext();
Object objRef= ctx.lookup("myejbjndiname");
MyEJBInterface myIface = (MyEJBInterface )
PortableRemoteObject.narrow(objRef, objRef.class);

myIface.operation1(...);
Like in the code above client can call the biz methods with out really creating the
Object. This will certainly increase programming bugs.

For the above to work properly, ejbhome implementor should have a default ejb in it
to redirect the call to( current implementation allows to crete the ejb on demand) .
Initializing the default ejb poses many problems. It can be intialized with a standard
set of arguments (removes the current flexibility of overloaded create methods). Some
entity beans can have only finder methods with out creation methods, what to do in
those cases ( ???)

Having single interface for both the purposes promotes programatical errors, and
removes current ambiguities.

By careful look of the problems encountered above we get the answer that interface
and it's creation are two different abstractions. By using creation abstraction just to
create & find and the interface to do biz methods we get cleaner code, and flexibility
to create, find ejb's with multiple types of arguments. for a good pattern for this
design see Robert's answer above

Can a bean act as a singleton to provide logging and other services?


Location: http://www.jguru.com/faq/view.jsp?EID=35559
Created: Apr 12, 2000 Modified: 2000-04-14 08:48:47.801
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Diederik de Groot
(http://www.jguru.com/guru/viewbio.jsp?EID=11611

No, You cannot implement a Singleton in EJB. A way to do this could be to implement
an RMI or CORBA object.
Comments and alternative answers

EntityBean as Singleton?
Author: Ravi Shankar (http://www.jguru.com/guru/viewbio.jsp?EID=560697), Nov
26, 2001
Wouldn't the following scheme work like a singleton? Define a read-only BMP
EntityBean with <prim-key-class> as String. In the ejbFindByPrimaryKey() method,
always return a hard-coded string (irrespective of the primary key value passed in).
Wouldn't all clients then get a reference to the same EJB instance? Regards Ravi
Does it work? Did you try?
Author: Chris Duerr (http://www.jguru.com/guru/viewbio.jsp?EID=1234080),
Mar 22, 2005
The ejb specification states: at any time, there is only one client thread per bean
instance active. Therefore I expect that there might more than one instance of an
entity bean, even if there is only one data set to represent.

Setting the entitiy bean read-only means that there is no call to the (unneseccary)
ejbStore(). A read-only bean still may be represented by more than one instance.

But this is blank theory, so does it in practice work? Did you try?

Use a stateless session bean with an instance pool size of 1.


Author: Dominic Cioccarelli (http://www.jguru.com/guru/viewbio.jsp?EID=759666),
Feb 14, 2002
You can (in many application servers) determine the instance pool size for each bean.
By implementing a stateless session bean with an instance size of 1, you effectively
have a singleton. The downside is that setting the pool size is vendor specific.

Re: Use a stateless session bean with an instance pool size of 1.


Author: David Li (http://www.jguru.com/guru/viewbio.jsp?EID=767271), Feb 21,
2002
My impression is that a stateless session bean instance is not free threaded and
does not allow a re-entry while another client is using it. The other way to view it
is that if a single instance of a stateless session bean were a singleton and were
able to serve multiple client simultanouly, why would you ever need to put more
than one bean instances in a pool? Hope somebody can confirm my impression or
tell me why I am wrong. Thanks David

Re[2]: Use a stateless session bean with an instance pool size of 1.


Author: Kirill Fakhroutdinov
(http://www.jguru.com/guru/viewbio.jsp?EID=501201), May 7, 2002
You are right that this singleton EJB can not be multithreaded - as any other
EJB. Only one client at a time would be able to access it. And because other
EJBs can not wait because of the absence of synchronization mechanisms -
they probably will be just failing (unless application server/container will be
able to put them "on hold" - that I doubt).

P.S. Read-only singleton could be free-threaded, but read-write singleton


usually has to be synchronized.

Use Of Singleton Pattern in EJB.


Author: santosh Terkhedkar (http://www.jguru.com/guru/viewbio.jsp?EID=996598),
Sep 9, 2002
I think use of singleton pattern is possible in EJb, we can use JNDI to store arbitrary
objects and lookup these objects through jndi,but use of singleton pattern in ejb is not
useful. other way to achive this could be to write a java class and call this bean from
within java class and make only one instance of this class.

Re: Use Of Singleton Pattern in EJB.


Author: Ankush Purwar (http://www.jguru.com/guru/viewbio.jsp?EID=1221499),
Jun 20, 2005
Using your approach write a java class and call this bean from within java class
and make only one instance of this class doesn't work in clustering.

Which fields in beans should be public?


Location: http://www.jguru.com/faq/view.jsp?EID=35561
Created: Apr 12, 2000 Modified: 2000-04-17 07:55:28.417
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by sanath sarma
(http://www.jguru.com/guru/viewbio.jsp?EID=13815

All Container Managed Fields in an Entity Bean must be public.

Ejb 1.1 spec section 9.4.1 - "The fields must be defined in the entity bean class as
public, and must not be defined as transient."

How do you implement callbacks in EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=35566
Created: Apr 12, 2000 Modified: 2000-04-17 08:01:09.382
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by telmo sa
(http://www.jguru.com/guru/viewbio.jsp?EID=5055

If your client is an EJB, it can pass a reference to itself to the method of the bean
that it is calling. The EJB can then call methods directly on that interface.

If your client is a Java client, your client requires some sort of object that will "listen"
for call-backs. This could be either a CORBA or RMI object. Again, you could pass
references to these objects to the EJB, which could then invoke methods on the
references.

Comments and alternative answers

Case 1: Client is an EJB. If client EJB is running...


Author: Thomas Kirsch (http://www.jguru.com/guru/viewbio.jsp?EID=47333), May
10, 2000
Case 1: Client is an EJB. If client EJB is running in a JVM different from the one of
the server EJB and you pass a reference of the client EJB to the server EJB for a
"direct" call back, how can the server EJB find the client EJB? In a "direct" callback
there is no look-up in a Java naming service involved.

Case 2: The client contains an RMI object that listens for callbacks. Do you have to
register this client RMI object with an RMI registry running on the client machine for
the EJB to find the object?

Don't worry: RMI takes care of all that automagically....


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 17,
2000
Don't worry: RMI takes care of all that automagically. The RMI skeleton, in
processing the request, saves all the information about the caller. A nameserver is only
required if you only know the name of the remote object; since you've been invoked
by it, then by definition you already know who and where it is.

Wrong answers !!
Author: Raees Uzhunnan (http://www.jguru.com/guru/viewbio.jsp?EID=281081), Feb
14, 2002
An enterprise bean should not pass its reference to any callback methods. It should
first obtain a remote refernce to itself using contect object and then pass this to the
callback method. This is for container to have a track of who all accessing the
specified enterprise bean - based on spec 1.1

When should I use bean-managed transactions instead of specifying


transaction information in the deployment descriptor?
Location: http://www.jguru.com/faq/view.jsp?EID=36327
Created: Apr 14, 2000 Modified: 2000-08-03 22:11:55.978
Author: Uma Sankar ramaraju (http://www.jguru.com/guru/viewbio.jsp?EID=36320)
Question originally posed by hari narayandas
(http://www.jguru.com/guru/viewbio.jsp?EID=32993

Hi Hari,

The Sun J2EE EJB Guide says like this:

Although beans with container-managed transactions require less coding, they have
one limitation: When a method is executing, it can be associated with either a single
transaction or no transaction at all. If this limitation will make coding your session
bean difficult, you should consider using bean-managed transactions.

The following pseudo-code illustrates the kind of fine-grained control you can obtain
with bean-managed transactions. By checking various conditions, the pseudo-code
decides whether to start and stop different transactions within the business method.

begin transaction
...
update table-a
...
if (condition-x)
commit transaction
else if (condition-y)
update table-b
commit transaction
else
rollback transaction
begin transaction
update table-c
commit transaction
...

I think what it means is there are some limitations in j2ee transaction support. In a
container managed situation, nested or multiple transactions are not allowed within a
method. if a biz method needs those features you need to go for bean managed
transactions.

Comments and alternative answers

Actually, BMT isn't about nested transactions. It just...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 17, 2000
Actually, BMT isn't about nested transactions. It just allows you finer control than the
various transaction options provided by the container. If you tell it to in the DD, the
container will suspend an existing transaction, create a new one, join on the an
existing one, and so forth, automatically doing the right thing before and after your
method. Bean-managed transactions just allow you to do the same sort of stuff, only
with more control over the conditions under which that would happen. That is, you
can do transaction stuff *inside* a method, rather than letting the method be the level
of granularity.

It turns out that nested transactions are not currently supported by Java TP
implementations. Or has that changed?

How do I automatically generate primary keys?


Location: http://www.jguru.com/faq/view.jsp?EID=37217
Created: Apr 17, 2000 Modified: 2000-08-15 06:30:23.774
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by sat d
(http://www.jguru.com/guru/viewbio.jsp?EID=14705

A common way to do it is to use a stateless session bean to retrieve the ID that you
wish to use as the primary key. This stateless session bean can then execute an
Oracle sequencer or procedure etc. to retrieve the ID value used as the primary key.
Comments and alternative answers

Such mechanism is not possible with MS SQL Server....


Author: Se Hee Lee (http://www.jguru.com/guru/viewbio.jsp?EID=21287), Apr 19,
2000
Such mechanism is not possible with MS SQL Server. There is no way of getting the
next sequence number which serves as the primary key in SQL Server. In this MS
SQL case, the developer has to make the table non-automatic, and use some type of
helper class to find the the next key which is always unique.

That is not true. For MS SQL Server you can issue,...


Author: James Pansarasa (http://www.jguru.com/guru/viewbio.jsp?EID=54657), Jun
14, 2000
That is not true. For MS SQL Server you can issue, in the context of the same
transaction, a "SELECT @@IDENTITY ..." call to get the last identity value
generated by the statement. If the statement did not affect any tables with identity
columns, @@IDENTITY returns NULL. If multiple rows are inserted, generating
multiple identity values, @@IDENTITY returns the last identity value generated.

Example (taken from the MS SQL Server 7.0 documentation):

This example inserts a row into a table with an identity column and uses
@@IDENTITY to display the identity value used in the new row.

INSERT INTO jobs (job_desc,min_lvl,max_lvl)


VALUES ('Accountant',12,125)

SELECT @@IDENTITY AS 'Identity'

If you are using Oracle it can be done via a database...


Author: Malcolm Speedie (http://www.jguru.com/guru/viewbio.jsp?EID=100266), Jul
24, 2000
If you are using Oracle it can be done via a database trigger. You can have the trigger
automatically set the id if you do not provide one on insert.

Here is a simple example:

CREATE OR REPLACE TRIGGER emps_in_trg


BEFORE INSERT ON emps
FOR EACH ROW
DECLARE

v_seq_num NUMBER(10);

BEGIN

-- By using IS NULL we give the programmer the option to set these


values
-- otherwISe we default them

IF :new.emp_id IS NULL THEN


SELECT emp_id_sequence.nextval
INTO v_seq_num
FROM dual;
:new.emp_id := v_seq_num;
END IF;
EXCEPTION
WHEN OTHERS THEN
NULL;
-- Should really do something
END emps_in_trg;
/

show errors

This Oracle trigger does not work. You are always ...
Author: Srihari Bathini (http://www.jguru.com/guru/viewbio.jsp?EID=54760), Sep 8,
2000
This Oracle trigger does not work. You are always giving 0 (Zero) to sequence
number, it will say, duplicate key. I tested this.

My approach is to use a simple Singleton Class to ...


Author: Alexandros Kotsiras (http://www.jguru.com/guru/viewbio.jsp?EID=47511),
Jan 8, 2001
My approach is to use a simple Singleton Class to generate PKs instead of a Session
Bean. The only public method of the class is nextVal() which can be implemented in
different ways. The above example shows my prefered implementation by using an
Oracle Sequence :
public class SequenceGen {

private static Context jndiCtx ;


private static DataSource ds ;
private static SequenceGen singleInstance ;

private SequenceGen() {

Hashtable ht = new Hashtable() ;


ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");

try{
jndiCtx = new InitialContext(ht) ;
ds = (javax.sql.DataSource)
jndiCtx.lookup("weblogic.jdbc.jts.EJBThin");
System.out.println("############# SequenceGen.constructor()
called ###############");
}
catch(NamingException ex) { ex.printStackTrace() ;
}
finally {
try{
jndiCtx.close() ;
}
catch(NamingException ex) { ex.printStackTrace() ; }
}
}

private static SequenceGen getSingleInstance() {


if(singleInstance == null) singleInstance = new SequenceGen();
return singleInstance ;
}
// This is the only public method !! You can change the
implementation to whatever unique ID generator you want to use.
public static synchronized long nextVal() {

long nextVal = -1 ;
Connection conn = null ;
PreparedStatement pst = null ;
ResultSet rs = null ;
try{
conn = getConnection();
pst = conn.prepareStatement("Select RMH_SEQ.nextval from
DUAL");
rs = pst.executeQuery();
if(rs.next()) nextVal = rs.getLong(1);
}
catch(SQLException ex) {
ex.printStackTrace() ;
}
finally {
try{
if(rs != null) rs.close();
if(pst != null) pst.close() ;
freeConnection(conn);
}catch(SQLException ex) {
ex.printStackTrace() ;
}

return nextVal ;
}
}

private static Connection getConnection()


{
Connection conn = null ;
try{
conn = getSingleInstance().ds.getConnection() ;
System.out.println("Sequence.getConnection() called ");
}
catch(SQLException ex) { ex.printStackTrace() ; }
return conn ;
}

private static void freeConnection(Connection conn)


{
try{
if(conn != null) conn.close();
}
catch(SQLException ex) {
ex.printStackTrace() ;
}
}

public static void main(String[] args) {


System.out.println("nextval 1 : " + SequenceGen.nextVal());
// This time the constructor will not be called again
System.out.println("nextval 2 : " + SequenceGen.nextVal());
}
}
Then in the Entity Bean i add a no-args ejbCreate() method as follows :
public class CabinBean implements EntityBean {

int id ;

public CabinPK ejbCreate() throws Exception {


int _id = (int)SequenceGen.nextVal();
this.id = _id ;
return null ;
}

.
.
.
}
This should be faster and is definitelly simpler than the Session context approach. No
need for <ejb-ref> in all your Entity Beans
Also it hides from the Client the creation of the PKs. I don't want the EJB client
Application to have control over the creation of PK values. The advantage of the
Session bean approach is that it is accessible from remote Entity Beans (residing in
external JVMs).

Re: My approach is to use a simple Singleton Class to ...


Author: Jasen Halmes (http://www.jguru.com/guru/viewbio.jsp?EID=766898), Feb
21, 2002
The problem with this approach is that if you can't rely on a "trigger/sequence" like
mechanism at the db level and you implement your own, you need to write an SQL
update statement. When you try to commit that, you get an IllegalStateException
because apparently jdbc inherits the callers transaction state, in this case an EJB.
Has anyone figured out how to use a non EJB id generation that uses jdbc and is
called from an EJB and does an update (and therefore a commit)?

Re: My approach is to use a simple Singleton Class to ...


Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Feb 21, 2002
Alexandro,
how do you handle clustering ?

Re[2]: My approach is to use a simple Singleton Class to ...


Author: Nick Kelly (http://www.jguru.com/guru/viewbio.jsp?EID=768078),
Feb 22, 2002
I think the proposed singleton solution is OK, because it uses an Oracle
sequence to generate the actual key - which always returns a new unique value
when you invoke .NEXTVAL.

However, it is still an Oracle specific solution. It would be nicer to see a


mechanism that was directly portable across DBs.

Re[3]: My approach is to use a simple Singleton Class to ...


Author: cedric perrot
(http://www.jguru.com/guru/viewbio.jsp?EID=1059101), Oct 8, 2003
this is the only portable way for different databases. from the code you just
call the procedure or function. otherwise you have to cope with
@@IDENTITY's in SQL Server, ROWID's in Oracle .... i appended the
oracle solution its easy to port it to any database.

create table uk_sequence_table ( TABLE_NAME varchar2(100), COUNTER


integer );
ALTER TABLE uk_sequence_table ADD PRIMARY KEY (TABLE_NAME)
USING INDEX TABLESPACE TS_SALE_INDEX01;
CREATE OR REPLACE FUNCTION uk_for_table (tname IN VARCHAR)
RETURN INTEGER IS cntr INTEGER; -- declare the return variable BEGIN
lock table uk_sequence_table in exclusive mode; update uk_sequence_table
set COUNTER = COUNTER + 1 where TABLE_NAME = tname; select
COUNTER into cntr from uk_sequence_table where TABLE_NAME =
tname; RETURN cntr; END; /
CREATE OR REPLACE PROCEDURE uk_for_table_proc ( tname IN
VARCHAR, lngIdentity OUT INTEGER ) IS BEGIN lock table
uk_sequence_table in exclusive mode; update uk_sequence_table set
COUNTER = COUNTER + 1 where TABLE_NAME = tname; select
COUNTER into lngIdentity from uk_sequence_table where TABLE_NAME
= tname; END;
INSERT INTO uk_sequence_table (TABLE_NAME, COUNTER) VALUES
('<your tablename>', 0);

Re: My approach is to use a simple Singleton Class to ...


Author: jyothi veera (http://www.jguru.com/guru/viewbio.jsp?EID=1084918),
May 14, 2003
I have pretty much understood the code but iam not sure about where to include
this code in wsad and also i din't get a clear picture about the jndi context. Please
can you explain me a little bit in detail Thanks

How do you model for a JOIN operation in a relational database using entity
bean(s)? Do you have to have separate entity beans for each table in the
database?
Location: http://www.jguru.com/faq/view.jsp?EID=37219
Created: Apr 17, 2000 Modified: 2000-04-18 15:06:30.614
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Benjamin Ghofrani
(http://www.jguru.com/guru/viewbio.jsp?EID=28085

This depends on the granularity and the design of your Entity beans.

A way to do it is to model an Entity for each table and for the join specify a reference
to Entity Bean 2 (from table2 ) from Entity Bean 1 (from table 1). If this is a one-to-
one relationship then you could easily place these into the same Entity bean - this is
a design issue and has other factors involved.

For a one-to-many relationship you could specify a collection of EJB references to


Entity Bean 1 inside Entity Bean 2.

If you're using CMP, the above information will be very much reliant on the EJB CMP
tool that you are using. Each tool has its strengths. I am basing this response on the
Inprise Application Server 4.0.

Comments and alternative answers

Another possibility is that one of the tables may not...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Apr 24, 2000
Another possibility is that one of the tables may not map to an entity at all: it may
instead map to a 'value object' AKA 'dependant object'. Again this really depends on
what your beans _are_, on what your design is. An example where I'd probably use
value objects is where i have a Customer (which would be an entity) who has many
Addresses (each of which would be a value object). The net effect is that your Entity
becomes more coarse grained, which is generally considered a Good Thing in
distributed systems. This has several advantages:

1. You can pull an address across the wire/process boundary in one shot, which is
nice since you usually use most of the fields of an address.
2. It's simpler to construct good transactions, since you get a big chunk of data,
which you can call accessors on locally, therefore out of transaction scope.
3. It allows you to define an optimistic locking mechanism at the Customer level,
so that you can detect when possibly conficting changes are made to any of
the Customer's dependents

Re: Another possibility is that one of the tables may not...


Author: Banda Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=389958),
Apr 5, 2001
hi, if we use one entity bean for multiple tables, is that possible to
insert/delete/update (DML) operations on the tables thru this entity bean? if yes,
how?? please give me a detailed answer.

Joins in Entity Beans


Author: surya navi (http://www.jguru.com/guru/viewbio.jsp?EID=388862), Mar 27,
2001
To avoid the complicated nature of doing joins with Entity beans , we took the
DAO(Data access Objects) route suggested in J2EE design blue prints book. In
Session bean , create a connection object and pass it to DAO JavaBean's method with
the required parameters. In DAO, we execute a simple SQL query using Statement
object and return a collection to session bean.We use the entity beans only for creating
and updating records.For search we avoid entity beans. This improves performance
too and this is the route suggested by Weblogic People.It works nicely and simplified
the programming work in our project

Re: Joins in Entity Beans


Author: henry lee (http://www.jguru.com/guru/viewbio.jsp?EID=489761), Sep 24,
2001
test

Re: Joins in Entity Beans


Author: Anthony Alcamo (http://www.jguru.com/guru/viewbio.jsp?EID=571329),
Dec 3, 2001
Surya, This improves performance, but can be quite dangerouse to write data
without the transactional facility your EJB container provides. Anthony

Re[2]: Joins in Entity Beans


Author: Vincy Kalvar (http://www.jguru.com/guru/viewbio.jsp?EID=988302),
Aug 23, 2002
As surya says he uses DAO's only for finders.Not to update,create.So it can't
be that dangerous is my guess.

test
Author: henry lee (http://www.jguru.com/guru/viewbio.jsp?EID=489761), Sep 24,
2001
test

How should singleton EJBs be implemented in a cluster ?


Location: http://www.jguru.com/faq/view.jsp?EID=37838
Created: Apr 19, 2000 Modified: 2000-04-19 12:16:11.852
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Aravind Naidu
(http://www.jguru.com/guru/viewbio.jsp?EID=12326

There is no such thing as a Singleton EJB. This design pattern cannot be achieved
with EJB, an alternative solution to the problem using J2EE standards includes
implementation using RMI or CORBA.
Comments and alternative answers
I have to somewhat disagree with the answer regarding,...
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), Jun
21, 2000
I have to somewhat disagree with the answer regarding, "...This design pattern cannot
be achieved with EJB," and just make the suggestion that you could set your bean up
so that there is only one istance of it in the EJB pool controlled by the container. In
this case, if a client had a connection to this "Singleton"-like EJB bean, then any other
client would have to wait. Use the maxBeansInFreePool and maxBeansInCache fields
in the deployment descriptor.

Or, for an entity bean, don't provide any create m...


Author: Constantin Gonciulea
(http://www.jguru.com/guru/viewbio.jsp?EID=124918), Aug 11, 2000
Or, for an entity bean, don't provide any create method, and make the find method
return a fixed primary key. In this case you'd have to store the bean "manually" in the
database.

You cannot just narrow down the pool to one instance...


Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362), Oct
11, 2000
You cannot just narrow down the pool to one instance and call it a solution, it is a
hack. It does not work in a cluster, and still does NOT gurantee that the same physical
instance will be used.

Another flaw is that not all EJB containers allow you to control the pool at such a fine
level and those that do provide minimums that are larger than 1.

Singleton pattern with EJBs


Author: Puppa Kononen (http://www.jguru.com/guru/viewbio.jsp?EID=490736), Sep
5, 2001
There is no way to implement a singleton pattern in a distributed environment without
having a single point of failure.

I think you can use reference storing to JNDI (or the Handle), but then all the requests
for that EJB would be pointed at the same server, which might not be efficient. The
only resources that are shown to all servers in a cluster are the JNDI tree and normally
the database. Also the information between entity bean's that represent the same data
is shared, so entity bean's are the first place where I would store 'singleton'
information.

Yes, there still issues to be solved (what happens if two EJB clients want to change
the same data), but this way you can provide similar behaviour as in the singleton
pattern.

How do I connect to SQL Server 6.5 from J2EE for Windows? What changes
should I have to do in the properties file? Can I use the JDBC-ODBC bridge?
Location: http://www.jguru.com/faq/view.jsp?EID=37845
Created: Apr 19, 2000 Modified: 2000-04-24 19:56:01.653
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Sathya Narayanan
(http://www.jguru.com/guru/viewbio.jsp?EID=31789

If you insist on initially using a database other than Cloudscape, you should carefully
read and follow the instructions in the following J2EE RI documentation:

• Configuration Guide
• Release Notes

How is the passivation of Entity beans Managed?


Location: http://www.jguru.com/faq/view.jsp?EID=38317
Created: Apr 20, 2000 Modified: 2000-04-21 12:15:35.921
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by Sripada Srinivas
(http://www.jguru.com/guru/viewbio.jsp?EID=23408

The passivation of Entity beans is managed by the container. To passivate an


instance, the container first invokes the ejbStore() method for synchronizing the
database with the bean instance, then the container invokes the ejbPassivate()
method. It will then return the bean instance back to the pooled state. (Every bean
has an instance pool.)

There are two ways for transitioning an entity bean from the ready to the pooled
state, by using the ejbPassivate() or ejbRemove() method. The container uses
ejbPassivate() to disassociate the bean instance from the entity object identity, and
uses ejbRemove() to remove the entity object.

When the instance is put back into the pool, it is no longer associated with an entity
object identity. The container can now assign the instance to any entity object within
the same entity bean home.

A bean instance in the pool can be removed by using unsetEntityContext().

A more thorough discussion can be found in the EJB 1.1 specification by Sun.

Comments and alternative answers

The short answer is "by the container" :...


Author: Gene De Lisa (http://www.jguru.com/guru/viewbio.jsp?EID=38746), Oct 9,
2000
The short answer is "by the container" :)

Activation/passivation means different things to session beans and entity bean. In a


stateful session bean, the container will persist the state in activate/passivate. This
does not happen for entity beans.
Activation for an entity bean means "the container has just grabbed an anonymous
instance of the entity class from the free pool and has associated it with an identity".
Identity means a primary key stored in an EJBObject. Beans in the free pool have no
valid state since they are not associated with an EJBObject (and therefore a primary
key).There is no loading of state here. With BMP you load the state in ejbLoad; with
CMP the container does it right before ejbLoad.

Passivation for an entity bean means "the container is done with this instance and it is
going back to being an anonymous member of the free pool". There is no saving of
state here. With BMP you save the state in ejbStore; with CMP the container does it
right after ejbStore.

Take a look at the EJB spec 1.1 on page 102. Figure 23 shows this is a pseudo Harel
state diagram. Also look at Figure 28, page 138 and Figure 29, page 139 for object
interaction diagrams.

To complete a transaction, which Transaction Attributes or Isolation Level


should be used for a stateless session bean?
Location: http://www.jguru.com/faq/view.jsp?EID=38749
Created: Apr 21, 2000 Modified: 2000-08-03 22:23:58.612
Author: Gene De Lisa (http://www.jguru.com/guru/viewbio.jsp?EID=38746)
Question originally posed by Santosh Malpekar
(http://www.jguru.com/guru/viewbio.jsp?EID=30121

[For example, I have a method transfer which transfers funds from one account to
another account.]

Vague question. Is the Session bean doing the DB work? I'll assume no.

Let's say AtmEJB is a Session bean with the transfer method. Let's say AccountEJB is
an Entity bean.

Step 1:

When the client invokes the transfer method you want that to be the transaction; i.e.
"the transfer transaction". therefore you need to set the tx attribute of transfer to
something that will make the container start a tx at the beginning of transfer and
terminate it at the end of transfer. RequiresNew might be a good choice but you need
to look at all your use cases not just this one.

Step 2:

The AccountEJB methods invoked from the transfer method need to have a tx
attribute that allows them to be part of an ongoing tx. That means that deposit and
withdraw cannot be RequiresNew! (that would suspend the transfer tx and run in its
own tx). Look at the spec for these: there are 3 that meets the criteria for deposit
and withdraw in the transfer use case. Which one to use? What are the other use
cases in which deposit and withdraw will be called? Find one that works for each one.

Explain the different Transaction Attributes and Isolation Levels with


reference to a scenario.
Location: http://www.jguru.com/faq/view.jsp?EID=39161
Created: Apr 23, 2000 Modified: 2000-08-03 22:14:50.017
Author: Milind Sawant (http://www.jguru.com/guru/viewbio.jsp?EID=36835)
Question originally posed by Santosh Malpekar
(http://www.jguru.com/guru/viewbio.jsp?EID=30121

The Enterprise JavaBeans model supports six different transaction rules:

• TX_BEAN_MANAGED. The TX_BEAN_MANAGED setting indicates that the


enterprise bean manually manages its own transaction control. EJB supports
manual transaction demarcation using the Java Transaction API. This is very
tricky and should not be attempted without a really good reason.

• TX_NOT_SUPPORTED. The TX_NOT_SUPPORTED setting indicates that the


enterprise bean cannot execute within the context of a transaction. If a client
(i.e., whatever called the method-either a remote client or another enterprise
bean) has a transaction when it calls the enterprise bean, the container
suspends the transaction for the duration of the method call.

• TX_SUPPORTS. The TX_SUPPORTS setting indicates that the enterprise bean


can run with or without a transaction context. If a client has a transaction
when it calls the enterprise bean, the method will join the client's transaction
context. If the client does not have a transaction, the method will run without
a transaction.

• TX_REQUIRED. The TX_REQUIRED setting indicates that the enterprise bean


must execute within the context of a transaction. If a client has a transaction
when it calls the enterprise bean, the method will join the client's transaction
context. If the client does not have a transaction, the container automatically
starts a new transaction for the method. Attributes

• TX_REQUIRES_NEW. The TX_REQUIRES_NEW setting indicates that the


enterprise bean must execute within the context of a new transaction. The
container always starts a new transaction for the method. If the client has a
transaction when it calls the enterprise bean, the container suspends the
client's transaction for the duration of the method call.

• TX_MANDATORY. The TX_MANDATORY setting indicates that the enterprise


bean must always execute within the context of the client's transaction. If the
client does not have a transaction when it calls the enterprise bean, the
container throws the TransactionRequired exception and the request fails.

Comments and alternative answers

Yes we can all read p 177-178 of the EJB spec. Where...


Author: Gene De Lisa (http://www.jguru.com/guru/viewbio.jsp?EID=38746), Apr 28,
2000
Yes we can all read p 177-178 of the EJB spec. Where is the scenario the questioner
asked for?

Re: Yes we can all read p 177-178 of the EJB spec. Where...
Author: Kalpeshkumar Soni
(http://www.jguru.com/guru/viewbio.jsp?EID=916018), Jul 2, 2002
Nobody seems to paying attention to isolation levels !

Re: Yes we can all read p 177-178 of the EJB spec. Where...
Author: sesha venkat (http://www.jguru.com/guru/viewbio.jsp?EID=1245960),
May 26, 2005
Hi

I still did not understand the difference between TX_REQUIRED and


TX_SUPPORTS from the explanation given. Can anybody explain.

Thanks in advance.

Re[2]: Yes we can all read p 177-178 of the EJB spec. Where...
Author: Giri B (http://www.jguru.com/guru/viewbio.jsp?EID=1248402), Jun
13, 2005
TX_REQUIRED A bean is going to participate in TX or a client call a Bean
then that method should executed in the TX if client doesnot have the TX then
Container will create the TX for that TX_SUPPORTS The client supports the
TX to the method execution.If the client doesnot have any TX then the method
will execute without TX

Are there any good examples of how to handle one-to-many, many-to-one,


and many-to-many entity bean relationships?
Location: http://www.jguru.com/faq/view.jsp?EID=40120
Created: Apr 25, 2000 Modified: 2000-04-26 10:48:11.45
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Joe McDaniel
(http://www.jguru.com/guru/viewbio.jsp?EID=5292

The EJB spec does not specify how to deal with relationships. You'll have to develop
your own Java classes to handle these design patterns.

Francesco Mondora points us to an IBM RedBook on EJB Development using


VisualAge (chapter 10),

The itso.bank.ejb.relation package includes two classes (ManyLink and SingleLink)


that support implementing persistent one-to-many associations between entity
beans depending on storing and retrieving primary or foreign key values in a
database. The one-to-many relationships are mapped to backward pointing foreign-
key references.
Class ManyLink implements the multi-value association end. Depending on the
relation type parameter in the constructor, ManyLink supports an aggregation
association (the parent controls the live cycles of its children) or a normal
association.

Class SingleLink is the single-valued inverse association end of the one-to-many


relationship.

Which IDEs are available that support EJB development? And are any free or
low-cost?
Location: http://www.jguru.com/faq/view.jsp?EID=40579
Created: Apr 26, 2000 Modified: 2000-04-26 10:57:05.156
Author: Keir Hansen (http://www.jguru.com/guru/viewbio.jsp?EID=38387) Question
originally posed by DINESH DEWAN
(http://www.jguru.com/guru/viewbio.jsp?EID=37190

We've been doing some review of WebGain's StructureBuilder 3.3, which supports a
UML-to-Javacode cyclical development, and with its new "ejbCreate" facility, supports
1.0 and 1.1 EJB development. So far, we're thoroughly impressed. A little
clunky/slow, but definitely worth investigating for lower cost (standard $395,
enterprise $695) bean development.

A fully functional demo is available at


http://www.webgain.com/Products/Structure_Builder/.

What is the most efficient approach for integrating EJB with JSP? Should the
EJBs be invoked directly from within JSP scriptlets? Should the access take
place from within Java beans? Or is it best to use custom tags for this
purpose?
Location: http://www.jguru.com/faq/view.jsp?EID=42963
Created: May 1, 2000 Modified: 2000-05-02 23:22:15.212
Author: Christopher Longo (http://www.jguru.com/guru/viewbio.jsp?EID=2166)
Question originally posed by Sanjay Mistry
(http://www.jguru.com/guru/viewbio.jsp?EID=17764

JSP scriptlet code should be minimal. Invoking EJB code directly on a JSP page
results in many lines of code on your JSP page, including try...catch blocks to catch
naming and finding exceptions.

Using a standard JavaBean as an intermediary between the JSP page and EJB server
cuts down on the amount of code needed to add to a JSP page, and promotes reuse.
The JavaBean should be a simple wrapper around the EJB you are accessing.

If you use a standard JavaBean you could also use the jsp:useBean tag to setup EJB
parameters, such as the server URL and server security parameters.

Custom tags are also an option. However, they require a lot more coding than a
simple JavaBean wrapper. The point should be to rewrite as little code as possible
while at the same time keeping the JSP scriptlet content as light as possible.

Comments and alternative answers


See also How can my JSP page communicate with an EJB...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 29,
2000
See also How can my JSP page communicate with an EJB Session Bean?.

Ok, fine. How about this: Your regular JavaBean creates...


Author: Gene De Lisa (http://www.jguru.com/guru/viewbio.jsp?EID=38746), Aug 1,
2000
Ok, fine. How about this: Your regular JavaBean creates a Session bean. Where does
it remove the Session bean?

There is no "stopUsingBean" tag. You cannot rely on the finalizer. So, do you just
wait for the session timeout?

This is why I don't use the JavaBean intermediary.

Simple. Have a method in your bean: public void...


Author: Christopher Longo (http://www.jguru.com/guru/viewbio.jsp?EID=2166), Oct
12, 2000
Simple. Have a method in your bean:
public void removeSession()
{
session.remove();
}

The Orionserver taglibs provide a really easy way using...


Author: Mathias Bogaert (http://www.jguru.com/guru/viewbio.jsp?EID=202039), Dec
28, 2000
The Orionserver taglibs provide a really easy way using EJB's with JSP pages, and it
is fast too. Download from: http://www.orionserver.com/tags/ejbtags/

What if I have JSP in one server(View), Servlet in...


Author: Rangarajan Mangudi Parthasarathy
(http://www.jguru.com/guru/viewbio.jsp?EID=347775), Mar 16, 2001
What if I have JSP in one server(View), Servlet in another server(Controller),EJB in
another server(Model). Does it not improve the scalability of my application?. Give
me some sample code if possible.

How do you get a JDBC database registered with a JNDI name so that it can
be accessed from an EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=42968
Created: May 1, 2000 Modified: 2000-08-24 18:58:56.376
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by David Bosschaert
(http://www.jguru.com/guru/viewbio.jsp?EID=40641
The short answer is that it depends on which container you're using to some extent.
The one thing that (should be) common in EJB 1.1 containers is that the ejb-jar.xml
file's entry for that bean needs to contain a 'resource-ref' stanza, like so:
<resource-ref>
<res-ref-name>jdbc/LocalDB2<res-ref-name>
<res-type>javax.sql.DataSource<res-type>
<res-auth>Container<res-auth>
<resource-ref>
The res-ref-name is the most interesting part. This is the JNDI name relative to the
java:comp/env namespace. Hence, to get this connection you'd do (in your bean):
Context context = new InitialContext();
DataSource source = context.lookup("java:comp/env/jdbc/LocalDB2");
which gives you a DataSource that you can call getConnection on.

The other half of this is container specific and done at deployment time by a
'Deployer' or 'Assembler' (to use the rolenames specified by the EJB spec.) This can
work very differently from one container to the next, but here are a couple of
(abbreviated) examples.

With Weblogic 5.1, you must define a connection pool in weblogic.properties, then
edit the weblogic specific deployment descriptor (using the EJB Deployment tool) to
associate the resource-ref specified in ejb-jar.xml with that connection pool.

With Inprise Application Server 4.0, all of the parameters for the connection (JDBC
driver, connection URL, etc.) are specified in the inprise specific deployment
descriptor (also editable via their deployment tool).

Other servers will have other ways of associating the resource-ref with a pre-defined
connection pool.

Comments and alternative answers

I would like to know how I get my existing JDBC da...


Author: David Bosschaert (http://www.jguru.com/guru/viewbio.jsp?EID=40641),
May 8, 2000
I would like to know how I get my existing JDBC database registered with JNDI so
that I can use it as explained in this page.

To give an example: I use the open source database InstantDB. Normally I would
connect to it with:

Class.forName("idbDriver");
Connection con =
DriverManager.getConnection("jdbc:idb:c:\temp.prp");
How and where do I register my JDBC database in order to use it with EJB's through
the JNDI?

I would like to know how I get my existing JDBC database registered with JNDI.

Author: Sribha Jain (http://www.jguru.com/guru/viewbio.jsp?EID=484436), Sep 26,


2001
I am SQL server as my database and weblogic 4.0 Application server

How to manage fields that can have null values in a container-managed


Entity bean?
Location: http://www.jguru.com/faq/view.jsp?EID=43332
Created: May 2, 2000 Modified: 2000-05-02 12:53:12.198
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by guru guru
(http://www.jguru.com/guru/viewbio.jsp?EID=39655

First of all, let's just set up a typical scenario:

You are developing a product which allows a bank to sign up new customers online.
You have done analysis and design and settled on having two tables: 'users' and
'account' (let's keep it simple). Each "user" will have a corresponding "account". The
foreign key between the two will be the "account number".

So, for the 'users' table, you have the following fields: firstName, lastName, userId,
password, and acctNum. When this table is created in the database, it is empty. Now
you must relate your EJB code to this table for persistence. For simplicity sake I will
leave out the Session bean (which I would use to talk to my Entity bean), the Entity
bean primary key class, and the home and remote interfaces.

We have the UserBean:

public class UserBean implements javax.ejb.EntityBean {


public String firstName = null;
public String lastName = null;
public String userId = null;
public String password = null;
public long acctNum = -1;

/**
* Called by the container after the UserHome.create() is called
*/
public void ejbCreate(String userId, String password, long acctNum) {
this.userId = userId;
this.password = password;
this.acctNum = acctNum;
}
...
...
public void setUserData(UserData data) throws RemoteExeption,
UserDataException {
this.firstName = data.getFirstName();
this.lastName = data.getLastName();
}
...
...
}
Now, assuming you have the User (remote interface class), UserHome (home
interface class), UserPK (primary key class) already done, you need to create the
bean's deployment descriptor. Inside the deployment descriptor, you must specify the
database table, 'users', which this bean will map to. Also, you must specify which
fields from your bean map to which fields in the 'users' database table. (This is how
the container knows which fields to persist between your bean and the database
table.) Now assuming all code compiles and you have an EJB server up and running
and you have deployed your bean, all you need to do is write a client (I would use a
client to access a session bean, say 'CustomerSession', which would talk to my entity
bean) to create a new user and pass in the userId, password and acctNum values,
which will create the new user in the database.

Notice the fields in the UserBean will now be set, but the firstName and lastName
fields will still be set to null. These fields will still be empty in the database and will
not change until these fields are set in the bean, since it is persisted. Now, call the
setUserData(UserData data) method for setting the firstName and lastName, and
these fields will now be set in the database and no longer be null. The container will
handle the persistence of any fields which are set to null, just as it will handle any
fields which are set to some meaningful value.

Comments and alternative answers

NOT NULL
Author: pei wang (http://www.jguru.com/guru/viewbio.jsp?EID=424597), May 18,
2001
How about if the lastname, firstname are defined as NOT NULL in user table? What
will happen when the EJB try to persist itself the first time?

How can I debug my EJB applications?


Location: http://www.jguru.com/faq/view.jsp?EID=45681
Created: May 7, 2000 Modified: 2000-05-11 10:08:40.327
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Sanjay Mistry
(http://www.jguru.com/guru/viewbio.jsp?EID=17764

This depends upon which EJB Container you are using.

Borland's JBuilder 3.5, Foundation Edition allows you to debug any Java 2
application, including the Inprise Application Server, WebLogic Server and J2EE
Reference implementation. You can download it free from www.borland.com/jbuilder.

There are other IDE's out there including NetBeans/Forte www.sun.com/forte/ffj/ce/


that can also debug EJB.

Comments and alternative answers

The IDE Visual Café has a unique remote debugging...


Author: Christoph Krüger (http://www.jguru.com/guru/viewbio.jsp?EID=30208),
May 16, 2000
The IDE Visual Café has a unique remote debugging feature which allows you to
debug the EJB or any other Java class from your desktop while it is running on the
Application Server. Unfortunately it's not freely available but you can get a 60 day
unlimited trial version.

Our Application Server is the Objectspace Voyager ...


Author: Frank Falkenberg (http://www.jguru.com/guru/viewbio.jsp?EID=25357), Jun
13, 2000
Our Application Server is the Objectspace Voyager 3.3. To debug our EJB
applications on this Application Server we are using a remote debugger (it is the
Debug Enterprise from Metamata; see: http://www.metamata.com ). This debugger is
not Application Server specific as many other products we tried to evaluate (if you are
using BEA WebLogic you may have a much wider range of remote debug tools to
choose from).

To debug you compile your EJB source files with the metamata compiler 'mjavac' and
deploy the class files including the automatically generated debuginfo class file in a
JAR as you would normally do with your EJB application. When you start the
Application Server, you can attach to the process of the server/container from the
remote debug console and perform all standard debug actions as setting breakpoints,
defining watches, stepping through your EJB code expression by expression etc.

My impression is that this remote debugger is easy to use and improves our
development process for EJB applications very much - b.t.w. we used mainly
'System.out.println' - debugging before.

How can an applet talk directly with EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=46410
Created: May 8, 2000 Modified: 2000-05-09 08:36:22.113
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Sanjay Mistry
(http://www.jguru.com/guru/viewbio.jsp?EID=17764

An applet must use the same procedure as any other Java class: it must use JNDI to
locate the EJB Home Interface, then use RMI to talk with the Home Interface as well
as the EJB itself.

This means that the J2EE and/or JNDI and/or RMI classes need to be present in the
applet's Java Virtual Machine. The easiest way to assure this is to use the latest Java
Plug-in. Netscape 6, aka Mozilla, ships with the Java Plug-in. Other browsers have
various problems with RMI and JNDI classes that are beyond the scope of this
answer.

Note, however, that it is not recommended to use EJB directly from applets, in part
due to compatibility issues. Instead, you can use Servlets inside the application
server to provide an HTML front-end that is assured to work on a much larger base
of clients.
Comments and alternative answers

Has anyone used applet in Netscape with EJB an ? What...


Author: Michael Chen (http://www.jguru.com/guru/viewbio.jsp?EID=278118), Dec
14, 2000
Has anyone used applet in Netscape with EJB an ? What do you do with the j2ee.jar,
is it included as part of the archive?

Why isn't it recommended to use EJB from applets? What...


Author: Pratap Das (http://www.jguru.com/guru/viewbio.jsp?EID=129542), Mar 7,
2001
Why isn't it recommended to use EJB from applets? What are the compatibility issues
that you mention? Also, if the users need a much more dynamic interaction with the
GUI, wouldn't you still use an applet?

Re: Why isn't it recommended to use EJB from applets? What...


Author: Mark Bennetts (http://www.jguru.com/guru/viewbio.jsp?EID=445713),
Jun 26, 2001
Dont forget that EJB communication uses RMI-IIOP protocols. A good reason for
not performing direct Applet - EJB communication is because of firewalls that will
block these protocols. It is much safer (and well recognised) to use basic
HTTP/HTTPS between client and Web server, and then communicate to the EJB
tier from the Web tier. Hope this helps.

Keep in mind that the Java runtime that comes with...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Mar 8,
2001
Keep in mind that the Java runtime that comes with browser is Java 1.1-based, not
Java 1.2+ based. Also, keep in mind that an untrusted applet can only communicate
back to the server from which it came. You are basically forcing your users to
download the Java Plug-in AND the J2EE classes if you want to use EJB in an applet.
And, more then likely it will need to be signed... Instead, you should rely on some
middleware to do the actual EJB communications.

The best solution for applet to communicate with EJB...


Author: harish ganesan (http://www.jguru.com/guru/viewbio.jsp?EID=347623), Mar
9, 2001
The best solution for applet to communicate with EJB will be through an intermediate
servlet. The applet to servlet communication can be established as firts step. The
servlet can act as EJB client. This type of architecture is easy to maintain and
effectively deploy web applications.

What is the best way of implementing a web application that uses JSP,
servlet and EJB technologies all together following a Model View Controller
(MVC) architecture?
Location: http://www.jguru.com/faq/view.jsp?EID=48001
Created: May 11, 2000 Modified: 2000-06-21 11:05:30.729
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by christophe hillegeer
(http://www.jguru.com/guru/viewbio.jsp?EID=43669

[See the Sun J2EE Blueprints for "an integrated set of documentation and examples
that describe and illustrate 'best practices' for developing and deploying component-
based enterprise applications using the J2EE platform" including some good
architecture whitepapers and source code. -Alex]

Hmm, 'Best Way' is a bit rough - there are several 'good' ways, and the usual set of
trade-offs between them. (I'm a consultant - I have to start any answer with "It
depends...", otherwise they revoke my whiteboard privileges)

The main thing you need to keep in mind as you design this sort of a system is that
you want the interface into the EJB's to be rather narrow: in any flow, the ideal is to
call one EJB method (hopefully on a stateless session bean), and let it make calls to
entities on your behalf, then hand back the data you need to display.

How you display it depends: you can either embed beans on your JSPs and let the
beans make that hopefully-one EJB call, or you can post to a servlet, let that make
the call, then forward to the JSP for display. The second of these is more flexible and
gives you more leverage to hide, change, and enforce your site's structure. The first,
however, will be easier for developers new to this web thing to follow.

Essentially, I'm saying that Entity beans are your model, your controller is Session
beans (maybe with a bit of help from servlets or beans), and your JSPs, beans and
servlets are your View.

One thing to note here: this discussion strongly implies that your EJBs are capable of
externalizing their state as some number of very simple 'value objects' (not EJBs
themselves, just something we can pass back and forth). These value objects are
probably tuned tightly to a workflow, and will be produced by that session bean. This
way the traffic between the EJB (server) and the JSP/Servlet (client) is tuned to what
the client needs, while the transaction load on the server is minimized.

Comments and alternative answers

I have to disagree (somewhat) with the comment that...


Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), May
17, 2000
I have to disagree (somewhat) with the comment that "...your controller is Session
beans...", because it really "depends" on the architecture of the system. The Session
beans will not look up any Entity beans or invoke any methods on an Entity bean
without a client invoking a method on the Session bean itself. In other words, the
controller could be an independent Java application, or a C++ application using
CORBA, or a combination of HTML/WML page with servlets, or another EJB
application. The controller really takes on multiple forms depending on the
architecture of the system. If I had a simple system constructed of EJB beans, with
JSP's providing the interface between the client (web) and the application, then the
JSP's (actually servlets compiled from JSP) would be the controller. If I had an RMI
application on another server talking directly to the Session beans of my server, then
the RMI application is the controller.

I am working on a large project using model view a...


Author: Vibhu Srinivasan (http://www.jguru.com/guru/viewbio.jsp?EID=60278), May
31, 2000
I am working on a large project using model view architecture. Here goes my two
cents worth of an architecture that has produced good results for us

The architecure involves a MVC with the controllers being entity and session beans.
We are moving away from using entity beans unless there are many transactions
involved. These ejbs pass back value objects as specified in the blueprints by sun.

We also use bulk accessor session beans which go directly to the database and also
call some other session or entity beans.

This is the model.

Now about the controller and the view:

• All the JSP's talk to servlets which are the controllers.


• The servlets control creation and setting various properties on the java beans.
• The java beans are broken to two kinds.
1. Data access beans
2. Presentation beans
• The servlets create the presentation beans which are tied to some screens .
• The JSPs only read information from the java beans.

Check out the blueprints from sun for some good analysis!

Re: I am working on a large project using model view a...


Author: Anupam De (http://www.jguru.com/guru/viewbio.jsp?EID=958113), Mar
15, 2003
I have a question - if you are using JSP/Beans combination, then the View model
will be tying in the bean hard coding the data to the table with the html codes.
How best to separate it out ? One I was thinking was with Hashtables/Array ? But
I am looking or complete separation of the presentation layer from any code
snippets of Java. I am using Apache Tomcat 4.0.1

J2EE architecture
Author: Mindy Couleur (http://www.jguru.com/guru/viewbio.jsp?EID=1175354), Jun
1, 2004
I am new to J2EE and am wondering if you can expand on your answer a bit. I've
noticed that much of the logic that I see in Servlets could go in EJB's. I'm wondering
just how thin the servlet layer should be. I also would like to confirm some RMI logic
flow. As far as I understand..... JSP calls Servlet Remote interface then Servlet call
EJB remote interface....reply goes back to servlet then servlet forwards to JSP for
display. Is that considered the best way to separate the layers?

Are there any JNDI tutorials?


Location: http://www.jguru.com/faq/view.jsp?EID=50797
Created: May 17, 2000 Modified: 2000-05-17 14:07:17.49
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Yes, check out The JNDI Tutorial online and/or buy a copy of it here.

What books cover JNDI (Java Naming and Directory Interface)?


Location: http://www.jguru.com/faq/view.jsp?EID=50819
Created: May 17, 2000 Modified: 2000-05-17 14:17:58.483
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out The JNDI Tutorial. It's also available on the web.

For other books that are relevant to JNDI, check out Are ther any books that provide
decent JNDI coverage?.

When does the container call my bean's ejbCreate / ejbPostCreate /


ejbStore / ejbPassivate / ejbActivate / ejbLoad / ejbPassivate method? And
what should I do inside it?
Location: http://www.jguru.com/faq/view.jsp?EID=51577
Created: May 18, 2000 Modified: 2000-06-19 12:41:34.947
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

The lifecycle of an enterprise bean is the heart of the EJB system. Your bean is
basically implemented as a set of callback methods. There are a lot of these
methods, which can be confusing; however, the implementation of each one is
actually quite straightforward. Most of the time you can get away with implementing
only a few of them.

Using Bean-Managed Persistence, each callback method ejbX means the obvious
thing (usually "you must do X").

Using Container-Managed Persistence,

• ejbCreate means "fill in your defaults"


• ejbPostCreate means "your primary key is now valid; keep initializing"
• ejbStore means "I'm about to store your data into the DB"
• ejbPassivate means "I just stored your data, and I'm about to passivate you"
• ejbActivate means "I just activated you, and I'm about to load in your data"
• ejbLoad means "I just loaded your data from the DB"

The following table is based on the EJB Spec 1.1, chapter 9, section 5. Section 9.4
and 9.5 has detailed descriptions of each of the callbacks; you should definitely read
the spec, and use the table as a quick reference only.
Initialization:

Container-Managed Persistence Bean-Managed Persistence


Client calls EJBHome create()
Container calls ejbCreate()
Bean fills in default values Bean creates representation in DB
Container extracts field values from bean
Container creates representation in DB
Container creates a new Remote Object (Wrapper)
Container calls ejbPostCreate()
Primary Key is now valid
Bean does more initialization
Container creates a new EJB Instance
Home returns a remote reference to client

Passivating an active instance:

Container-Managed Persistence Bean-Managed Persistence


Container calls ejbStore()
Bean performs pre-storage cleanup Bean stores data into DB
Container extracts container-managed fields
Container stores data into DB
Container calls ejbPassivate()
Bean performs post-storage cleanup

Activating a passive instance:

Container-Managed Persistence Bean-Managed Persistence


Client calls business method of Remote Object (Wrapper)
Container calls ejbActivate()
Bean performs pre-activation initialization
Container loads state from DB
Container sets instance fields
Container calls ejbLoad()
Bean performs pre-load initialization Bean loads state from DB
Remote Object calls business method of Bean
Bean performs business logic
Bean returns value to Remote Object
Remote Object returns value to client
Comments and alternative answers

Passivate calls ejbStore!


Author: Geraldo Xexeo (http://www.jguru.com/guru/viewbio.jsp?EID=524001), Jan
14, 2002
It is very annoying that to passivate an object for an BMP there is a call to ejbStore
before the call to ejbPassivate. So, a naive ejbStore will make extra updates
completely unnecessary in the database, as I see.

Re: Passivate calls ejbStore!


Author: Neo Gigs (http://www.jguru.com/guru/viewbio.jsp?EID=748386), Apr 26,
2002
Hi there,

Let say i need to run a stored procedure calls inside a EJB (regardless CMP or
BMP), should I just create a method call that fired the stored procedure or which
area of the lifecycle?

Here i provide my EJBean code, please help me to verify:

import java.io.Serializable;
import java.ejb.*;
import java.sql.*;
import java.naming.*;
import java.util.*;
import weblogic.db.jdbc.*;
import NTConn.ConnSetup;
import db.UpdMainLedgIE;

public class UpdMainLedgIEBean implements EntityBean {

// Initializes object references


ConnSetup TestSetupConn;
Connection conn;
String url = "jdbc:oracle:thin@10.97.2.50:1521:REL4";
UpdMainLedgIE local_UpdMainLedgIE;

// Initializes variables
private EntityContext ctx;
private int iMainLedgPrin;
private int iMainLedgInt;
private int iMainLedgLPI;
private int iMainLedgOC1;
private int iMainLedgOC2;
private int iMainLedgUappAmt;
private int iMainLedgIISInt;
private int iMainLedgIISLP1;
private int iMainLedgIntClw;
private int iMainLedgLPIClw;
private int iTotUnchrgPrin;
private int iPrpdUduePrin;
private String iLastUpdUsrId;
private String iLastUpdBrchCd;

public void setSessionContext(SessionContext ctx)


{
log("setSessionContext called");
this.ctx = ctx;
}

public void unsertEntityContext()


{
log("unsetSessionContext called");
this.ctx = null;
}

public void ejbActivate()


{
log("ejbActivate called: " + id());
}

public void ejbPassivate()


{
log("ejbPassivate called: " + id());
}

// Updates data
public void ejbStore()
{
log("ejbStore called: " + id());
}

// Return records from db


public void ejbLoad()
{
log("ejbLoad called: " + id());
}

// Insert new records


public void ejbCreate()
{
log("ejbCreate called: " + id());
}

// Prepare to run create method


public void ejbPostCreate()
{
log("ejbPostCreate called: " + id());
}

// For records remove purposes


public void ejbRemove()
{
log("ejbRemove called: " + id());
}
// For logging purposes
public void log(String s)
{
System.out.println(s);
}

// Return a string with the bean id


private String id()
{
return "PK = " + (String) ctx.getPrimaryKey();
}

private void cleanup(Connection con)


{
try {
if (con != null) con.close();
} catch (Exception e) {
log("Error closing connection: " + e);
throw new EJBException(e);
}
}

public void UpdateLedger(int r_iMainLedgPrin, r_int


iMainLedgInt,
int r_iMainLedgLPI, int
r_iMainLedgOC1, int r_iMainLedgOC2,
int r_iMainLedgUappAmt, int
r_iMainLedgIISInt, int r_iMainLedgIISLP1,
int r_iMainLedgIntClw, int
r_iMainLedgLPIClw, int r_iTotUnchrgPrin,
int r_iPrpdUduePrin, String
iLastUpdUsrId, String iLastUpdBrchCd)
{
this.iMainLedgPrin = r_iMainLedgPrin;
this.iMainLedgInt = r_int iMainLedgInt;
this.iMainLedgLPI = r_iMainLedgLPI;
this.iMainLedgOC1 = r_iMainLedgOC1;
this.iMainLedgOC2 = r_iMainLedgOC2;
this.iMainLedgUappAmt = r_iMainLedgUappAmt;
this.iMainLedgIISInt = r_iMainLedgIISInt;
this.iMainLedgIISLP1 = r_iMainLedgIISLP1;
this.iMainLedgIntClw = r_iMainLedgIntClw;
this.iMainLedgLPIClw = r_iMainLedgLPIClw;
this.iTotUnchrgPrin = r_iTotUnchrgPrin;
this.iPrpdUduePrin = r_iPrpdUduePrin;
this.iLastUpdUsrId = iLastUpdUsrId;
this.iLastUpdBrchCd = iLastUpdBrchCd;

log("UpdateLedger called: " + id());

try {
TestSetupConn = new ConnSetup;
conn = TestSetupConn.MBSConn();
local_UpdMainLedgIE = new
UpdMainLedgIE(iMainLedgPrin, iMainLedgInt,
iMainLedgLPI, iMainLedgOC1,
iMainLedgOC2,
iMainLedgUappAmt, iMainLedgIISInt,
iMainLedgIISLP1,
iMainLedgIntClw, iMainLedgLPIClw,
iTotUnchrgPrin,
iPrpdUduePrin, iLastUpdUsrId,
iLastUpdBrchCd, conn);
} catch (SQLException sqle) {
log("One update transaction failed: " +
id());
throw new EJBException(ejbE)
} finally {
cleanup(conn);
}
}
}

Thanks

Neo

Exception in ejbPostCreate and rollback.


Author: Ken Loh (http://www.jguru.com/guru/viewbio.jsp?EID=46975), Apr 7, 2005
It would be very helpful if there is an explanation on what would happen if there is an
exception in ejbPostCreate. If the bean has a relationship with another bean, what
would happen if the associated bean could not be created ? Would there be a
rollback ?

What's the difference between EJBHome, EJB Home, EJB Object, EJBObject
and EJB (not to mention Home Interface and Remote Interface)?
Location: http://www.jguru.com/faq/view.jsp?EID=51578
Created: May 18, 2000 Modified: 2000-05-18 20:36:36.409
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

The EJB spec is all about really bad naming decisions.

First, an Enterprise JavaBean is not a JavaBean (but you already knew that).

The "Home Interface" is actually a Factory Object. It is responsible for locating or


creating instances of the desired bean, and returning remote references.

When you write the source code for the EJB Home Interface, you must extend the
interface EJBHome, and provide method signatures for all the desired create()
and find() methods. An object that implements the Home Interface is automatically
generated by the EJB Server tools.

The "EJB Object", or Remote Object, is actually a Wrapper. It sits somewhere inside
the container, between the client and your code. It is responsible for performing all
the setup and shutdown tasks (like opening transactions, or restoring data state)
immediately before and after your enterprise bean is called.
The "EJB Object" is generated by the EJB Server tools -- you don't have to write any
part of it. However, you do have to write another interface, called the "Remote
Interface" or the "EJBObject Interface," that extends interface
EJBObject, and provides method signatures for all the business methods. The
server automatically generates a Java class that implements the Remote Interface; it
is this object that is registered with RMI, and a reference to it is returned by the
Home Interface (which we now know is actually a Factory Object).

The "EJB," or Enterprise Bean, ironically, is not the EJB Object (even though it is an
EJB and it is an object). It doesn't even implement the EJBObject interface, nor
does it implement the Remote Interface. Instead, it implements either the
EntityBean interface or the SessionBean interface. It also must implement all the
methods defined in the Remote Interface -- but it doesn't actually implement the
interface (in the Java sense). This is unfortunate, since we cannot rely on the Java
compiler to make sure we've implemented all the right methods. It must also
implement one ejbCreate() method for each create() method in the Home Interface
(as well as ejbFind()/find()).

See what I mean about poorly chosen names? :-)

Comments and alternative answers

Home is a interface where you provide all your business...


Author: harikishan charagundla
(http://www.jguru.com/guru/viewbio.jsp?EID=92970), Jul 3, 2000
Home is a interface where you provide all your business methods you want to provide
to the client. Remote is the Interface where all Create Methods and
FindbyPrimaryKey's and remove methods will be declared.

EJB Bean the class, which implements these methods, when the user calls the
methods in the remote Interface the corresponding methods will be called. The calling
of the methods is taken care by the container which is residing in the EJB Server.

Note: Even though you do not extend any of the interface which we have created
previously we have to implement the methods of the interface, yes it looks amazing
but it is EJB specification.

Re: Home is a interface where you provide all your business...


Author: JavaP P (http://www.jguru.com/guru/viewbio.jsp?EID=850304), Feb 12,
2005
HI HariKishan,
Update the message. It might leads to a confusion for new EJB programmer.

Thanks in advance.

Sorry to say Hari that u have got the home and remote...
Author: kishore_k_v k (http://www.jguru.com/guru/viewbio.jsp?EID=202022), Sep
10, 2000
Sorry to say Hari that u have got the home and remote mixed up.I for one rely on
online help a lot to get more info.Please change it before someone new to ejb goes. Of
Course I'm sure it was just another typographical error.

Can the security context be passed between a web container (servlets/jsp)


and an EJB container ? When the servlet calls an EJB I want its identity to
be that of the original web client authenticated with a certificate.
Location: http://www.jguru.com/faq/view.jsp?EID=53955
Created: May 22, 2000 Modified: 2000-08-13 16:38:04.872
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by Daniel Weimer
(http://www.jguru.com/guru/viewbio.jsp?EID=25540

The whole issue of propagation of authentication context from client to the EJB
server is still evolving - both in terms of the specification as well as vendor offerings.
According to the current Java 2 specification (page 224):
"the container is the authentication boundary between callers and components
hosted by the caller. For inbound calls it is the container's responsibility to make an
authentic representation of the caller identity available to the component".
The JAAS 1.0 specification extends the types of principals and credentials that can be
associated with the client but it is also evolving.

Thus given the container implementation that is required to drive this whole thing,
the answer depends on your app vendor - some like Weblogic (WLE), Websphere
provide security plug-ins/SDKs that can enable the propagation. Other vendors are
close behind. Check your vendor plug-in.

Comments and alternative answers

Some vendors, like Pramati, provide a facility where...


Author: Asit Padhi (http://www.jguru.com/guru/viewbio.jsp?EID=61648), Jul 18,
2000
Some vendors, like Pramati, provide a facility where the security credentials of the
web client are first authenticated by the web container and when the Servlet calls the
EJB components the same security context is passed on to the EJB container.

Re: Some vendors, like Pramati, provide a facility where...


Author: Nilesh Shah (http://www.jguru.com/guru/viewbio.jsp?EID=1810), Sep
19, 2002
Is this still true?. We are want to use Resin servlet engine at web layer and
weblogic 7.0 at EJB layer.

Can we pass security context from resin to weblogic?. Can JAAS help use
here?.

If we use weblogic at both layer that it passes the context.


Why is EJB better than Microsoft COM/DCOM/MTS/DNA ?
Location: http://www.jguru.com/faq/view.jsp?EID=56727
Created: May 25, 2000 Modified: 2000-05-26 16:55:46.965
Author: Sharanya Vemu (http://www.jguru.com/guru/viewbio.jsp?EID=56479)
Question originally posed by Varsha Shetty
(http://www.jguru.com/guru/viewbio.jsp?EID=50958

The two primary architectures for distributed


computing
are CORBA and Sun`s Enterprise JavaBeansTM.

Some would argue that Microsoft`s Component


Object
Model and Distributed COM are additional
candidates,
but Greenfeld disagrees. "DCOM may eventually
become a server technology of importance," he
says,
"but right now, it`s a desktop technology
cobbled
together to have the appearance of a server
story to tell.
Few, if any, large-scale implementations of
DCOM exist
or even aspire to enterprise-scale, mission-
critical
operations at this point."

Most developers interviewed for this story


are taking a
wait-and-see attitude toward DCOM, while
almost
all have piloted or ran an implementation of
CORBA or Enterprise JavaBeans.

InformationWeek, December 13, 1999

"...a polarization in the market for server-


side
components, with Microsoft on one side and
EJB-focused vendors and users on the other.
While the
co-existence and interoperability message
still holds,
IDC believes that EJB is well on the way to
becoming a de facto standard for
heterogeneous,
multiplatform environments"

IDC, "Programmer Development Tools


Synopsis:
1999 Worldwide Markets and Trends", April
1999
"Enterprise JavaBeans is definitely a
strategic
direction for us" says Lisa Villareal, a
Schwab vice
president. "It's given us the ability to
launch new
products and new channels very
quickly"...DCOM,
however, has one big weakness -- it only runs
on
Microsoft's Windows NT, which remains far less
reliable than other corporate operating
systems such as
Unix. Schwab, for instance, worried that it
couldn't
use DCOM for larger transactions and didn't
even
consider it as a way of developing new
applications"

Wall Street Journal, July 1999

Programmers using the Java and CORBA (common


object request broker architecture)
programming
models outnumber those targeting Microsoft's
COM
programming model by nearly a 2-to-1 margin:
44
percent to 24 percent.

Forrester Research, Inc., July 1999

Microsoft is scheduled to release Windows


2000, with
its EJB alternative, COM+ (Component Object
Model), by year's end. Analysts say EJB is
ahead of
COM+ in adoption in the enterprise.

PCWeek, July 25, 1999

"So tallying up my numbers, EJB wins 8 to 1.


It's a bit
one-sided, isn't it? But as I said, MTS was a
really nice
prototype for EJB"

Anne Thomas, Patricia Seybold Group;


"Comparing MTS and EJB"; Distributed
Computing, December 1998

Comments and alternative answers


The above is cribbed from ENTERPRISE JAVABEANSTM T...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 31,
2000
The above is cribbed from ENTERPRISE JAVABEANSTM TECHNOLOGY VS.
COM+/MTS at Sun's EJB site . See also Sun's J2EE FAQ, Blueprints, and the various
white papers at Sun's J2EE site and Sun's EJB site.

Also, MTS does not support Object Persistence


Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040), Sep
17, 2000
Also, MTS does not support Object Persistence

Being Java, EJB has the freedom of being platform ...


Author: ravi kishore (http://www.jguru.com/guru/viewbio.jsp?EID=310013), Jan 23,
2001
Being Java, EJB has the freedom of being platform independent unlike MS
DCOM/COM/MTS

Is there a EJB Server available for Win98?


Location: http://www.jguru.com/faq/view.jsp?EID=57292
Created: May 26, 2000 Modified: 2000-05-26 16:59:48.406
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Suresh Kuyilath
(http://www.jguru.com/guru/viewbio.jsp?EID=52013

I installed Weblogic (4.5.1 and 5.1.0) in my computer with Win98 and it works
perfectly (the only changes with respect to NT are that it doesn't use the Native
interface for I/O connections and uses the standard socket implementation)...

The only recommendation is that you must have a "powerful" machine with at least
128MB of RAM (better 192MB for 5.1.0) and a 400MHz processor (or above)...

Anyway take a look at http://java.sun.com/products/ejb/tools1.html where Sun lists


all the container and developement tool avaiable...

Comments and alternative answers

The J2EE reference implementation from Sun works on...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 26,
2000
The J2EE reference implementation from Sun works on Windows 95 and Windows
98 as well as Windows NT. Download it from the Sun J2EE Product Page. You may
have to edit the various .bat scripts to change the end-of-line character to be DOS-
compatible.

You can also use JRun 3.0 from www.allaire.com. It...


Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040), Sep
17, 2000
You can also use JRun 3.0 from www.allaire.com. It works on variety of platforms
including the Win 98 that you have asked for..

Is there a difference between container managed and bean managed


persistence in terms of performance?
Location: http://www.jguru.com/faq/view.jsp?EID=58125
Created: May 29, 2000 Modified: 2000-07-31 05:08:26.189
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by olivier rachon
(http://www.jguru.com/guru/viewbio.jsp?EID=44117

[Short answer: with bean-managed persistence, you can optimize your queries and
improve performance over the generalized container-managed heuristics. But
container-managed persistence is very convenient, and vendors will be working to
improve its performance as time goes on. -Alex]

There is of course a difference as many CMPs use O-R mapping using metadata,
which is slower than hardcoded queries (except vendors like GemStone that use a
OODB which is slow anyway!) As always, a lot depends on the database schema.
Given that CMP is still evolving, complex relationships (e.g.inheritance) and
distributed transactions are not even supported by most EJB server vendors, leave
alone performance.

Having said that however, it does not seem right to compare BMP and CMP on
performance because the motivation of CMP is precisely to relieve bean providers
from thinking about this! In (J2EE) theory, a good CMP implementation should
perform well in a production environment; in practice, except for a couple of vendors
who have traditionally been strong in persistent storage space (e.g. Persistence
Software, GemStone) you will not find great CMP support at this very moment.

BMP offers a tactical approach while CMP is more strategic. Which implies that if you
can work-around some (perhaps severe) limitations for near-term, there may be
much to gain with CMP as the vendor offering matures.

Given that RMI-IIOP does not support distributed garbage collection (unlike
RMI-JRMP), do I need to do something explicitly to GC beans, or is it
magically handled by the EJB framework?
Location: http://www.jguru.com/faq/view.jsp?EID=60460
Created: May 31, 2000 Modified: 2000-05-31 10:21:02.894
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Alex McManus
(http://www.jguru.com/guru/viewbio.jsp?EID=45888

(The lack of distributed GC was noted in the article "EJBs from a critical
perspective".)

It is the Containers' responsibility to handle distributed garbage collection. This is


how EJB's were designed.
Looking at Stateful Session Beans (SFSB) or Entity Beans. When you write a SFSB,
you must implement ejbActivate() and ejbPassivate(). Implementing these methods,
mean that the container can passivate your bean, hence take it out of memory and
store its state on disk or in a datastore somewhere.

Whilst this article does take a hit at EJB, I believe that it is misleading in some sense
and is outdated. Most of the pot shots that it takes about EJB products not
supporting latest standards etc. are now obsolete as vendors such as Inprise, BEA,
GemStone etc. have updated there products, it's a shame that he didn't get to
review the beta products...

The article also mentions the importance of "Dynamic Glue" which is not using
statically generated stubs and skeletons. This is in fact possible with RMI-IIOP using
DII (Dynamic Invoacation Interface), but he fails mention how this technology is
used in building systems and why it is important. He says that it is why CORBA has
failed, which is wrong. EJB is a logical extension of and most Containers are built on
top of CORBA.

He also mentions the overheads of intra-vm calls. This is something that most
products provide optimizations for and something he clearly hasn't researched as this
is a feature that CORBA ORB's have supported for quite a while.

OK, so EJB doesn't support user-created threads. So how do I perform tasks


asynchronously?
Location: http://www.jguru.com/faq/view.jsp?EID=60468
Created: May 31, 2000 Modified: 2000-05-31 10:22:32.115
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Venkateswaran Muthuswamy
(http://www.jguru.com/guru/viewbio.jsp?EID=47714

If your EJB does not need to know about the results of the aynch calls, then you can
use JMS to send an asynch. message to another part of the system.

Another alternative is to place the multithreaded code inside a CORBA or RMI server
and call this from your EJB. Always keep site of the big picture, RMI and CORBA are
part of J2EE and can be used as part of a 'J2EE' solution.

There are some things that these technologies can do that EJB at this present time
cannot.

Comments and alternative answers

You can perform tasks asynchronously in two different...


Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479),
Jun 14, 2000
You can perform tasks asynchronously in two different ways. 1. Using client-side
threads - less complex. Kick off separate threads for each EJB access. At a later time
join the threads on the client-side. 2. Using JMS - more complex. Define EJB
methods with an additional parameter to indicate whether it is a asynchronous call or
not. If called asynchronously, the EJB method would post a JMS message to a queue
and return immediately without doing any work. The JMS queue monitor would pick
up the message and call the EJB by setting the asynchronous parameter to false. The
EJB executes the method and returns the results. The queue monitor posts the results
to an output queue being monitored by the client. Both JavaPro and Java Report had
published articles on this topic recently.

How should I set the CLASSPATH to develop EJBs?


Location: http://www.jguru.com/faq/view.jsp?EID=60466
Created: May 31, 2000 Modified: 2000-06-09 03:06:23.66
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Rajshekhar Bashetti
(http://www.jguru.com/guru/viewbio.jsp?EID=54152

This depends on the J2EE Application Server that you are using, but for all of them
you will at least require all of the J2EE classes, which are downloadable as part of the
J2EE Reference Implementation.

Basically, take the JAR file from your implmentation and add it to your CLASSPATH.
The easiest way is to just copy the file to the jre\lib\ext directory under your JDK
directory.

Comments and alternative answers

Can you give me the exact classpath to compile EJB...


Author: Anil Vupputuri (http://www.jguru.com/guru/viewbio.jsp?EID=61459), Jun 2,
2000
Can you give me the exact classpath to compile EJB files? Thanking you. Anil.

if you are using weblogic server you can set the e...
Author: ravindra ch (http://www.jguru.com/guru/viewbio.jsp?EID=63594), Jun 3,
2000
if you are using weblogic server you can set the environmental variables by calling
the "setenv" command at the command prompt.

First of all, to "develop EJBs", you want...


Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), Jun
13, 2000
First of all, to "develop EJBs", you want to be able to do the following:

1. compile your *.java files into *.class files


2. create your serialized deployment descriptor
3. run the ejb compiler on your serialized deployment descriptor file
4. create a JAR file (including a Manifest file you've created)
5. (recommended) check the JAR file for ejb compliance

Now, to do the compiling etc. you at least want your CLASSPATH to include the path
to the Java compiler (javac), the path to the JAR utility, and the path to the EJB
compiler (should come with your EJB server - weblogic.ejbc for Weblogic).

Of course you don't even have to set your CLASSPATH if you want to do each step at
a command line - you will just have to give the full path to the compiler(s).

need help in istalling java2 in windows XP


Author: regy john (http://www.jguru.com/guru/viewbio.jsp?EID=536181), Nov 1,
2001
I installed it, for some reason my command prompt does not accept the commands for
java2 such as javac. Thank you

My session beans call other bean methods within a transaction. Using bean-
managed transactions, how should I take care of commit and rollback ?
Location: http://www.jguru.com/faq/view.jsp?EID=62121
Created: Jun 2, 2000 Modified: 2000-09-12 15:55:36.874
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by Shalabh Nigam
(http://www.jguru.com/guru/viewbio.jsp?EID=47481

There are two steps here:

1. Coding step:

public class exBean implements SessionBean {


EJBContext ec;
javax.transaction.UserTransaction utxn;
.
.
.
utxn = ec.getUserTransaction();
utxn.begin();

// do all your txn stuff


// getting DB connections, updates, other bean methods, etc.
.
.
utxn.commit();
}

Note you have to begin a txn before opening dB connections and close connections
before committing.

2. Deployment step:

- Your app server must support a JTS for distributed txns. Most do.

- Verify there is no conflict with the bean transaction properties in calling beans.

Comments and alternative answers


Are there any issues if each of my bean methods uses...
Author: Shalabh Nigam (http://www.jguru.com/guru/viewbio.jsp?EID=47481), Jul 3,
2000
Are there any issues if each of my bean methods uses a different DB Connection?

What code changes do we need to make to upgrade our EJBs developed in


Weblogic 4.5 to work under Weblogic 5.1?
Location: http://www.jguru.com/faq/view.jsp?EID=65536
Created: Jun 9, 2000 Modified: 2000-06-09 20:43:12.272
Author: sachin mahishi (http://www.jguru.com/guru/viewbio.jsp?EID=4437)
Question originally posed by Ramasubramani Subramani
(http://www.jguru.com/guru/viewbio.jsp?EID=50068

BEA describes the differences at


http://www.weblogic.com/docs51/classdocs/API_ejb/EJB_whatsnew.html#1024497
[See also http://www.jguru.com/jguru/faq/view.jsp?EID=319.]

Is it possible to use Microsoft Access as the database while implementing


entity beans? (Weblogic refuses to use the JDBC-ODBC bridge, since it
needs a thin driver.)
Location: http://www.jguru.com/faq/view.jsp?EID=70556
Created: Jun 10, 2000 Modified: 2000-06-16 08:15:11.171
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by Nilesh Bhattad
(http://www.jguru.com/guru/viewbio.jsp?EID=62514

You are right about the JDBC-ODBC bridge. Since it does not support multi-threading
it is not of much use. But you can find 3rd-party drivers in the market that will allow
you to work with MS Access from EJBs.

For a list of those drivers search for MS Access drivers from the following page:

http://industry.java.sun.com/products/jdbc/drivers.

What is an EJB Context?


Location: http://www.jguru.com/faq/view.jsp?EID=64760
Created: Jun 13, 2000 Modified: 2000-06-13 08:22:48.343
Author: sairam kudapa (http://www.jguru.com/guru/viewbio.jsp?EID=64721)
Question originally posed by Anuradha Chavan
(http://www.jguru.com/guru/viewbio.jsp?EID=55611

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.

How do you use the JNDI ENC to access JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=75066
Created: Jun 14, 2000 Modified: 2000-06-14 07:30:41.03
Author: Steven Lau (http://www.jguru.com/guru/viewbio.jsp?EID=72026) Question
originally posed by Se Hee Lee
(http://www.jguru.com/guru/viewbio.jsp?EID=21287

First of all, you have to create a javax.mail.Session like you would in accessing other
resources such as JDBC connections:

InitialContext ctx = new InitialContext();


Session session =
(Session) ctx.lookup("java:comp/env/TheMailSession");
After that, everything else is the same:

Message msg = new MimeMessage(session);


...
...
Depending on the application server you're using, you'll have different ways in
setting up the ENC.

Can I deploy a new EJB without restarting my server? (I'm using Weblogic.)

Location: http://www.jguru.com/faq/view.jsp?EID=75637
Created: Jun 14, 2000 Modified: 2000-06-14 15:51:26.555
Author: Suja Rao (http://www.jguru.com/guru/viewbio.jsp?EID=62310) Question
originally posed by Dakshinamurthy Ramachandran
(http://www.jguru.com/guru/viewbio.jsp?EID=57231

Sure. WebLogic Server4.5 includes "hot deploy" feature that allow you to deploy,
redeploy or undeploy EJBs while the Server is running, from the Weblogic Console.
Deployment of EJBs made through the console are however lost when you restart the
WebLogic Server.
Comments and alternative answers

http://www.weblogic.com/docs45/techdeploy/hotdeplo...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 21, 2000
http://www.weblogic.com/docs45/techdeploy/hotdeploy.html#deploy

See: http://www.weblogic.com/docs45/techdeploy/hot...
Author: Keith Schwartz (http://www.jguru.com/guru/viewbio.jsp?EID=27189), Jun
21, 2000
See:

http://www.weblogic.com/docs45/techdeploy/hotdeploy.html

if you're using weblogic 4.5 or:

http://www.weblogic.com/docs51/techdeploy/hotdeploy.html
if you're using weblogic 5.1.

How do I get a list of records (like from a database query) in EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=74357
Created: Jun 17, 2000 Modified: 2000-06-17 16:37:01.419
Author: sachin mahishi (http://www.jguru.com/guru/viewbio.jsp?EID=4437)
Question originally posed by es goh
(http://www.jguru.com/guru/viewbio.jsp?EID=59126

[Basically, you have to cheat. Make a custom data class that is not an EJB. Create a
Vector or List containing objects of this type, one per EJB; fill the data objects with
the same values as are in the EJBs. Then you can return this List, and it will be
serialized through RMI, and magically reconsituted on the client side. -Alex]

In your bean:

public get Vector getCustomerData()


{
//Connect to DB

//get result set

Vector vector = new Vector();

//iterate and build CustomerData object and add to vector

return vector;
}
In your bean's remote interface:
public Vector getCustomerData()
throws RemoteException;
In both client and server:
public class CustomerData implements java.io.Serializable
{
private long id;
private String name;

public CustomerData(long id, String name)


{
this.id = id;
this.name = name;
}

public long getId() {


return id;
}

public String getName() {


return name;
}
}
In client (for ejb 1.0 lookups....)
Context ctx = getInitialContext();
//get initial context for lookup
CustomerHome CustHome = (CustomerHome)ctx.lookup("Customer");
Customer customer = CustHome.create();
Vector v=customer.getCustomerData();
// iterate through v
Comments and alternative answers

An Alternative to this could be using a method in the...


Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040), Sep
17, 2000
An Alternative to this could be using a method in the bean (e.g. ejbFindAllRecords).
This method will return the Collection Primary Keys. Such a method in Bean will
have a corresponsing findAllRecords in the home interface, that returns the collection
of Remote Interfaces.

On the client side, one needs to call the findAllRecords method from the home
interface. Then iterate over the Collection returned that contains refernce to rhe
Remote interface. You can get the Primary keys from the individual items in the
Collections. One can pass this Primary key to a Session bean to get the list of all the
records.

Is this way OK. I have not tried this myself, but I am sure this can work...

[I'm confused: are you talking about returning a list of primary keys, or a list of
remote references? -Alex]

In weblogic...
Author: samson su (http://www.jguru.com/guru/viewbio.jsp?EID=232778), Apr 7,
2001
I don't know how this works in other environment... but in weblogic, when you
declare the return type of findXXX() as "Enumeration", the deployer tool will auto
generate an implementation that returns a couple of records. For example:
public interface IBookHome extends EJBHome {
public IBook findByPrimaryKey(CBookPK key)
throws RemoteException, FinderException;
public Enumeration findByAuthor(String name)
throws RemoteException, FinderException;
}

...

in your client code:

for (Enumeration en = home.findByAuthor("John"); en.hasMoreElements()


;) {
book = (IBook) en.nextElement();
System.out.println("Name: " + book.get_name());

......
}

JDBC 2 alternatives
Author: ian pojman (http://www.jguru.com/guru/viewbio.jsp?EID=383696), Apr 20,
2001
Now that JDBC 2 is out, why create a CustomerData class? You can just use a
connectionless ResultSet (RowSet or CachedResultSet). This way you can access
your SQL data just as if you had just gotten the ResultSet from a hard-coded SQL
query!

Re: JDBC 2 alternatives


Author: Anders Ericsson (http://www.jguru.com/guru/viewbio.jsp?EID=414347),
May 3, 2001
The advantage of a CustomerData class over a connection less ResultSet is that
the the CustomerData class descripes itself at development time. You could check
types with the compiler. A Vector of CustomerData is also less complex. But using
a connectionless ResultSet a have other advantage.

How to setup access control in an EJB such that different application clients
have different rights to invoke different methods in one EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=74503
Created: Jun 17, 2000 Modified: 2000-08-24 18:58:32.114
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by Wai MOK
(http://www.jguru.com/guru/viewbio.jsp?EID=51540

To set up EJB access control you should do the following:

1) Set up the different users/groups and the methods each can have access to in
your deployment descriptor. Note: You don't have to specify different methods for
each user, you could also just specify different users to your entire bean - for
example if you only wanted another component of your application talking to your
bean.

2) Inside your client code, whenever you make your connection to the EJB server (to
look up the bean) you need to specify the user and password, in order to set the
Identity of the client:

...
Properties p = new Properties();
..
p.put(Context.SECURITY_PRINCIPAL, "user");
p.put(Context.SECURITY_CREDENTIALS, "password");
...

3) Inside your bean, you can do "extra" security checks (if you used 'Role'-based
security): (Assuming you have a 'manager' role defined in your deployment
descriptor and a user assigned to this role)
public int getAccountBalance(accountId) {
if (ejbContext.isCallerInRole("manager"))
return balance;
}
You could also enforce security to your EJB server. Using Weblogic, you could add the
following to your weblogic.properties file:
...
weblogic.password.user=password
...
where "user" is the username you grant access for and "password" (after '=') is the
password for this username.

Much more detailed information on this topic can be found by reading the SUN
specification of EJB at: http://www.java.sun.com/products/ejb/docs.html

Where can I find ejb-jar.xml file templates?


Location: http://www.jguru.com/faq/view.jsp?EID=77549
Created: Jun 17, 2000 Modified: 2000-06-17 16:40:19.925
Author: Luis F. Canals Samaniego
(http://www.jguru.com/guru/viewbio.jsp?EID=66172) Question originally posed by
Ming-fang Wang (http://www.jguru.com/guru/viewbio.jsp?EID=67927

There are examples of ejb-jar.xml files in Enterprise JavaBeans Specificiation v1.1.


You can download it from http://java.sun.com/products/ejb/docs.html

What's new in the EJB 2.0 specification?


Location: http://www.jguru.com/faq/view.jsp?EID=80572
Created: Jun 20, 2000 Modified: 2000-06-20 11:43:25.782
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

Read this article by Richard Monson-Haefel and find out!


Comments and alternative answers

Following are the main features supported in EJB 2.0 *...


Author: Mad Man (http://www.jguru.com/guru/viewbio.jsp?EID=311964), Feb 14,
2001
Following are the main features supported in EJB 2.0 * Integration of EJB with JMS
* Message Driven Beans * Implement additional Business methods in Home interface
which are not specific for bean instance. * EJB QL.

How is persistence implemented in enterprise beans?


Location: http://www.jguru.com/faq/view.jsp?EID=79536
Created: Jun 20, 2000 Modified: 2000-06-20 11:50:49.968
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by Dallas Dreyer
(http://www.jguru.com/guru/viewbio.jsp?EID=58484

Persistence in EJB is taken care of in two ways, depending on how you implement
your beans: container managed persistence (CMP) or bean managed persistence
(BMP).
For CMP, the EJB container which your beans run under takes care of the persistence
of the fields you have declared to be persisted with the database - this declaration is
in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon
as the method you have executed is finished, the new data is persisted to the
database by the container.

For BMP, the EJB bean developer is responsible for defining the persistence routines
in the proper places in the bean, for instance, the ejbCreate(), ejbStore(),
ejbRemove() methods would be developed by the bean developer to make calls to
the database. The container is responsible, in BMP, to call the appropriate method on
the bean. So, if the bean is being looked up, when the create() method is called on
the Home interface, then the container is responsible for calling the ejbCreate()
method in the bean, which should have functionality inside for going to the database
and looking up the data.

See the following FAQs, and the appropriate topics (listed on the main EJB FAQ
page):

• What is a CMP bean?


• What is a BMP bean?
• When does the container call my bean's ejbCreate / ejbPostCreate / ejbStore
/ ejbPassivate / ejbActivate / ejbLoad / ejbPassivate method?

Can the primary key in the entity bean be a Java primitive type such as int?
Location: http://www.jguru.com/faq/view.jsp?EID=81676
Created: Jun 20, 2000 Modified: 2000-08-15 06:31:10.893
Author: Keith Schwartz (http://www.jguru.com/guru/viewbio.jsp?EID=27189)
Question originally posed by Steven Lau
(http://www.jguru.com/guru/viewbio.jsp?EID=72026

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).
Comments and alternative answers

A primary key is a class which provides a pointer into...


Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), Jun
21, 2000
A primary key is a class which provides a pointer into the database. It is used to
obtain a remote reference to some entity bean. The only requirement for the primary
key class is that it implements the java.io.Serializable interface. The value fields
inside the primary key class can be of the Java primitive type, such as int, long, etc.,
as well as the type String. An example primary key class is below:

import java.io.Serializable;

public class UnknownPK implements Serializable {


public int id;
public String name = "";
public UnknownPK() {}

public UnknonwPK(int id) {


this.id = id;
}

public UnknownPK(int id, String name) {


this.id = id;
this.name = name;
}

public boolean equals(Object obj) {


if (obj == null || !(ojb instanceof UnknownPK))
return false;
else if ((((UnknownPK)obj).id == id) &&
(((UnknownPK)obj).name.equals(name))
return true;
else
return false;
}

public int hashCode() {


return id + name.hashCode();
}

public String toString() {


return String.valueOf(id) + name;
}
}

In the EJB 1.1 specification, primary keys have been...


Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), Jul 6,
2000
In the EJB 1.1 specification, primary keys have been defined as either simple or
compound keys. Simple keys use a single field in the underlying datastore as a
primary key, while compound keys use multiple fields. For simple primary keys, you
don't need to wrap the field in a primary key class. This type of simple key is defined
in the ejb-jar.xml deployment descriptor file:

<entity>
...
<prim-key-class>java.lang.String</prim-key-class>
...
<primkey-field>userName</primkey-field>
...
For primary keys which map to primitive types, like int, the specification requires a
primary key wrapper class. You can define these primay key types as compound
primary keys. Note: Compound primary keys are used for multiple primary key fields
as well as single primary key fields of primitive types. With compound primary keys,
the EJB bean developer still has to define the primary key class. Compound primary
keys are defined in the ejb-jar.xml file as follows:

<entity>
...
<prim-key-class>com.mypath.MyBeanPK</prim-key-class>
...

Are EJBs the best solution to make a component which have to manage a
hardware device (modem, fax...) and provide access to them?
Location: http://www.jguru.com/faq/view.jsp?EID=81868
Created: Jun 21, 2000 Modified: 2000-06-21 11:14:30.996
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Luis F. Canals Samaniego
(http://www.jguru.com/guru/viewbio.jsp?EID=66172

I would suggest not, because these devices would probably be served best by
Singleton Objects which could control the access to the device, and EJB does not
support Singletons (in a standard way).

A suggestion is to delegate the call from an EJB to another Object, possibily an RMI
or CORBA object or even an a Java object implementing the Singleton pattern,
possibly using JNI to use OS-dependent device access libraries.

Comments and alternative answers

What is meant by a "Java Object"? Doesn't...


Author: Benjamin McCartney
(http://www.jguru.com/guru/viewbio.jsp?EID=109357), Aug 16, 2000
What is meant by a "Java Object"? Doesn't this need to be located outside the
container? If so, what other objects beside RMI and CORBA are supported?

How do I map a Date/Time field to an Oracle database with CMP?


Location: http://www.jguru.com/faq/view.jsp?EID=82581
Created: Jun 21, 2000 Modified: 2000-06-21 11:15:54.741
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by Nilesh Bhattad
(http://www.jguru.com/guru/viewbio.jsp?EID=62514

[Question continues: (I have written a wrapper class with the help of


java.util.GregorianCalendar but it doesn't store time in Oracle database, whereas it
stores Date without any problem.)]
Use the java.sql.Timestamp field to store your Date/Time in your entity bean, and
then declare the corresponding field as 'Date' type in the Oracle database and it will
work fine. You will have the "date" value and the "time" value preserved.

Comments and alternative answers

DATE field in Oracle


Author: Chetan Desai (http://www.jguru.com/guru/viewbio.jsp?EID=497154), Sep
14, 2001
Just a note that the DATE field in Oracle has a precision of only upto 1 second. So if
you are working in milliseconds arena = beaware, precision will be lost !!!

Re: DATE field in Oracle


Author: V Shah (http://www.jguru.com/guru/viewbio.jsp?EID=226807), Dec 7,
2001
How would you compare two dates then ? I'm interested only in comparing "date"
portion, not "Time" one. When I create two date objects at the same time and then
store 'em in Oracle database, retrieve 'em back and compare , my comparision
always false. What could be going wrong here ?

Re[2]: DATE field in Oracle


Author: Chetan Desai (http://www.jguru.com/guru/viewbio.jsp?EID=497154),
Dec 8, 2001
How are you creating your two date objects? using the clone() method ?

What criteria are you using to compare the date objects ?

-Chetan.

What is the difference between a Server, a Container, and a Connector?


Location: http://www.jguru.com/faq/view.jsp?EID=82650
Created: Jun 21, 2000 Modified: 2000-06-21 12:34:13.769
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

To keep things (very) simple:

An EJB server is an application, usually a product such as BEA WebLogic, that


provides (or should provide) for concurrent client connections and manages system
resources such as threads, processes, memory, database connections, network
connections, etc.

An EJB container runs inside (or within) an EJB server, and provides deployed EJB
beans with transaction and security management, etc. The EJB container insulates an
EJB bean from the specifics of an underlying EJB server by providing a simple,
standard API between the EJB bean and its container.
(Note: The EJB 1.1 specification makes it clear that it does not architect the interface
between the EJB container and EJB server, which it says it left up to the vendor on
how to split the implementation of the required functionality between the two. Thus
there is no clear distinction between server and container.)

A Connector provides the ability for any Enterprise Information System (EIS) to plug
into any EJB server which supports the Connector architecture. See
http://java.sun.com/j2ee/connector/ for more indepth information on Connectors.

Does the J2EE reference implementation support the JMS?


Location: http://www.jguru.com/faq/view.jsp?EID=82204
Created: Jun 21, 2000 Modified: 2000-07-11 22:37:14.122
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Richard Landon
(http://www.jguru.com/guru/viewbio.jsp?EID=57892

The current release of J2EE (1.2.1) support EJB 1.1 specification so it doesn't
implements JMS over EJB.

This kind of EJB appears only in the EJB 2.0 specifications (available at
http://java.sun.com/products/ejb/docs.html).

At this time only BEA and Silverstream support this specification. Probably in the
future more Vendors will follow this new specification, so wait...

Comments and alternative answers

The current release of J2EE reference implementation...


Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479),
Jun 22, 2000
The current release of J2EE reference implementation supports the JMS API only and
does not come with a reference implementation of JMS. Thus, you can write EJB and
non-EJB components to run in the J2EE reference implementation which access a
3rd-party JMS server using the JMS API.

Orion supports JMS now, as well.


Author: Joseph Ottinger (http://www.jguru.com/guru/viewbio.jsp?EID=37791), Jul 6,
2000
Orion supports JMS now, as well.

JRun 3.0 also has started supporting the JMS featu...


Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040), Sep
17, 2000
JRun 3.0 also has started supporting the JMS feature.

My client's connection times out when trying to retrieve a huge number of


records (1000+) from an EJB server that uses CMP to a database. How can I
resolve this?
Location: http://www.jguru.com/faq/view.jsp?EID=83822
Created: Jun 25, 2000 Modified: 2000-08-24 18:57:16.711
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by Siva Busa
(http://www.jguru.com/guru/viewbio.jsp?EID=60533

You need to make some adjustments to your EJB bean through the deployment
descriptor. Modify the 'maxBeansInFreePool', 'maxBeansInCache' and
'idleTimeoutSeconds' fields until you get the results desired. The more you increase
the value of 'maxBeansInFreePool' and 'maxBeansInCache', the less you should have
to adjust the 'idleTimeoutSeconds' field.
Comments and alternative answers

But if I increase these two numbers -- i.e. if I i...


Author: Sanjeev Dhupkar (http://www.jguru.com/guru/viewbio.jsp?EID=8389), Jul 6,
2000
But if I increase these two numbers -- i.e. if I increase the value of the
maxBeansInFreePool and maxBeansInCache --won't it hamper the performance of the
application server i.e. wont the load on the application server be high?

Yes, the load will be heavier on the server as it now...


Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), Jul
30, 2000
Yes, the load will be heavier on the server as it now has to manager additional
references in the pool. However, everything is a tradeoff. Suppose, for example, if
you are currently running maxBeansInCache=100 and maxBeansInFreePool=250,
isn't this placing more load on the EJB server/container than if you used 50 and 150
respectively for these fields? You have to consider what is relevant to your
application. On the other hand, depending on your server, you might not even notice
the difference. For example, if your EJB server is executing SQL queries with your
database and looking up 10,000 accounts in 0.043 seconds, is it much of a
performance issue to have this value increase to say 0.32 seconds?

Re: Yes, the load will be heavier on the server as it now...


Author: manish jain (http://www.jguru.com/guru/viewbio.jsp?EID=525616), Oct
20, 2001
hiya.. Instead of doing all this changes in properties of app server. we can make
small modification in the CMP bean itself. Try to use findInRange method this
will fetch limited no of records from the database so ur application wont get
blocked/timedout. i hope this will help u. regards manish jain

Re[2]: Yes, the load will be heavier on the server as it now...


Author: RAJEESHA np
(http://www.jguru.com/guru/viewbio.jsp?EID=1036504), Dec 11, 2002
Wht is this findInRange method?Can i use it in ejb2.0 entity bean?

What is "clustering" in EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=97603
Created: Jul 6, 2000 Modified: 2000-07-06 12:16:02.049
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by surendrakumar ganta
(http://www.jguru.com/guru/viewbio.jsp?EID=88738

Clustering refers to the ability of multiple load-balanced web servers to share session
and entity data. It is a major feature of web application servers. Standardized
support for clustering was one of the primary motivations behind the EJB spec.

Clustering also applies to Servlet containers sharing HttpSession data (similar to EJB
Session Beans).

For more information, see the following questions on the Servlet FAQ:

• What servlet engines support clustering -- that is, sharing of session data
across multiple load-balanced web servers?

Comments and alternative answers

what is clustering in EJB


Author: K Sunitha (http://www.jguru.com/guru/viewbio.jsp?EID=464102), Jul 29,
2001
I thought clustering was only available in Weblogic, is it part of the ejb
specification...?

Re: what is clustering in EJB


Author: Gaurav Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=66767),
Oct 31, 2001
No clustering is not specified in EJB specifications. It is a value added feature
which most of the application server vendors provide. Different vendors may
implement clustering in different ways.

What is "hot deployment" in WebLogic?


Location: http://www.jguru.com/faq/view.jsp?EID=97622
Created: Jul 6, 2000 Modified: 2000-07-06 12:37:25.632
Author: Keith Schwartz (http://www.jguru.com/guru/viewbio.jsp?EID=27189)
Question originally posed by rajasekhar pokuri
(http://www.jguru.com/guru/viewbio.jsp?EID=81912

"Hot Deployment" in weblogic is the act of deploying, re-depolying, and un-deploying


EJBs while the server is still running (you don't have to shutdown the server to
deploy an EJB).

see:
http://www.weblogic.com/docs51/classdocs/API_ejb/EJB_deployover.html#1054622

Comments and alternative answers

Also, the beans that are "Hot Deployed" are...


Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040), Sep
17, 2000
Also, the beans that are "Hot Deployed" are not retained when the server is restarted.
To retain the bean, it's entry has to be made in the weblogic.properties file.

Regards
Anoop Sehdev

What is meant by the term "business logic"?


Location: http://www.jguru.com/faq/view.jsp?EID=97696
Created: Jul 6, 2000 Modified: 2000-07-06 13:17:00.956
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Ramkumar Krishnamurthy
(http://www.jguru.com/guru/viewbio.jsp?EID=89709

"Business logic" is just a fancy way of saying "code." :-)

More precisely, in a three-tier architecture, business logic is any code that is not
specifically related to storing and retrieving data (that's "data storage code"), or to
formatting data for display to the user (that's "presentation logic"). It makes sense,
for many reasons, to store this business logic in separate objects; the middle tier
comprises these objects. However, the divisions between the three layers are often
blurry, and business logic is more of an ideal than a reality in most programs. The
main point of the term is, you want somewhere to store the logic and "business
rules" (another buzzword) of your application, while keeping the division between
tiers clear and clean.

What are the deprecated EJB 1.0 conventions with respect to EJB 1.1?
Location: http://www.jguru.com/faq/view.jsp?EID=97827
Created: Jul 6, 2000 Modified: 2000-07-09 06:32:26.732
Author: sachin mahishi (http://www.jguru.com/guru/viewbio.jsp?EID=4437)
Question originally posed by Angus Mezick
(http://www.jguru.com/guru/viewbio.jsp?EID=81798

This are the list of changes which can be found in Chapter 1 of EJB 1.1 specification
It is as follows:-

EJB 1.1 attempts to provide a high degree of application compatibility for enterprise
beans that were written for the EJB 1.0 specification. Principally, the deployment
descriptor of EJB 1.0 based enterprise beans must be converted to the EJB 1.1 XML
format. However, the EJB 1.0 enterprise bean code does not have to be changed or
re-compiled to run in an EJB 1.1 Container, except in the following situations:

• The bean uses the javax.jts.UserTransaction interface. The package name of


the javax.jts interface has changed to javax.transaction, and there have been
minor changes to the exceptions thrown by the methods of this interface. An
enterprise bean that uses the javax.jts.UserTransaction interface needs to be
modified to use the new name javax.transaction.UserTransaction.
• The bean uses the getCallerIdentity() or isCallerInRole(Identity iden-tity)
methods of the javax.ejb.EJBContext interface. These method were depre-
cated in EJB 1.1 because the class java.security.Identity is deprecated in Java
2 platform. While a Container Provider may choose to provide a backward
compatible imple-mentation of these two methods, the Container Provider is
not required to do so. An enterprise bean written to the EJB 1.0 specification
needs to be modified to use the new methods to work in all EJB 1.1.
Containers.
• The bean is an entity bean with container-managed persistence. The required
return value of ejbCreate(...) is different in EJB 1.1 than in EJB 1.0. An
enterprise bean with con-tainer- managed persistence written to the EJB 1.0
specification needs to be recompiled to work with all EJB 1.1 compliant
Containers.
• The bean is an entity bean whose finders do not define the FinderException in
the meth-ods’ throws clauses. EJB 1.1 requires that all finders define the
FinderException.
• The bean is an entity bean that uses the UserTransaction interface. In EJB
1.1, an entity bean must not use the UserTransaction interface.
• The bean uses the UserTransaction interface and implements the
SessionSynchro-nization interface at the same time. This is disallowed in EJB
1.1.
• The bean violates any of the additional semantic restrictions defined in EJB
1.1 but which were not defined in EJB 1.0.

Are there any good hands-on EJB programming tutorials for WebLogic?
Location: http://www.jguru.com/faq/view.jsp?EID=97780
Created: Jul 6, 2000 Modified: 2000-10-06 22:44:31.497
Author: santosh chakrapani (http://www.jguru.com/guru/viewbio.jsp?EID=97772)
Question originally posed by zhuogang li
(http://www.jguru.com/guru/viewbio.jsp?EID=88190

You can find very cool hands-on tutorial on EJB on WebLogic at


http://www.weblogic.com/docs51. Here you can also find extensive documentation
on how weblogic supports the complete J2EE family.

Can I specify specific WHERE clauses for a find method in a CMP Entity
Bean?
Location: http://www.jguru.com/faq/view.jsp?EID=97806
Created: Jul 6, 2000 Modified: 2000-07-07 06:57:18.246
Author: sachin mahishi (http://www.jguru.com/guru/viewbio.jsp?EID=4437)
Question originally posed by Vijay Anand
(http://www.jguru.com/guru/viewbio.jsp?EID=91574

The EJB query language is totally vendor specific in EJB1.1. It is being standardized
in 1.2.

Yes, you can specify the where clause for a find method. This is the example for
EJB's deployed on weblogic:

findBigAccounts(double balanceGreaterThan): "(> balance


$balanceGreaterThan)"
where balance maps to some field in the table.
Comments and alternative answers
Where should this line appear?
Author: samson su (http://www.jguru.com/guru/viewbio.jsp?EID=232778), Apr 7,
2001
Would you tell me in detail where this line should appear? I always think WLQL is
too powerless... I spent several hours to find a way to do a case-insensitive "LIKE"
operation but finally give up (I can convert @0 to uppercase with @0.toUpperCase(),
but no way to wrap the SQL field name with SQL UPPER() function). The document
is very short and there are even errors in it. Is there any way in weblogic ejb tool to
specify customized standard SQL statement? It's more flexible. Thanks

Yes, in EJB 2.0


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 12, 2001
EJB 2.0 standardizes EJB-QL, which looks remarkably like SQL, for use inside the
DD for CMP entity beans. That way you can have finder methods in the home
interface that get the SQL automatically generated based on the content of the EJB-
QL.

Can an EJB handle (RMI remote reference) be stored in an HttpSession?


Location: http://www.jguru.com/faq/view.jsp?EID=97963
Created: Jul 7, 2000 Modified: 2000-07-09 06:39:45.243
Author: David Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=17915) Question
originally posed by David Garcia
(http://www.jguru.com/guru/viewbio.jsp?EID=17915

[Note: My HttpSessions are persistent (disk swap), so if the handle is not serializable
I will have troubles when the HttpSession is restored. ]

Test result:
I have used the handle for locating local and remote EJB. I have no problem about
storing the handle inside the HttpSession and swapping the HttpSession. However if
some problem arise about the swap of the HttpSession, you may could keep the
HttpSession in memory.

Test conditions:
BEA Weblogic 4.5.1 (uses EJB 1.0 and allow keep HttpSessions in memory). Windows
NT 4.0

Observations:
I'm a little surprised about the test since I keep in mind that handles could only be
used for locating local EJB's not remote ones (wrong?).

Comments and alternative answers

You can refer to the url below for more info and a...
Author: kishore_k_v k (http://www.jguru.com/guru/viewbio.jsp?EID=202022), Sep
11, 2000
You can refer to the url below for more info and a clear picture on this topic although
i think you know the answers.
http://www.weblogic.com/docs51/classdocs/API_ejb/EJB_design.html#1022000

What is the initial context factory for sun's EJB reference implementation,
and how is the initial context url specified? I always see the code fragment
"InitialContext ctx = new InitialContext();" but where are the initial
properties specified for this to work?
Location: http://www.jguru.com/faq/view.jsp?EID=98374
Created: Jul 7, 2000 Modified: 2000-07-09 06:27:55.491
Author: K J (http://www.jguru.com/guru/viewbio.jsp?EID=98373) Question originally
posed by Juan Rodriguez (http://www.jguru.com/guru/viewbio.jsp?EID=18476

When you are getting an initial context from outside of the EJB Container, you must
specify the properties for the initial context. These properties include the
InitialContextFactory class, the url of the server, and possibly authentication
parameters. These properties can either by created programatically using a
java.util.Properties object, or can be loaded at runtime from the jndi.properties file in
the classpath.

If you are using Sun's J2EE reference implementation in developing and deploying
EJBs, you are most likely including the J2EE.jar file in your classpath, which is
located in %J2EE_HOME%\lib\. If you look inside of this jar file, you will notice that
in the root of the jar file there is a jndi.properties file. This file sets up the initial
context properties for the Sun J2EE reference implementation. This is why you can
just make a call such as:

Context ctx = new InitialContext();

without setting up the initial context properties, when using the Sun reference
platform. If you use any other J2EE Application server, you will be required to set up
those properties.

Comments and alternative answers

It'd be nice to have an example of how to set the ...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 9, 2000
It'd be nice to have an example of how to set the properties from the command line...
(hint hint)

How can I write EJBs that will run (unmodified) in any EJB-Container? What
do I have to pay attention to?
Location: http://www.jguru.com/faq/view.jsp?EID=99739
Created: Jul 10, 2000 Modified: 2000-07-11 14:57:21.311
Author: Archana Karnik (http://www.jguru.com/guru/viewbio.jsp?EID=68139)
Question originally posed by Aladin Sindbad
(http://www.jguru.com/guru/viewbio.jsp?EID=83931
EJB containers are provided by App servers like Weblogic, Websphere etc. EJB
specification does not assure any interoperability between different App servers , in
turn between containers generated by app servers.

When writing EJBs, do not use any vendor specific packages. Stick to javax packages
(as per EJB spects). If you observe this rule, your EJB s should run on any App
server.

Also, check EJB 2.0 spects. They define minimum interoperability standards between
app servers using RMI - IIOP. But I did not find whether it's mandatory for the
vendors or not. I am waiting for the final EJB 2.0 spec to be released.

Comments and alternative answers

I'm not sure why the answer to this question dwells...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Jul 14, 2000
I'm not sure why the answer to this question dwells on interoperability, as my reading
of the question is purely portability. At any rate: other things to be carefull of for
portability:

1. With CMP entity beans, be careful of how you map SQL types to Java types:
WebLogic, at least, is pretty touchy here.
2. If you're lucky enough to be using a container whose CMP can handle
dependant ('value') objects, don't use that feature - it's not at all portable in
EJB 1.1 (2.0 is much better, but much different)
3. As the above points imply, BMP might tend to be much more portable. Make
sure that you do datasource lookups by the spec, though, and you might want
to think about making the datasource JNDI name (the whole shot:
"java:/comp/env/jdbc/DataSourceName") an environment entry (I've run into
bugs where containers weren't putting datasources in the spec-ordained
"java:/comp/env/jdbc" namespace
4. Make sure you use the ejb-reference deployment descriptor stuff, don't use a
client-style lookup from an EJB
5. Stick with the spec, even if you're using a server that allows more fredom.
Don't use threads, don't read the filesystem directly, etc. (Some containers will
let you get away with some of these)

I've got some CMP beans that will run in Weblogic and IAS, getting there was a bit of
an adventure.

Re: I'm not sure why the answer to this question dwells...
Author: Arun Balaji (http://www.jguru.com/guru/viewbio.jsp?EID=119257), Aug
10, 2001
Just to add to Dan's post - you should also consider issues like concurrency which
is not laid out in EJB 1.1. While containers like Weblogic5.1 use pessimistic
concurrency, others like Websphere use optimistic. You may have to plug in
versioning in your code to do staleness checks.

How can a EJB talk to legacy applications written in ILE/RPG without using
the IBM java toolbox?
Location: http://www.jguru.com/faq/view.jsp?EID=100504
Created: Jul 12, 2000 Modified: 2000-07-18 01:44:01.291
Author: Zack Li (http://www.jguru.com/guru/viewbio.jsp?EID=100500) Question
originally posed by Revathy Subramani
(http://www.jguru.com/guru/viewbio.jsp?EID=89892

The short answer would be waiting for the Connectors. See


http://java.sun.com/j2ee/connector for details.
Comments and alternative answers

I think EJB2.0 spec has a concept of Connector which...


Author: Asit Padhi (http://www.jguru.com/guru/viewbio.jsp?EID=61648), Jul 18,
2000
I think EJB2.0 spec has a concept of Connector which allows EJB's to interface with
Legacy Systems

Re: I think EJB2.0 spec has a concept of Connector which...


Author: Abhay Kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=469627),
Aug 6, 2001
With J2EE Connector architecture one can write EJB that can interface with
Legacy system, but on the other side it is the requirment that * the Legacy system
must provide a J2EE Connector compliant Resource Adater * that is plugabble in
EJB component.

If there is a method in an Entity EJB that does not modify the bean's data
(read only), can I specify that load() and store() methods should not be
called before and after the call to this method?
Location: http://www.jguru.com/faq/view.jsp?EID=101301
Created: Jul 13, 2000 Modified: 2000-07-18 03:24:40.017
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by Corneanu Dan
(http://www.jguru.com/guru/viewbio.jsp?EID=41082

The EJB 1.1 specification does not define any such business method contracts that
you can use as read-only methods (methods which do not call ejbLoad() and
ejbStore()).

Application servers like WebSphere provide you with an ability to specify beans as
read-only. When flagged as read-only in the bean deployment descriptor, WebSphere
optmizes the database access and the use of transaction control mechanisms.

Comments and alternative answers


the load and store method is only called if the de...
Author: Asit Padhi (http://www.jguru.com/guru/viewbio.jsp?EID=61648), Jul 18,
2000
the load and store method is only called if the declarative transaction attribute is
attched with it.Thats where the container reads the transaction attributes from the
deployment descripter and calls the call back method ejbload and ejbstore .Because
EJB 1.1 spec only talks about declarative transaction attributes for Entity beans
methods ,for read only method declare "Not supported" while defining the transaction
attributes for this read only method.Then ejbLoad and ejbStore method will not be
called by the container

Unfortunately the answer is no - the state machine...


Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210), Jul
18, 2000
Unfortunately the answer is no - the state machine for the callback methods is not
user configurable.

However, some vendors make some extensions/optimizations. For example, in


Weblogic provides a isModified method for CMP that is called before a store. If the
method returns TRUE then ejbStore will be called. The bean provider assumes
responsibility for data integrity in this situation. If unspecified (by bean provider) then
the Weblogic container will always do ejbStore.

In Weblogic there's an option that might help


Author: samson su (http://www.jguru.com/guru/viewbio.jsp?EID=232778), Apr 7,
2001
In weblogic's ejb deployer tool, goto "optimization" page, clear "update at the end of
each transaction" (not exactly... but very clear). Thus, when your entity bean is
mapped to a readonly stuff (such as a VIEW), there should be no "view not
updatable" exception when you perform readonly operations such as findByPK... (if
you leave this option checked, this exception would occur even if you were
performing readonly operations, because container will always try to ejbStore() after
any transaction, including a simple SELECT)

How do I decide between Enterprise Java Beans (EJB), Remote Method


Invocations (RMI), and CORBA?
Location: http://www.jguru.com/faq/view.jsp?EID=101761
Created: Jul 13, 2000 Modified: 2002-10-09 12:20:24.965
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by Srikanth Rao
(http://www.jguru.com/guru/viewbio.jsp?EID=80613

The following article desribes RMI, EJB and compares them.

Deciding whether to use RMI, CORBA or Enterprise JavaBeans


[Alex: the article isn't available at all, but it can still be found here. Big thanks to
Peter Alzheimer]

Comments and alternative answers

The article is not there


Author: Roger White (http://www.jguru.com/guru/viewbio.jsp?EID=726964), Jan 19,
2002
the link to the article is dead Can you point to another source?

Link is not working.


Author: Muhammad Ahmed Khan
(http://www.jguru.com/guru/viewbio.jsp?EID=903210), Jun 4, 2002
The link is dead for this question. Accessed on June 05, 2002. 02:41 am

Re: Link is not working.


Author: Peter Alzheimer (http://www.jguru.com/guru/viewbio.jsp?EID=1009379), Oct 8, 2002
http://web.archive.org/web/20010817004120/www.csd.uu.se/~d96cgr/CarRentalServlet/ejb/RMIvsEJ

Which, if any, of the automatically generated stub & skeleton class files
does one need to include in a JAR file to be used when creating stand-alone
clients? (I would like to create a client-side jar file which contains only the
class files actually needed by the client.)
Location: http://www.jguru.com/faq/view.jsp?EID=105016
Created: Jul 18, 2000 Modified: 2000-08-11 12:14:09.972
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by keith hawkins
(http://www.jguru.com/guru/viewbio.jsp?EID=83055

The answer is really not that generic as one may like to believe! Basically what a
client needs to invoke the services of an EJB layer are:

• locate the home interface (using a JNDI SPI) & invoke methods of the bean
instances (over IIOP). Depending on the vendor (e.g. IONA builds JNDI over
CORBA) the actual files will vary. You have to check with your vendor.
• definitions of serializable objects that are returned to client due to network
considerations (instead of object references).

[Can someone please provide examples, for a specific EJB server if need be?]

See also:

• What classes does a client application need to access EJB? (hmm, kind of
redundant, oops :-)

Comments and alternative answers

Dear friend For RMI clients (standalone) all you ...


Author: sharad chaudhary (http://www.jguru.com/guru/viewbio.jsp?EID=62937), Jul
24, 2000
Dear friend

For RMI clients (standalone) all you require is to copy your stub (generated using
rmic) and the remote interface (wherein you define the remotely invokable methods)
to your client directory, or jar it along with the client implementation of your
program. Thus you require 3 things only.. 1)stub 2)remote Interface 3)client
implementation Hope this solves your problem.. Sharad

Please show me an example of an Entity Bean that accesses more than one
database table, using BMP.
Location: http://www.jguru.com/faq/view.jsp?EID=105215
Created: Jul 18, 2000 Modified: 2000-08-09 20:09:15.717
Author: Asit Padhi (http://www.jguru.com/guru/viewbio.jsp?EID=61648) Question
originally posed by Mohan Raj (http://www.jguru.com/guru/viewbio.jsp?EID=66168

here is the total code of an entity bean that uses multiple table using BMP

package com.orillion.india.nds.ejb.entity;

/*Enterprise Bean instance can throw javax.ejb.EJBException


or
* java.lang.RuntimeException to its container to report
that the invoked
* business method or callback method could not be completed
because of an
* unexpected error (e.g. the instance failed to open a
database connection).
*/
import java.rmi.RemoteException;
import javax.ejb.*;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.naming.*;

public class CableEntityBean implements


javax.ejb.EntityBean {

public java.lang.Integer cableId;


public java.lang.String cabName;
public java.lang.String cabType;
public java.lang.String cabLongName;
public java.lang.Integer vendorId;
public java.lang.String partNum;
public java.lang.String actualState;
public java.sql.Date
actualStateDate;
public java.lang.String actualSubState;
public java.util.Vector conCat = new
Vector();
private EntityContext entityContext =
null;
private Connection con = null;
private String dbName =
"java:comp/env/jdbc/NidDB3.0";

//Place your business methods here.

public Integer getCableId(){


return cableId;
}
public java.lang.String getCabName(){
return cabName;
}
public java.lang.String getCabType(){
return cabType;
}
public java.lang.String getCabLongName(){
return cabLongName;
}
public java.lang.Integer getVendorId(){
return vendorId;
}
public java.lang.String getPartNum(){
return partNum;
}
public java.lang.String getActualState(){
return actualState;
}
public java.sql.Date getActualStateDate(){
return actualStateDate;
}
public java.lang.String getActualSubState(){
return actualSubState;
}
public java.util.Vector getConCat() {
return conCat;
}
public void setAllValues(String cabName,String
cabType,String cabLongName,
Integer vendorId,String partNum,String
actualState,
java.sql.Date actualStateDate,String
actualSubState,Vector Concatenation){
this.cabName = cabName;
this.cabType = cabType;
this.cabLongName = cabLongName;
this.vendorId = vendorId;
this.partNum = partNum;
this.actualState = actualState;
this.actualStateDate = actualStateDate;
this.actualSubState = actualSubState;
if(Concatenation !=null){
this.conCat =Concatenation;
}

public java.lang.Integer ejbCreate(java.lang.String


cabName, java.lang.String cabType,
java.lang.String cabLongName, java.lang.Integer
vendorId, java.lang.String partNum,
java.lang.String actualState, java.sql.Date
actualStateDate,
java.lang.String actualSubState,Vector
conCatenation)
throws javax.ejb.CreateException
{
this.cableId = getCableIdFromDB();
this.cabName = cabName;
this.cabType = cabType;
this.cabLongName = cabLongName;
this.vendorId = vendorId;
this.partNum = partNum;
this.actualState = actualState;
this.actualStateDate = actualStateDate;
this.actualSubState = actualSubState;

try {

makeConnection();

insertRow(cableId, cabName, cabType, cabLongName,


vendorId, partNum, actualState,
actualStateDate,
actualSubState);
if(conCatenation != null) {
this.conCat =conCatenation;
insertIntoConcatenation(cableId,conCatenation);
}
//System.out.println("able to ceate record"
+this.cableId + this.cabType );
} catch (Exception ex) {
throw new EJBException("ejbCreate: " +
ex.getMessage());
}
finally {

closeConnection();
}

return cableId ;
}

public void ejbPostCreate(java.lang.String cabName,


java.lang.String cabType,
java.lang.String cabLongName, java.lang.Integer
vendorId, java.lang.String partNum,
java.lang.String actualState, java.sql.Date
actualStateDate,
java.lang.String actualSubState, Vector
conCatenation)
throws javax.ejb.CreateException
{
}

//FindByPK method
public Integer ejbFindByPrimaryKey(Integer
primaryKey)
throws javax.ejb.FinderException
{

try {

makeConnection();
if (selectByPrimaryKey(primaryKey)) {
return primaryKey;
}
else {
throw new ObjectNotFoundException
("Row for id " + primaryKey + " not found.");
}
} catch (Exception ex) {
throw new EJBException("ejbFindByPrimaryKey: " +
ex.getMessage());
}
finally {
closeConnection();
}

//Implementing EntityBeanInterface methods.....


public void setEntityContext(EntityContext
entityContext)
throws javax.ejb.EJBException,
java.rmi.RemoteException
{
this.entityContext = entityContext;

public void unsetEntityContext()


throws javax.ejb.EJBException,
java.rmi.RemoteException
{
this.entityContext = null;

//Remove Methods....
public void ejbRemove()
throws java.rmi.RemoteException,
javax.ejb.EJBException, javax.ejb.RemoveException
{
try {
makeConnection();

deleteRow(cableId);
} catch (Exception ex) {
throw new EJBException("ejbRemove: " +
ex.getMessage());
}
finally {
closeConnection();
}
}

public void ejbActivate()


throws javax.ejb.EJBException,
java.rmi.RemoteException
{
cableId =
(Integer)entityContext.getPrimaryKey();
}

public void ejbPassivate()


throws javax.ejb.EJBException,
java.rmi.RemoteException
{
closeConnection();
cableId =null;
}

public void ejbLoad()


throws javax.ejb.EJBException,
java.rmi.RemoteException
{
try {
makeConnection();
loadRow();
} catch (Exception ex) {
throw new EJBException("ejbLoad: " +
ex.getMessage());
}
finally {
closeConnection();
}
}

public void ejbStore()


throws javax.ejb.EJBException,
java.rmi.RemoteException
{
try {
makeConnection();
storeRow();
} catch (Exception ex) {
throw new EJBException("ejbStore: " +
ex.getMessage());
}
finally {
closeConnection();
}
}
//-----end of implementation-----------
//Serialization of BeanObject is to be done
here.....//
private void writeObject(java.io.ObjectOutputStream
out)
throws java.io.IOException
{
//write non-serializable attributes here...

out.defaultWriteObject();
}

private void readObject(java.io.ObjectInputStream in)


throws java.io.IOException,
ClassNotFoundException
{
//read non-serializable attributes here ...

in.defaultReadObject();
}
// serialization done ///

/*********************** Database Routines


*************************/

private void makeConnection() throws NamingException,


SQLException {

InitialContext ic = new InitialContext();


DataSource ds = (DataSource) ic.lookup(dbName);
con = ds.getConnection();
}

private void closeConnection() {


try {
con.close();
}catch(Exception e) {
//e.printStackTrace();
}
}

private void insertRow (Integer cableId, String cabName,


String cabType, String cabLongName,
Integer vendorId,String partNum,
String actualState, java.sql.Date
actualStateDate,
String actualSubState) throws SQLException {
String insertStatement =
"insert into cable values ( ? , ? , ? ,
?, ?, ?, ?, ?, ? )";
PreparedStatement prepStmt =
con.prepareStatement(insertStatement);

prepStmt.setInt(1, cableId.intValue());
prepStmt.setString(2, cabName);
prepStmt.setString(3,cabType);
if(cabLongName !=null)
prepStmt.setString(4, cabLongName);
else
prepStmt.setNull(4,Types.VARCHAR);
prepStmt.setInt(5, vendorId.intValue());
if(partNum !=null)
prepStmt.setString(6, partNum);
else
prepStmt.setNull(6,Types.VARCHAR);
prepStmt.setString(7, actualState);
prepStmt.setDate(8, actualStateDate);
prepStmt.setString(9, actualSubState);

prepStmt.executeUpdate();
//System.out.println("created the record" +
cableId);
prepStmt.close();
}
private void insertRowIntoConcat(int cabid, int
cabConcatenate,
int position) throws SQLException {

String insertStatement =
"insert into cableconcatenation values ( ?
, ? , ? )";
PreparedStatement prepStmt =
con.prepareStatement(insertStatement);

prepStmt.setInt(1, cabid);
prepStmt.setInt(2,cabConcatenate);
prepStmt.setInt(3, position);

prepStmt.executeUpdate();
prepStmt.close();

}
private void deleteRow(Integer cableId) throws
SQLException {
String deleteStatement =
"delete from cable where cableId = ? ";
PreparedStatement prepStmt =
con.prepareStatement(deleteStatement);

prepStmt.setInt(1, cableId.intValue());
prepStmt.executeUpdate();
prepStmt.close();
}

private void deleteRowFromConcat(Integer cabConId)


throws SQLException {

String deleteStatement =
"delete from cableconcatenation where
cabconcatenate = ? ";
PreparedStatement prepStmt =
con.prepareStatement(deleteStatement);

prepStmt.setInt(1, cabConId.intValue());
prepStmt.executeUpdate();
prepStmt.close();
}

private boolean selectByPrimaryKey(Integer primaryKey)


throws SQLException {

String selectStatement =
"select cableId " +
"from cable where cableId = ? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
prepStmt.setInt(1, primaryKey.intValue());

ResultSet rs = prepStmt.executeQuery();
boolean result = rs.next();
prepStmt.close();
return result;
}

private void loadRow() throws SQLException {

String selectStatement =
"select
cabName,cabType,cabLongName,vendorId,partNum,actualState,ac
tualStateDate,actualSubState " +
"from cable where cableId = ? ";

PreparedStatement prepStmt =
con.prepareStatement(selectStatement);

prepStmt.setInt(1,this.cableId.intValue());

ResultSet rs = prepStmt.executeQuery();
if (rs.next()) {
this.cabName = rs.getString(1);
this.cabType = rs.getString(2);
this.cabLongName = rs.getString(3);
this.vendorId = new Integer(rs.getInt(4));
this.partNum = rs.getString(5);
this.actualState = rs.getString(6);
this.actualStateDate = rs.getDate(7);
this.actualSubState = rs.getString(8);
prepStmt.close();
}

else {
prepStmt.close();
throw new NoSuchEntityException("Row for id " +
cableId +
" not found in database.");
}

String selectStatement1 =
"select cabId from CableConcatenation where
cabconcatenate = ? order by listposition ";
PreparedStatement prepStmt1 =
con.prepareStatement(selectStatement1);
prepStmt1.setInt(1,this.cableId.intValue());
ResultSet rs1 = prepStmt1.executeQuery();

while (rs1.next()) {
this.conCat.addElement(new Integer(rs1.getInt(1)));
}
if(!(conCat.size() > 0)) this.conCat =new Vector();

prepStmt1.close();

private void storeRow() throws SQLException {


String updateStatement =
"update cable set cabName = ? ,cabType = ?
,cabLongName = ?, " +
"vendorId = ? , partNum =?, actualState = ?,
actualStateDate=?, actualSubState=? " +
"where cableId= ?";
PreparedStatement prepStmt =
con.prepareStatement(updateStatement);

prepStmt.setString(1, cabName);
prepStmt.setString(2, cabType);
if(cabLongName !=null)
prepStmt.setString(3, cabLongName);
else
prepStmt.setNull(3,Types.VARCHAR);
prepStmt.setInt(4, vendorId.intValue());

if(partNum !=null)
prepStmt.setString(5, partNum);
else
prepStmt.setNull(5,Types.VARCHAR);

prepStmt.setString(6, actualState);
prepStmt.setDate(7, actualStateDate);
prepStmt.setString(8, actualSubState);
prepStmt.setInt(9, cableId.intValue());
int rowCount = 0;
try {
rowCount = prepStmt.executeUpdate();

if(conCat.size()> 0) {
deleteRowFromConcat(cableId);
insertIntoConcatenation(cableId,conCat);
}

} catch (SQLException e) {
//e.printStackTrace();
}
prepStmt.close();

if (rowCount == 0) {
throw new EJBException("Storing row for id " +
cableId + " failed.");
}
}
private void insertIntoConcatenation(Integer
cabid,Vector concatenation) throws SQLException {

for(int i=0; i < concatenation.size(); i++) {


Integer id =(Integer)
concatenation.elementAt(i);

insertRowIntoConcat(id.intValue(),cabid.intValue(),i+1);
}

public Integer getCableIdFromDB() {


int cableId =0;
String query = "select cable_seq.nextval from
dual";
try {
makeConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.next();
cableId = rs.getInt(1);
}catch(Exception ex){
//System.out.println(ex.getMessage());
}
finally {
closeConnection();
}
return (new Integer(cableId));

}
Comments and alternative answers

Any way to do that with CMP?


Author: Julien Martin (http://www.jguru.com/guru/viewbio.jsp?EID=1165737), Apr
24, 2004
Hello,
I have just read a post stating that one can't map several database tables to a single
cmp entity ejb. This post was quite old. Has anything changed with the advent of ejb
2.1?
Julien.

How can we work with LDAP using EJB's?


Location: http://www.jguru.com/faq/view.jsp?EID=110185
Created: Jul 24, 2000 Modified: 2000-07-24 22:00:50.636
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Guruprasad Pyati
(http://www.jguru.com/guru/viewbio.jsp?EID=101356

See the JNDI FAQ and the LDAP Topic for information on using LDAP from J2EE.
(There is nothing particularly special about using LDAP from EJB, as opposed to any
other use of LDAP from Java.)
Comments and alternative answers

I think there is more to your question than meets the...


Author: Jim Gish (http://www.jguru.com/guru/viewbio.jsp?EID=119497), Aug 4,
2000
I think there is more to your question than meets the eye. If you mean can entity beans
be persisted in an LDAP directory, the answer is "sort of". First of all, the obvious
part - you have to use bean-managed persistence since at present no vendors offer
container-managed persistence with LDAP. The harder question is one of
transactional requirements. Although LDAPs are typically built on transactional
systems, only statement level (implicit) transactions are available. If your entity beans
are read-only, this may not be a problem. However, if you have other applications
modifying your LDAP or your beans are not read-only, or they involve multiple hits
to the LDAP to do an update, then you have a problem. Getting LDAPs to participate
in a heterogeneous distributed transaction is currently not possible. However, given
all the hoopla about LDAP these days, the need is emerging rapidly.

Where can I find EJB components for retail, health care, and utility
solutions?
Location: http://www.jguru.com/faq/view.jsp?EID=111072
Created: Jul 25, 2000 Modified: 2000-07-27 06:41:34.894
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by sharon wahl
(http://www.jguru.com/guru/viewbio.jsp?EID=101124

A starting point would be the Solutions Marketplace section under


http://industry.java.sun.com/solutions/ . Another site is the http://www.mgm-
edv.de/ejbsig/ejbcomponents.html.

Sure this is just a start and will require some research on the promised component
packages. Since the rather tepid success of IBM's San Francisco, many have not
ventured into productizing reusable components especially for verticals you have
mentioned. Companies like BEA Systems (eBusiness Smart Components) and IBM
(San Francisco) provide some foundation components to get jumpstarted. Others
include TheortCenter (eBSC) and DigitalHarbor (Charisma) - unfortunately not for
the verticals you have listed.

When using a stateful session bean with an idle timeout set, how can the
bean receive notification from the container that it is being removed due to
timeout?
Location: http://www.jguru.com/faq/view.jsp?EID=111811
Created: Jul 26, 2000 Modified: 2000-08-13 15:59:56.613
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by K J
(http://www.jguru.com/guru/viewbio.jsp?EID=98373

[Question continues: ? (Through some tests, it looks like none of the standard EJB
callback methods are called when a stateful session bean is removed due to idle-
timeout.)]

According to the spec, ejbRemove need not (or must not) be called in this case.
ejbPassivate is simply the Wrong Thing to be called (the bean is transitioning to the
'does not exist' state, not the 'passive' state).

The EJB 1.1. spec says in section 6.6.3 Missed ejbRemove Calls:

The application using the session bean should provide some clean up mechanism to
periodically clean up the unreleased resources.

For example, if a shopping cart component is implemented as a session bean, and


the session bean stores the shopping cart content in a database, the application
should provide a program that runs periodically and removes “abandoned” shopping
carts from the database.

Probably not the answer you're looking for, especially if you allocate some other
resource (a Message Queue, for example) that you need to release. Although, if
you're using a resource, you really should be getting it when you need it (via JNDI)
and returning it back to the pool right away.

Can I use the afterBegin, beforeCompletion, and afterCompletion methods


in a BMP bean? (as these are the methods of the SessionSynchronization
interface)
Location: http://www.jguru.com/faq/view.jsp?EID=111818
Created: Jul 26, 2000 Modified: 2000-08-03 22:20:59.882
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by chamiraju raghavendra
(http://www.jguru.com/guru/viewbio.jsp?EID=30402

The spec says no. Really, (IMHO) these don't translate well to the life of an entity
bean for the following reasons:

• afterBegin might not mean much since the entity might join the transaction
long (computerwise) after the transaction is started.
• Anything an entity bean needs to do 'beforeCompletion' should be done in
ejbStore.
• An entity bean really can't do much 'afterCompletion' - by definition, the
entity's state is already wherever it needs to be (database, queue, legacy
system, etc.)

You might want to re-evaluate what you're actually trying to do: chances are you're
missing a key abstraction in your model.
Comments and alternative answers
Dan. Not Entity Bean but Session bean with BMP
Author: Seetesh H (http://www.jguru.com/guru/viewbio.jsp?EID=1038574), Dec 17,
2002
Hi Dan
The question out here refers to Session bean with BMP and not Entity bean.
As BMP has full control over transactions, can I use the SessionSynchronization
methods?
Seetesh

How can I access EJBs from JavaBeans Components?


Location: http://www.jguru.com/faq/view.jsp?EID=112404
Created: Jul 27, 2000 Modified: 2000-07-27 06:45:12.19
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Roman Lukomski
(http://www.jguru.com/guru/viewbio.jsp?EID=102185

In short, JavaBeans are not special; you access EJBs from JavaBeans the way you
would from any other EJB client.

However, JavaBeans can be useful as a 'wrapper' for EJBs that hide some of the
complexities of EJBs and allow their use from other Java programs. A visual
JavaBean, in particular, can be assembled in a GUI "bean builder" application, while
an EJB often cannot. However, adapting an EJB to become a JavaBean can be very
complicated and should not be undertaken lightly.

Perhaps another Guru can give feedback to this response with an example and/or
source code demonstrating this technique.

I have created a remote reference to an EJB in FirstServlet. Can I put the


reference in a servlet session and use that in SecondServlet?
Location: http://www.jguru.com/faq/view.jsp?EID=114024
Created: Jul 29, 2000 Modified: 2000-07-29 05:59:08.95
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Nagaraj shyagale
(http://www.jguru.com/guru/viewbio.jsp?EID=29160

Yes.

The EJB client (in this case your servlet) acquires a remote reference to an EJB from
the Home Interface; that reference is serializable and can be passed from servlet to
servlet.

If it is a session bean, then the EJB server will consider your web client's servlet
session to correspond to a single EJB session, which is usually (but not always) what
you want.

Using Websphere for a small EJB application deployment, why do I get the
message "The jar file you have created does not contain any beans.Please
select a jar file with beans in it".
Location: http://www.jguru.com/faq/view.jsp?EID=114476
Created: Jul 30, 2000 Modified: 2000-07-31 03:29:06.125
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by Yogesh Beri
(http://www.jguru.com/guru/viewbio.jsp?EID=99548

This isn't particularly due to the fact that you are using Websphere, although I won't
rule that out here based on what you have described. The way to check this would be
to try to deploy the same JAR file in Weblogic and see if you receive the same error
message.

More than likely, your problem is the fact that your manifest (serialized, in the JAR
file) is pointing to a bean, say, com.mycompany.mybean.BigBean and inside the JAR
file, the package structure for this bean does not match. In other words, you should
see the exact folder structure of the BigBean in the JAR file as in the manifest file.
So, your JAR file should display the file, BigBean, and then under the 'Path' section,
you should have com/mycompany/mybean/. So, if this is your problem, look at how
you are JARring up your files, the package structure in your classes and you might
need to modify your manifest file.

Comments and alternative answers

The jar file you have created may not have a Serialized...
Author: Munish Pandhi (http://www.jguru.com/guru/viewbio.jsp?EID=270315), Dec
12, 2000
The jar file you have created may not have a Serialized Deployment Descriptor file
contained within in it.

1. To prepare the jar file a file named manifest with no extension should be created in
the same package as that of Remote Interface , Home Interface , Bean Class ,Key
Class ( FinderHelper Interface ,FinderObject Class only in case of container managed
persistence entity bean) . The following two lines should be added in the manifest file
:
Name : package/serialized deployment descriptor name.ser Enterprise-
Bean: True
(Here .ser is the extension of serialized deployment descriptor file) The directory tree
of package should be separated by forward slashes(‘/’) . 2. The following command
should be used on command line to create the jar file(Java Archive)
C:\..\project>jar cmf package directory tree\manifest entitybean jar
file name.jar package directory tree\*.class package directory
tree\*.java package directory tree\*.ser
The project is the directory just above where directory tree of the package lies.

In the manifest defined is depicting the path of serialized deployment descriptor and
while using the JAR utility to create the jar file of entity bean we tell the JAR utility
to use our manifest information to create the jar file of entity bean.

If you don’t want to add .java files in the jar file then remove package directory\*.java
from above command.
What is the difference between a Component Transaction Monitor (CTM) and
an Application Server?
Location: http://www.jguru.com/faq/view.jsp?EID=114746
Created: Jul 30, 2000 Modified: 2000-08-03 22:20:06.412
Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602) Question
originally posed by Nagaraj shyagale
(http://www.jguru.com/guru/viewbio.jsp?EID=29160

A Component Transaction Monitor (CTM) is an application server that uses a server-


side component model. Since a CTM is a Transaction Processing monitor (TP), it is
expected to provide services for managing transactions, security, and concurrency. In
addition, CTMs also facilitate distributed object architectures and provide facilities for
object persistence. In short, a CTM is a specific type of application server.

[Can someone give feedback with examples of a CTM? Also, is this different from a
TP Monitor? -Alex]

Comments and alternative answers

BEA WebLogic Application Server is an example of a...


Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602), Jul 31,
2000

BEA WebLogic Application Server is an example of a CTM (as is any EJB


Application Server).

A CTM is essentially a TP monitor combined with a distributed component


architecture, such as EJB. A CTM provides a richer set of services than a TP monitor
since it also manages the components.

Example of a TP monitor is BEA TUXEDO, IBM CICS......


Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040), Sep
17, 2000
Example of a TP monitor is BEA TUXEDO, IBM CICS...

Example of CTM is MTS, and various other Application servers...

A CTM is a hybrid Technology between a TP monitor and the ORB.

Correct me if I am wrong. These are the words from the famous Enterprise JavaBeans
from O'Reilly.

Regards
Anoop Sehdev
How can I call one EJB from inside of another EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=114944
Created: Jul 31, 2000 Modified: 2000-07-31 05:01:34.042
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by biju mathew
(http://www.jguru.com/guru/viewbio.jsp?EID=90463

Just do it!

EJBs can be clients of other EJBs. It just works. Really. Use JNDI to locate the Home
Interface of the other bean, then acquire an instance reference, and so forth.

How good is the performance of EJB systems? Are there any benchmarks?
Location: http://www.jguru.com/faq/view.jsp?EID=115140
Created: Jul 31, 2000 Modified: 2000-07-31 05:27:47.907
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Lee Fuller
(http://www.jguru.com/guru/viewbio.jsp?EID=109421

EJB systems are designed to perform very poorly.

Very provocative, no? :-)

What I mean is this: EJBs allow you to make an application distributed and scalable.
This can have a huge positive impact on performance -- if your application really is
running in a cluster, on dozens of host machines simultaneously, with hundreds of
simultaneous clients. However, the performance of each individual machine will
usually be much slower than the same application running on a single app server.
This is because of the overhead introduced by the EJB server managing your
persistence and transactions for you.

However, like I said, this is by design. As a simple illustration of this, think about
session data. In a simple web server environment, the session data is stored in RAM,
and stays resident for the life of the client session. Access to this session data is very
fast. In a distributed, EJB server environment, the session data may get swapped to
disk between client requests, and the client may connect to a different host for the
second request. This requires more work to save and load the data for each request,
so performance must suffer. However, it also allows many more client sessions to be
active simultaneously, and to make use of the same (limited) amount of RAM per
machine, and to use many many many machines in your cluster.

EJB performance is a classic "hockey stick" curve: the performance suffers in the
short term (small number of hosts), then improves greatly in the long term (large
number of hosts). Another way to look at it is that it enables the "just throw money
at it" solution (i.e. more servers) to actually have a chance of success.

As for benchmarking: as far as I know, nobody has done any benchmarks comparing
different EJB servers, or comparing EJB with other similar technologies. And once
they do, everyone will find problems with it, as usual.
Flame on! Please feel free to object violently to any of the above assertions. That's
what the "feedback" function is for! :-)

Comments and alternative answers

For comparison between the IPlanet App Server, Web...


Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040), Sep
17, 2000
For comparison between the IPlanet App Server, WebSphere and WebLogic go to the
following site :

http://www.iplanet.com/products/infrastructure/app_servers/wp_dhbrown.html

For complete Report from DH Brown go to

http://www.iplanet.com/products/infrastructure/app_servers/wp_dhbrown.pdf

See also a thread on the Threads FAQ


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 11, 2001
The following thread -- Thread Execution: static methods vs. instance methods. --
contains some interesting points about performance, including the paragraph
The claims that EJBs are high-performance are total nonsense. On a single machine,
EJBs will perform worse than servlets or any other custom solution. The reason they
say they're "high-performance" is because they're scalable. It's just doublespeak. It's
like saying a car is faster because it has a bigger gas tank, which means it doesn't have
to stop as often to refuel on long trips -- but on short trips, speed is speed.
(Written by me :-))

How do I insert or update 2 different Entity Beans within the same


transaction?
Location: http://www.jguru.com/faq/view.jsp?EID=116652
Created: Aug 1, 2000 Modified: 2000-08-03 21:54:24.393
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by James Hr
(http://www.jguru.com/guru/viewbio.jsp?EID=106189

To easily achieve this, you can call both inserts from another bean, for example a
Session Bean (if you are using the standard Session wraps Entity design pattern).

Lets say that both Entity Beans have defined create methods, and that the Session
Bean has a method called insertEntities(). Inside the insertEntities() method, you
would obtain handles to the approriate home interfaces and call create on each one.
The trick here is on how you set up the transaction attributes.

You would like both of your Entity Beans to share the same transaction, and in this
example, we can have the Session Bean as the initiator of the transaction.
If we set the insertEntites() method to have a Transaction Attribute of REQUIRED or
REQUIRES_NEW, then we assure that a transaction will be present. (REQUIRED is
generally more robust, since it allows this insertEntities() call to be part of an
ongoing, larger transaction, but if one is not in progress, a new one will be created.)
If we then set the Transaction Attributes for each of the Entity Beans to REQUIRED,
then the same Transaction Context will be propagated from the Session Bean to both
Entity Beans, achieving the result you are after.

[Note that this works no matter which Persistence method (CMP or BMP) the Entity
Beans use.]

How do I use JNDI to locate the home interface of an EJB running on a


different host? My client's InitialContext doesn't seem to know where the
server is.
Location: http://www.jguru.com/faq/view.jsp?EID=116655
Created: Aug 1, 2000 Modified: 2001-10-09 23:26:36.597
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Puneet Sachdeva
(http://www.jguru.com/guru/viewbio.jsp?EID=28785

This depends on which EJB container / JNDI implementation that you are using.

For example, in WebLogic, you set the javax.naming.Context.PROVIDER_URL


property to be the host and port, for example "t3://hostname:7001"

Using the Inprise Application Server, it will do this automatically if you are within the
same subnet using the Smart Agent, or you can pass a command-line parameter into
the virtual machine.

You should refer to the documentation for the implementation that you are using for
the exact specifics.

Comments and alternative answers

How do I use JNDI to locate the home interface of an EJB running on a different
host?
Author: Sribha Jain (http://www.jguru.com/guru/viewbio.jsp?EID=484436), Aug 27,
2001
How do we do this using J2EE server and where is this property specified?

Re: How do I use JNDI to locate the home interface of an EJB running on a
different host?
Author: James Chiang (http://www.jguru.com/guru/viewbio.jsp?EID=341533),
Aug 29, 2001
Setting the following env. when instantiating InitialContext:
Properties env = new Properties();
env.put("java.naming.factory.initial",
"com.sun.jndi.cosnaming.CNCtxFactory");
env.put("java.naming.provider.url",
"iiop://hostname:1050");
InitialContext jndiCtx = new InitialContext(env);

Re: Re: How do I use JNDI to locate the home interface of an EJB running
on a different host?
Author: Sribha Jain (http://www.jguru.com/guru/viewbio.jsp?EID=484436),
Aug 29, 2001
Thanks, James...but will this work for all application servers...i am using J2EE
server currently. And how do we know whether our iiop port is 1050(as u have
given in code).

Re: Re: How do I use JNDI to locate the home interface of an EJB running
on a different host?
Author: Sribha Jain (http://www.jguru.com/guru/viewbio.jsp?EID=484436), Aug
29, 2001
I tried it out but it gives following error on running the client.
javax.naming.NameNotFoundException. Root exception is
org.omg.CosNaming.NamingC ontextPackage.NotFound at
org.omg.CosNaming.NamingContextPackage.NotFoundHelper.read(Unknown
So urce) at
org.omg.CosNaming.NamingContextPackage.NotFoundHelper.extract(Unknown
Source) at org.omg.CosNaming._NamingContextStub.resolve(Unknown Source)
at com.sun.jndi.cosnaming.CNCtx.callResolve(Unknown Source) at
com.sun.jndi.cosnaming.CNCtx.lookup(Unknown Source) at
com.sun.jndi.cosnaming.CNCtx.lookup(Unknown Source) at
javax.naming.InitialContext.lookup(Unknown Source) at
ConverterClient.main(ConverterClient.java:27)

Re: Re: Re: How do I use JNDI to locate the home interface of an EJB
running on a different host?
Author: James Chiang
(http://www.jguru.com/guru/viewbio.jsp?EID=341533), Aug 29, 2001
It's indeed port 1050 for SUN's j2ee RI server. You can type "j2ee -verbose"
to find the naming service port.
As to solve NotFoundException, just copy j2ee.jar (located at
%J2EE_HOME%\lib) to the client end and set into classpath.

Re: Re: Re: Re: How do I use JNDI to locate the home interface of
an EJB running on a different host?
Author: Sribha Jain
(http://www.jguru.com/guru/viewbio.jsp?EID=484436), Aug 29, 2001
I have already done that, but the problem persists...

Re: Re: Re: Re: Re: How do I use JNDI to locate the home
interface of an EJB running on a different host?
Author: moiroux matthieu
(http://www.jguru.com/guru/viewbio.jsp?EID=540275), Nov 6, 2001
i've just try it and it work tx !

Re[2]: How do I use JNDI to locate the home interface of an EJB running
on a different host?
Author: Vassilis Mokas
(http://www.jguru.com/guru/viewbio.jsp?EID=855498), Apr 26, 2002
Can you please tell me the corresponding code for Borland Application Server
4.5 or 5 ? I just want to locate an EJB in BAS using a servlet in Tomcat.

Re[3]: How do I use JNDI to locate the home interface of an EJB


running on a different host?
Author: Laurent Mihalkovic
(http://www.jguru.com/guru/viewbio.jsp?EID=407112), Jul 17, 2002
Hi

I was just going through the same discovery process with the Borland
AppServer, and found myself at the same place you must have been a
while ago...

I found the following document in the Google search cache.

I found it very interesting as it explains some of the basic mechanisms of


the Borland Naming service. One thing for sure, Borland uses Corba/IIOP
as its underlying communication layer. And unlike LDAP for example, or
ven the SUN reference j2ee server, there does not seem to be syntax for
specifying a Context.PROVIDER_URL property. However, I found the
following bit of code that shows some of the other properties that can be
used:

javax.naming.Context context;

// get a JNDI context using the Naming service


Hashtable env = new Hashtable();

env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
"com.inprise.j2ee.jndi.CtxFactory");
env.put(javax.naming.Context.URL_PKG_PREFIXES,
"com.inprise.j2ee");
context = new javax.naming.InitialContext(env);
The documentation states that URL_PKG_PREFIXES is necessary to support
the standard java:comp namespace.

Borland uses a runtime discovery mechanism to identify the servers, and in


all of the examples, a simple ctx = new InitialContext() does the job
of identifying the server dynamically at run-time. My understanding is that
there must be a command line parameter for specifying a specific server
when more than one is present on the network.

Cheers,
laurent

Re[2]: How do I use JNDI to locate the home interface of an EJB running
on a different host?
Author: test sherchan (http://www.jguru.com/guru/viewbio.jsp?EID=962675),
Jul 24, 2002
I am getting the same problem and i am using J2EE server. Can u tell me plz
how to set that env.
Re[3]: How do I use JNDI to locate the home interface of an EJB running on a
different host?
Author: frank xing (http://www.jguru.com/guru/viewbio.jsp?EID=918691), Oct 23, 2002
The way to use JNDI to locate a home interface of an
EJB on remote host differs among different application servers.
As I am using WebLogic6.1, the steps are as follows:
1. at the client side, set the weblogic.jar in your classpath.
2. You have to prepare a Properties object for initialContext, that is:
Properties p = new Properties();
//weblogic's JNDI driver(provider)
p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory

//URL which located the remote server


p.put(Context.PROVIDER_URL,"t3://192.168.153.101:7001");
whereas 192.168.153.101 is my remote server's IP address.
3.Then you construct the InitialContext object
Context ctx = new InitialContext(p);
4.lookup your EJBHome interface:
Object objref = ctx.lookup("com.***.ejb.session.User");
whereas "com.***.ejb.session.User" is your EJB Home interface's JNDI name
5. narrow to the EJBHome
return PortableRemoteObject.narrow(objref, UserHome.class);
that's all you need to do on WebLogic.

And for other application servers, you need to obtain the corresponding JNDI
provider(driver) as step1, set the INITIAL_CONTEXT_FACTORY and PROVIDER_URL
step2 and then follow step 3, 4, 5.

Hope this will be help.

Re: Re[3]: How do I use JNDI to locate the home interface


of an EJB running on a different host?
Author: Srinivas Tati
(http://www.jguru.com/guru/viewbio.jsp?EID=1022849), Nov 7, 2002
how can I achieve the same result if i dont want to hard code the
hostname . Is there some way of passing the hostname as a parameter ?

Re: Re[3]: How do I use JNDI to locate the home interface


of an EJB running on a different host?
Author: leena sharma
(http://www.jguru.com/guru/viewbio.jsp?EID=1030690), Nov 26, 2002
But if my client application is not using weblogic then also I have to
include weblogic.jar. Is there some other way to lookup the bean
deployed under weblogic server.

Re: How do I use JNDI to locate the home interface of an EJB running on
a different host? [JBoss]
Author: Edison Wang
(http://www.jguru.com/guru/viewbio.jsp?EID=1149288), Feb 25, 2004
I was about to post a new thread on the forums when I see this one... I sort of
understood how the looking up to another host is now, but which namespace
should I put in for this line? I'm also not sure whether the IIOP for JBoss is on
port 1050.
env.put("java.naming.factory.initial",
"com.sun.jndi.cosnaming.CNCtxFactory");

Lookup for jndi resources on different app/ldap servers


Author: Java Developer (http://www.jguru.com/guru/viewbio.jsp?EID=1042536), Jan
2, 2003
Take this scenario: I am using iPlanet's app server. My jndi provider is using LDAP in
the background.
Now I have multiple ejbs each on a different appsever say EJB1 is deployed on
AppServer1 EJB2 is deployed on AppServer2 (and essentially different ldap server)
EJB1 uses EJB2 and so does a lookup of EJB2. In the implementation how do I
seamlessly lookup EJB2 on AppServer2 ?
By seamlessly I mean, is there a configuration in jndi, which does the lookup on a
primary server for a resource and not finding it there does a lookup on a secondary
ldap server ?

What is the best way to do a standard logging/tracking mechanism for a


distributed architecture? We're using J2EE, EJB, load balancing, and
multiple tiers.
Location: http://www.jguru.com/faq/view.jsp?EID=116656
Created: Aug 1, 2000 Modified: 2000-08-04 04:09:57.164
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by priya Vasudevan
(http://www.jguru.com/guru/viewbio.jsp?EID=60815

Most application servers provide an api to do logging, however if you want maximum
portability, I would recommend using a third party package, that you can take with
you. An open source libarary such as log4java http://www.log4j.org/ can be used
and fits well with a variety of technologies including EJB and CORBA.

[Does log4j really have support for multitier architectures? That is, so log messages
generated on different hosts end up in the same place? -Alex]
Comments and alternative answers

Hello, Yes. Log4j supports remote logging with the...


Author: Ceki Gulcu (http://www.jguru.com/guru/viewbio.jsp?EID=36306), Sep 4,
2000
Hello,

Yes. Log4j supports remote logging with the SocketAppender. A client can send its
log records to a remote server which can log it according to local server policy. This
includes the ability to log the incoming record on multiple output targets and even to
send the log record to a second log server.

A JMSAppender is on the works by the way. Ceki Gulcu

Should I use Entity Beans for all database tables, even though they may
have complicated relations and joins? Or should I just use them for
frequently-used and simple tables such as account info?
Location: http://www.jguru.com/faq/view.jsp?EID=116658
Created: Aug 1, 2000 Modified: 2000-08-04 04:12:44.822
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Kim Wang
(http://www.jguru.com/guru/viewbio.jsp?EID=99794

This is a question for which there is no "yes-or-no" answer for and depends on the
functionality of the product(s) that you are using, and the requirement of the
system.

An example of this is the ability to support dependant objects, which is coming in EJB
2.0, Inprise Application Server 4.1 supports this feature, where you can have non-
EJB Java objects inside your Entity Beans, which map to different tables in the
database. Giving you one entity bean covering multiple tables.

As a general note, I like to use Entity Beans which wrap a table and its dependants,
so that other programmers do not have to remodel simple relationships such as
Orders/OrderLines if there was an Entity Bean per table.

Comments and alternative answers

Does that mean that you make an OrderEJB only?


Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Nov
24, 2002
Does that mean that you make an OrderEJB and in it have an array of orderLineIds as
an attribute? In short you (personally, that is) make the parent table as the EJB and
don't make the child tables into entity beans, right? I guess you have a getter with DB
calls in it to get the array of orderLineIds for a particular order_id. True?
How do the six transaction attributes map to isolation levels like "dirty
read"? Will an attribute like "Required" lock out other readers until I'm
finished updating?
Location: http://www.jguru.com/faq/view.jsp?EID=116659
Created: Aug 1, 2000 Modified: 2000-08-03 22:36:36.532
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by ralph swick
(http://www.jguru.com/guru/viewbio.jsp?EID=108754

The Transaction Attributes in EJB do not map to the Transaction Isolation levels used
in JDBC. This is a common misconception.

Transaction Attributes specify to the container when a Transaction should be started,


suspended(paused) and committed between method invocations on Enterprise
JavaBeans.

For more details and a summary of Transaction Attributes refer to section 11.6 of the
EJB 1.1 specification.

[Now, how would we actually set JDBC attributes from inside or outside an EJB
method? -Alex]

Is there a way to dynamically lookup EJB interfaces, comparable to CORBA's


dynamic invocation interface (DII)?
Location: http://www.jguru.com/faq/view.jsp?EID=116661
Created: Aug 1, 2000 Modified: 2000-08-04 04:05:50.021
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Archana Karnik
(http://www.jguru.com/guru/viewbio.jsp?EID=68139

Each EJB class has an associated EJBMetaData class that can be retrieved from the
Home interface of the bean.

Home interfaces are published in JNDI, so they can also be discovered.

In particular, the javax.ejb.EJBMetaData interface provides methods such as


getHomeInterfaceClass() and getRemoteInterfaceClass()

One thing that you will have to consider is using an EJB server that support dynamic
stub downloading, so that you can make remote calls to the EJB.

When using Primary Keys, why do I have to implement the hashCode() and
equals() method in my bean?
Location: http://www.jguru.com/faq/view.jsp?EID=118541
Created: Aug 3, 2000 Modified: 2000-08-15 06:29:09.591
Author: Ryan Lynch (http://www.jguru.com/guru/viewbio.jsp?EID=118538) Question
originally posed by lyndon mendoza
(http://www.jguru.com/guru/viewbio.jsp?EID=8369
Implementing the hashCode() and equals() functions ensure that the primary key
object works properly when used with hash tables. Hash tables are the preferred way
EJB servers use to store and quickly retrieve instantiated entity beans.

If session #1 uses widget "A" (which is an entity bean) then the server needs to do
some work to instantiate and initialize the object. If session #2 then requests the
same widget "A", the EJB server will look in its hash table of existing entity beans of
type widget to see if widget "A" has already been instantiated.

Comments and alternative answers

The equals() method needs to compare two primary keys...


Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602), Aug 4,
2000

The equals() method needs to compare two primary keys to determine if they are
equal, which is to say that they refer to the same element in the database. The default
implemention of Object.equals() uses object identity, so it only returns true if
the objects are the same object. You need to provide an implementation of
equals() that is based on the content of the primary keys.

Whenever you override equals() you have to override hashCode() in order to


maintain the relationship:

    if a.equals(b) then a.hashCode() == 
b.hashCode()

it will be great if you can explain this by an example....


Author: Purushottam Nagtode (http://www.jguru.com/guru/viewbio.jsp?EID=24655),
Aug 15, 2000
it will be great if you can explain this by an example.

For ex: If my primarykey class is UserPK(int userid , String username), how do I


implememnt hachCode() and equals() function?

A really neat example is in the recent Book of Ent...


Author: shoban babu (http://www.jguru.com/guru/viewbio.jsp?EID=87955), Sep 18,
2000
A really neat example is in the recent Book of Enterprise Java Beans of O'Reilly
publications - In Chapter 9

Are there any good books that cover EJB (and related topics like LDAP and
so on)?
Location: http://www.jguru.com/faq/view.jsp?EID=119643
Created: Aug 4, 2000 Modified: 2000-08-04 13:18:39.763
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by mathew koshy
(http://www.jguru.com/guru/viewbio.jsp?EID=110668

Check out Enterprise JavaBeans from O'Reilly by our pal Richard Monson-Haefel. The
O'Reilly series also has good books on Security, Distributed Computing, and so on.

See also

• What books cover JNDI (Java Naming and Directory Interface)?

Comments and alternative answers

there's also a very comprehensive site covering J2EE...


Author: Peter Kua (http://www.jguru.com/guru/viewbio.jsp?EID=32290), Aug 7,
2000
there's also a very comprehensive site covering J2EE stuff, and you can also
download the complete Mastering Enterprise JavaBeans by Ed Roman. the site is
http://www.theserverside.com

If Client C calls EJB A, and EJB A calls EJB B, then will the methods in B be
invoked with the same security context of Client C?
Location: http://www.jguru.com/faq/view.jsp?EID=119676
Created: Aug 4, 2000 Modified: 2000-08-08 01:06:38.194
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by tirumala kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=94613

It depends on how you configure the EJBs. If you set the EJB A and B's run-as-
modes to CLIENT_IDENITY in the deployment descriptor, all methods in A and
methods in B will execute within the security context of Client C.
Comments and alternative answers

ok this works in version 1.0, but could you please...


Author: tirumala kumar (http://www.jguru.com/guru/viewbio.jsp?EID=94613), Aug
8, 2000
ok this works in version 1.0, but could you please give me info for version 1.1

Can I deploy two beans in a single jar file? If so, how?


Location: http://www.jguru.com/faq/view.jsp?EID=120786
Created: Aug 7, 2000 Modified: 2000-08-24 18:57:48.486
Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602) Question
originally posed by tirumala kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=94613

Yes, multiple EJBs can be deployed in a single jar file. The deployment is somewhat
different between EJB 1.0 and EJB 1.1.
In EJB 1.0 each bean has a separate serialized deployment descriptor. All of the bean
classes and deployment descriptors are placed in the jar file along with the manifest
file named META-INF/MANIFEST.MF. The manifest file must contain an entry for each
bean that names the bean's deployment descriptor. For example, the following
manifest is for a jar file that contains two deployment descriptors:

Name: BeanADD.ser
Enterprise-Bean: True

Name: dirname/BeanBDD.ser
Enterprise-Bean: True

Note that a blank line is required between the entries in the manifest file.

In EJB 1.1 and in the draft EJB 2.0 specification, instead of a manifest and serialized
deployment descriptors there is a single shared XML deployment descriptor named
META-INF/ejb-jar.xml. Within ejb-jar.xml there must be either a <session> or
<entity> element for each bean in the jar file. For example, the following XML
fragment is for a jar file that contains one entity and one session bean:

<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>MySessionBean</ejb-name>
... other xml elements describing the bean's deployment
properties ...
</session>
<entity>
<ejb-name>MyEntityBean</ejb-name>
... other xml elements describing the bean's deployment
properties ...
</entity>
</enterprise-beans>
</ejb-jar>

The EJB 2.0 draft specification for deployment descriptors differs from EJB 1.1 only in
the addition of XML elements for describing additional bean properties.

Comments and alternative answers

deploying two beans in a single jar file


Author: lalitha yellapragada (http://www.jguru.com/guru/viewbio.jsp?EID=390717),
Jun 4, 2001
In ejb1.1, we will change accordingly in ejb-jar file.. it is fine...But what changes has
to be made in weblogic-ejb-jar? Where shall we specify the 2 jndi

Re: deploying two beans in a single jar file


Author: mahesh kumar (http://www.jguru.com/guru/viewbio.jsp?EID=472441),
Aug 9, 2001
what ever the code is written in the weblogic-ejb-jar file for one jndi name just
copy and paste for the second bean with different jndi name .
Does Tomcat support EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=123221
Created: Aug 9, 2000 Modified: 2001-10-23 15:04:24.61
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Stella Fredo
(http://www.jguru.com/guru/viewbio.jsp?EID=112519

No, Tomcat does not support EJB. It is a Servlet/JSP container, not an EJB container.

The Jakarta Project provides an implementation of the Servlets API called Tomcat,
and an implementation of JavaServer Pages called Jasper. These are bundled
together in the Tomcat release.

However, the J2EE Reference Implementation, which supports EJB, is bundled with
an old version of Tomcat. This adds Tomcat's support for Servlets and JSP to the
J2EE product.

See also

• Can I use the latest version of Tomcat inside Sun's J2EE implementation?
• Can I use the Apache Web Server with the Sun J2EE Reference
Implementation?

Comments and alternative answers

There is a open source project for EJB called jboss...


Author: gunjan doshi (http://www.jguru.com/guru/viewbio.jsp?EID=65610), Aug 9,
2000
There is a open source project for EJB called jboss from www.jboss.org which
intergrates very well with Tomcat. The site even has step by step instructions for
intergrating the two.

You could also try, as an alternative to the reference...


Author: Eoghan O'Donnell (http://www.jguru.com/guru/viewbio.jsp?EID=74622),
Aug 9, 2000
You could also try, as an alternative to the reference implementation, the JBOSS
(http://www.jboss.org) EJB server, which has integrates nicely w/ Tomcat. It supports
EJB1.1.

It's a snap to set up and configure Tomcat w/ it, if you follow the advice given on their
site.

What are the viable alternatives for calling EJBs from non-Java programs?
Specifically, I'm interested in calling EJBs (probably indirectly) from plain
old C language.
Location: http://www.jguru.com/faq/view.jsp?EID=124198
Created: Aug 10, 2000 Modified: 2000-08-10 10:29:51.64
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Marty Hill
(http://www.jguru.com/guru/viewbio.jsp?EID=115510

Short answer: JNI

See also How can I access my EJBs from COM environments such as VB?

Comments and alternative answers

I understand that JNI allows Java code to call non-Java...


Author: Marty Hill (http://www.jguru.com/guru/viewbio.jsp?EID=115510), Aug 10,
2000
I understand that JNI allows Java code to call non-Java code (typically OS services),
but that's not what I'm asking. I need to call EJB methods from C code. I'm looking
for answers that do not involve COM or CORBA.

You can call Java methods from C using JNI, you can...
Author: Jim Coker (http://www.jguru.com/guru/viewbio.jsp?EID=2), Aug 10, 2000
You can call Java methods from C using JNI, you can also access Java data structures
directly.

maybe via this way : C -> HTTP -> SERVLET ->...


Author: Gilles Philippart (http://www.jguru.com/guru/viewbio.jsp?EID=83422), Aug
11, 2000
maybe via this way : C -> HTTP -> SERVLET -> JavaBean (optional) -> EJB. correct
me if i'm wrong.

Sybase Enterprise Server allows EJBs to be called as...


Author: Ludovic Claude (http://www.jguru.com/guru/viewbio.jsp?EID=2782), Aug
11, 2000
Sybase Enterprise Server allows EJBs to be called as stored procedures, but this
functionality is very limited.
An other solution would be to have servlets calling the EJBs, and your C code makes
HTTP request to the servlet and parse the result. Ugly and inefficiant at best...

Maybe you can use : C<-->corba<-->java...


Author: liu coolx (http://www.jguru.com/guru/viewbio.jsp?EID=69763), Aug 13,
2000
Maybe you can use : C<-->corba<-->java<-->ejb it works well.

You should check out our JunC++ion product at http...


Author: Alexander Krapf (http://www.jguru.com/guru/viewbio.jsp?EID=221775), Oct
4, 2000
You should check out our JunC++ion product at http://www.codemesh.com. It is
currently generally available on Wintel, but ports to various Unices are underway.

Its codegenerator accepts compiled Java classes as input and generates C++ proxy
classes for them. These proxy classes can be used like normal C++ classes, but totally
transparently to the developer a JVM gets launched when they are used the first time.
All operations on these classes result in the execution of the underlying Java code.
The connection is made through JNI, but you're totally insulated from it by the
generated code.

Once you're in C++, it's very easy to hook the code up to a C program.

One nice benefit of this solution is that all Java types are available to the C++
program. In CORBA you are limited to primitive and IDL-declared types.

Another benefit is that you can use complex Java datatypes in your C++ program
without having to convert the data. Take for example the java.util.Date type. If
your EJB server tries to return a date to a client, how do you have to do this for a C
client? In Java you just return the Date instance but for a C/C++ client you would
have to convert it to some kind of "seconds since" value or extract integers for the
C/C++ client to be able to make sense of it. That's code that you have to write just to
accommodate a language choice on the client.

Using JunC++ion on the other hand, you just use the C++ Date proxy class on the
client side and have full access to its rich call interface.

EJB-IDL-C++
Author: parul dholakia (http://www.jguru.com/guru/viewbio.jsp?EID=451179), Jul
26, 2001

You can convert EJB to IDL and then IDL to c++ which is ofcourse a CORBA
solution.

When I want to add/remove a record from database, should I use the


methods directly from Entity Bean or I should use a Session Bean to create
some methods which will call the methods in the Entity Bean?
Location: http://www.jguru.com/faq/view.jsp?EID=124213
Created: Aug 10, 2000 Modified: 2000-08-10 10:58:57.514
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by eddie chui
(http://www.jguru.com/guru/viewbio.jsp?EID=115751

It depends :-)

Usually you're fine just calling the EB methods (actually, create, and sometimes
remove, would be called on the EJBHome). Use the SB if you have other things you
want to do at the same time, like adding/removing other dependent entity beans, or
logging the action, or performing additional validation.
See also Should I use Entity Beans for all database tables, even though they may
have complicated relations and joins? Or should I just use them for frequently-used
and simple tables such as account info?

Comments and alternative answers

In a larger application (with a larger team), you may...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Aug 14, 2000
In a larger application (with a larger team), you may want to madnate that all client
calls go through session beans: This way you know that every interaction has a well
defined unit of work, there won't be as much temptation to add a call to an entity from
the client, and you'll have an extra level of indirection should you need to make major
changes for performance reasons.

Remember that every call to an EJB is a transaction (unless your client is managing
the transaction itself, which is probably more than you really want to do).

Can someone explain in detail the different steps involved in adding 'finder'
methods other than 'findByPrimaryKey' in IBM's VisualAge for Java?
Location: http://www.jguru.com/faq/view.jsp?EID=124806
Created: Aug 11, 2000 Modified: 2000-08-11 13:12:28.152
Author: Badri Kuppa (http://www.jguru.com/guru/viewbio.jsp?EID=98194) Question
originally posed by shyla rajeev
(http://www.jguru.com/guru/viewbio.jsp?EID=111902

You can create finder methods in the Home Interface and give an SQL hint in the
finderHelper class. For example if you want to create a finder method for userId then
the method in the home interface would be like this.
ObjectToBeReturned findByUserId(String userId) throws java.rmi.RemoteException,
javax.ejb.FinderException;

then in the finder helper class you can put this line..

public final static String findByUserIdWhereClause = "USERID = ?";

Remember, the String declaration in finderHelper class should be as above, i.e.,

findBy+toBeFound+whereClause
you can replace the where clause by a select statement too!

I hope this helps you!

--Badri bkuppa@usa.net

What is a three-tier architecture?


Location: http://www.jguru.com/faq/view.jsp?EID=125072
Created: Aug 11, 2000 Modified: 2000-08-11 14:55:10.431
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by joy choudhury
(http://www.jguru.com/guru/viewbio.jsp?EID=104345

A three-tier architecture is any system which enforces a general separation between


the following three parts:

1. Client Tier or user interface


2. Middle Tier or business logic
3. Data Storage Tier

Applied to web applications and distributed programming, the three logical tiers
usually correspond to the physical separation between three types of devices or
hosts:

1. Browser or GUI Application


2. Web Server or Application Server
3. Database Server (often an RDBMS or Relational Database)

However, inside of the application server, there is a further division of program code
into three logical tiers. This is kind of fractal: the part (app server object design)
resembles the whole (physical system architecture). In a classic JSP/Servlet system,
these objects are usually implemented as:

1. JSPs or Servlets responsible for creating HTML or WML user interface pages
2. Servlets or JavaBeans responsible for business logic
3. Servlets, JavaBeans, or Java classes responsible for data access. These
objects usually use JDBC to query the database.

In an EJB system, the three logical tiers are usually implemented somewhat
differently:

1. JSPs, Servlets, or Java client applications responsible for user interface


2. Session Beans or Entity Beans whose methods implement business logic
and business rules
3. Entity Beans whose fields represent data; these fields are "persisted"
(stored and retrieved) either by the EJB server (for container-managed
persistence) or by the Entity Beans themselves (for bean-managed
persistence)

As you can see, the precise definition of "tiers" can vary widely depending on the
particular needs and choices of an application designer. However, they all maintain
the general division of client-logic-storage.

If the architecture contains more than three logical tiers -- for instance, multiple data
feeds, multiple transactional data sources, multiple client applications -- then it is
typically called an "N-tier" or "Distributed" architecture.

See also:
• What seperates one tier from another in the context of n-tiered
architecture?
• In distributed architecture (typical three tier consisting of thin client,
middleware & database) which type of JDBC driver should be used
and why?
• What is meant by the term "business logic"?
• Are the following schemes 3 tiered architecture?
• What is the recommended, "best" architecture for JSP applications?

Comments and alternative answers

NEED SOME HELP WITH THE FOLLOWING QUESTIONS


Author: hapz happy (http://www.jguru.com/guru/viewbio.jsp?EID=1239371), Apr 18,
2005
hi, just need some answers to some questions about XML coz i dont hav a clue. 1)
how to identify a website that is using XML? 2) in which way can you identify a
website is using XML and not xhtml? 3) what is server-side XML, what is client-side
XML? 4) how to identify a website that is using a Three-Tier Architecture

Re: NEED SOME HELP WITH THE FOLLOWING QUESTIONS


Author: hapz happy (http://www.jguru.com/guru/viewbio.jsp?EID=1239371), Apr
18, 2005
reply to h.mahil@herts.ac.uk thanx

Re[2]: NEED SOME HELP WITH THE FOLLOWING QUESTIONS


Author: Felix Zhu (http://www.jguru.com/guru/viewbio.jsp?EID=1241528),
Apr 28, 2005
You should think twice about your post on this website. There are many other
methods of gaining knowledge. See me in class. I can help.

Re[2]: NEED SOME HELP WITH THE FOLLOWING QUESTIONS


Author: Leonardo DaVinci
(http://www.jguru.com/guru/viewbio.jsp?EID=1245556), May 24, 2005
Meow :)

How can I use JDO with EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=125704
Created: Aug 13, 2000 Modified: 2000-08-13 15:51:33.693
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Corneanu Dan
(http://www.jguru.com/guru/viewbio.jsp?EID=41082

JDO and EJB are different and incompatible persistence models. While there may in
the future be an EJB server that uses JDO, no such thing currently exists, and IMHO
never should.
Comments and alternative answers
Sun's site states that JDO could be used to implement...
Author: John Francis (http://www.jguru.com/guru/viewbio.jsp?EID=296576), Jan 8,
2001
Sun's site states that JDO could be used to implement persistence for a bean using
bean managed persistence. JDO is an object to relational mapping layer, so can live
inside the implementation of the bean.

ejb and jdo answer unsatisfactory


Author: chris mountford (http://www.jguru.com/guru/viewbio.jsp?EID=528277), Mar
7, 2004
I think EJB would better be described as a component model with CMP its stock
persistence model. BMP is an alternate persistence model that delegates and this
could easily delegate to JDO. Of course some people disprefer CMP. JDO is not a
component model at all so I can't see the incompatibility you cite.

How can I invoke an EJB from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=126254
Created: Aug 14, 2000 Modified: 2000-08-14 08:57:21.382
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by prakash patel
(http://www.jguru.com/guru/viewbio.jsp?EID=102421

You invoke an EJB from a servlet or JSP the same way you invoke one from any
other Java code. Just read the EJB docs and FAQ and have fun!
Comments and alternative answers

first create the home object, then using home, access...


Author: raghavendra ghorpade (http://www.jguru.com/guru/viewbio.jsp?EID=344479),
Mar 5, 2001
first create the home object, then using home, access the method. for example:
try {
Context c=new InitialContext();
Object o=c.lookup("gor");
first.ABCHome
home=(first.ABCHome)PortableRemoteObject.narrow(o,first.ABCHome.class);
abc=home.create();
(abc.yourmethod(with paramaters)
}
catch(Exception ex) {
ex.printStackTrace();
}

Re: first create the home object, then using home, access...
Author: J C (http://www.jguru.com/guru/viewbio.jsp?EID=756527), Feb 12, 2002
This seems to be lots of details missing. When you run J2EE client with Sun's
J2EE reference implementation server, you use runclient command which sets a
number of properties. How do you set these within servlet/JSP? I guess that you
have to set these properties when starting web server (e.g., servlet), right?

Why use EJB when we can do the same thing with servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=126400
Created: Aug 14, 2000 Modified: 2001-11-09 06:08:03.377
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by sreenivasulu kadirimangalam
(http://www.jguru.com/guru/viewbio.jsp?EID=123964

Actually, servlets/JSPs and EJB are complementary, not competing technologies:


Servlets provide support for writing web based applications whereas EJBs provide
support for writing transactional objects. In larger web systems that require
scalability, servlet and JSP or XML/XSL technologies provide support for the front end
(UI, client) code, where EJB provides support for the back end (database connection
pooling, declaritive transactions, declaritive security, standardized
parameterization...)

The most significant difference between a web application using only servlets and
one using servlets with EJBs is that the EJB model mandates a separation between
display and business logic. This is generally considered a Good Thing in non-trivial
applications because it allows for internal reuse, allows flexibility by providing a
separation of concerns, gives a logical separation for work, and allows the business
logic to be tested separately from the UI (among others).

Some of the hings that servlets and JSPs can do that EJBs cannot are:

• Respond to http/https protocol requests.


• (With JSP) provide an easy way to format HTML output.
• Easily associate a web user with session information

Some of the things that EJBs enable you to do that servlets/JSPs do not are:

• Declaritively manage transactions. In EJB, you merely specify whether a


bean's methods require, disallow, or can be used in the context of a
transaction. The EJB container will manage your transaction boundaries
appropriately. In a purely servlet architecture, you'll have to write code to
manage the transaction, which is difficult if a logical transaction must access
multiple datasources.
• Declaritively manage security. The EJB model allows you to indicate a security
role that the user must be assigned to in order to invoke a method on a bean.
In Servlets/JSPs you must write code to do this. Note, however that the
security model in EJB is sufficient for only 90% to 95% of application code -
there are always security scenarios that require reference to values of an
entity, etc.

What restrictions are imposed on an EJB? That is, what can't an EJB do?
Location: http://www.jguru.com/faq/view.jsp?EID=127037
Created: Aug 15, 2000 Modified: 2000-08-16 00:19:27.196
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
From the spec:

• An enterprise Bean must not use read/write static fields. Using read-only
static fields is allowed. Therefore, it is recommended that all static fields in
the enterprise bean class be declared as final.
• An enterprise Bean must not use thread synchronization primitives to
synchronize execution of multiple instances.
• An enterprise Bean must not use the AWT functionality to attempt to output
information to a display, or to input information from a keyboard.
• An enterprise bean must not use the java.io package to attempt to access
files and directories in the file system.
• An enterprise bean must not attempt to listen on a socket, accept connections
on a socket, or use a socket for multicast.
• The enterprise bean must not attempt to query a class to obtain information
about the declared members that are not otherwise accessible to the
enterprise bean because of the security rules of the Java language. The
enterprise bean must not attempt to use the Reflection API to access
information that the security rules of the Java programming language make
unavailable.
• The enterprise bean must not attempt to create a class loader; obtain the
current class loader; set the context class loader; set security manager;
create a new security manager; stop the JVM; or change the input, output,
and error streams.
• The enterprise bean must not attempt to set the socket factory used by
ServerSocket, Socket, or the stream handler factory used by URL.
• The enterprise bean must not attempt to manage threads. The enterprise
bean must not attempt to start, stop, suspend, or resume a thread; or to
change a thread's priority or name. The enterprise bean must not attempt to
manage thread groups.
• The enterprise bean must not attempt to directly read or write a file
descriptor.
• The enterprise bean must not attempt to obtain the security policy
information for a particular code source.
• The enterprise bean must not attempt to load a native library.
• The enterprise bean must not attempt to gain access to packages and classes
that the usual rules of the Java programming language make unavailable to
the enterprise bean.
• The enterprise bean must not attempt to define a class in a package.
• The enterprise bean must not attempt to access or modify the security
configuration objects (Policy, Security, Provider, Signer, and Identity).
• The enterprise bean must not attempt to use the subclass and object
substitution features of the Java Serialization Protocol.
• The enterprise bean must not attempt to pass this as an argument or method
result. The enterprise bean must pass the result of
SessionContext.getEJBObject() or EntityContext. getEJBObject() instead.

Why do we have a remove method in both EJBHome and EJBObject?


Location: http://www.jguru.com/faq/view.jsp?EID=127823
Created: Aug 15, 2000 Modified: 2000-08-16 07:27:14.72
Author: Wayne Kidd (http://www.jguru.com/guru/viewbio.jsp?EID=18969) Question
originally posed by kathir_75_mk resan
(http://www.jguru.com/guru/viewbio.jsp?EID=117079

With the EJBHome version of the remove, you are able to delete an entity bean
without first instantiating it (you can provide a PrimaryKey object as a parameter to
the remove method). The home version only works for entity beans. On the other
hand, the Remote interface version works on an entity bean that you have already
instantiated. In addition, the remote version also works on session beans (stateless
and statefull) to inform the container of your loss of interest in this bean.

Is there a guarantee of uniqueness for entity beans?


Location: http://www.jguru.com/faq/view.jsp?EID=128741
Created: Aug 16, 2000 Modified: 2000-08-16 22:17:23.973
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Dennis Dupont
(http://www.jguru.com/guru/viewbio.jsp?EID=38842

[ I have looked through the EJB 1.1 spec for a requirement that containers guarantee
that entity beans in the ready state are unique (i.e. that there is never more than
one instance of a bean with a given primary key value). I cannot find such a
guarantee, but I would expect one. Does anyone know if this is indeed the case? ]

There is no such guarantee. The server (or servers) can instantiate as many
instances of the same underlying Entity Bean (with the same PK) as it wants.
However, each instance is guaranteed to have up-to-date data values, and be
transactionally consistent, so uniqueness is not required. This allows the server to
scale the system to support multiple threads, multiple concurrent requests, and
multiple hosts.

Comments and alternative answers

Though it may not be guaranteing the uniqeness, I...


Author: ranak ranak (http://www.jguru.com/guru/viewbio.jsp?EID=129458), Aug 17,
2000
Though it may not be guaranteing the uniqeness, I feel the designer should make each
primarykey unique.

As a special case I wanted to create a dummy obect with a dummy primarykey in


weblogic4.5. When I was trying to create two Objects with the same primarykey, it
threw an Exception, as the other object was alreday in the Pool. Which is expected.
So I used findByprimarykey to retrive the object instead.

That's correct, but "unique" here meant ...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 18, 2000
That's correct, but "unique" here meant "unique instance in memory" not "unique
record in database." There must indeed be only one unique data representation
corresponding to a primary key; however, the server may have multiple bean
instances, in one or more servers, referring to that record (or set of records).
How can I call an EJB via an oracle stored procedure?
Location: http://www.jguru.com/faq/view.jsp?EID=129099
Created: Aug 17, 2000 Modified: 2000-08-18 19:31:30.752
Author: Nicholas Whitehead (http://www.jguru.com/guru/viewbio.jsp?EID=1260)
Question originally posed by Ramesh K
(http://www.jguru.com/guru/viewbio.jsp?EID=118618

[My EJB is deployed on JRUN server and my bean's url is ejipt://rams.com:2323. ]

There are a couple of ways you could potentially do this. You will need to select the
one[s] which suit your environment best.

The first is the time tested legacy method of calling any external routine from within
an Oracle database, whcih is to have an external process running in the OS which is
connected to the database. You then communicate with this process via DBMS_PIPEs
and the external process becomes your agent by listening for commands, executing
the call to your EJB, confirming the call and returning any applicable results.

The other possible way to do this is to create an EJB client in the Oracle JVM. I think
this is possible as of Oracle 8.1.6.

The third way would be to use an external library call. I think you can still only do
these in C, but you will probably be able to find a way to invoke an EJB from C.

Why is it that business methods should not be declared final?


Location: http://www.jguru.com/faq/view.jsp?EID=129282
Created: Aug 17, 2000 Modified: 2000-08-18 19:34:20.993
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by kathir_75_mk resan
(http://www.jguru.com/guru/viewbio.jsp?EID=117079

I believe that the basic reason is that mandating non-final business methods allows
container developers to implement their EJB container via inheritence. They can
generate a class that extends your bean, with methods that perform transactional
housekeeping, then call the inherited method (which is the one you wrote in your
bean), then perform more housekeeping.

That said, I know of no major container that does things this way (although some of
the OODBMS vendors may)

Why is ejbFindByPrimaryKey mandatory?


Location: http://www.jguru.com/faq/view.jsp?EID=131680
Created: Aug 21, 2000 Modified: 2000-08-21 19:02:07.0
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by kathir_75_mk resan
(http://www.jguru.com/guru/viewbio.jsp?EID=117079

An Entity Bean represents persistent data that is stored outside of the EJB
Container/Server.
The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into
the container, similar to a SELECT statement in SQL.

By making this method mandatory, the client programmer can be assured that if
they have the primary key of the Entity Bean, then they can retrieve the bean
without having to create a new bean each time - which would mean creating
duplications of persistent data and break the integrity of EJB.

Is it safe to pass EJBObjects as parameters to remote objects that may be


on another machine, or must you use the handle instead?
Location: http://www.jguru.com/faq/view.jsp?EID=131683
Created: Aug 21, 2000 Modified: 2000-08-21 19:04:14.921
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Alex McManus
(http://www.jguru.com/guru/viewbio.jsp?EID=117866

Yes, it is valid to pass references to remote objects as parameters to methods. The


references that you are passing are actually RMI stubs to the remote objects.

Generally, you should use the Handle when holding a reference to an EJB beyond
the life of a client process.

Comments and alternative answers

EJBObject and Handle


Author: Stefano De Giorgi (http://www.jguru.com/guru/viewbio.jsp?EID=533178),
Oct 29, 2001
What is the difference between serialize the EJBObject to disk and serialize Handle to
disk? I look at WLS 6.0 code and I found that getHandle() instantiate an Handle that
simply store in an instance variable a reference to the EJBObject. Thanks

Re: EJBObject and Handle


Author: John Quinn (http://www.jguru.com/guru/viewbio.jsp?EID=29646), Dec
11, 2001
I haven't looked at the WLS code, but if you look at the J2EE SDK source, you'll
see that the essential idea of a Handle is that the information necessary to look-up
the bean via JNDI is stored in the instance implementing Handle. Thus, when
getEJBObject() is invoked on a Handle, the JNDI lookup is performed, and the
container returns the RMI stub class necessary to instantiate the RMI stub
implementing the remote interface. If you only serialize the remote, then the
remote process that deserializes it may not have the RMI stub class in its classpath,
and you'll get a ClassNotFoundException when deserialization is attempted.

Re: EJBObject and Handle


Author: Seetesh H (http://www.jguru.com/guru/viewbio.jsp?EID=1038574), Dec
17, 2002
Hi,
With this u can achieve Activation and Passivation ie the state of the Session bean
can be stored using Object Serialization as it doesnt contain the ejbLoad and
ejbStore methods contained in the Entity Bean only.
Session bean uses object serialization and stores the handle to an external file say
if the session bean is moved from ready to pooled state and again if the business
methods on the pooled Session bean is called then the state of that object (in this
case the handle ) can be recalled from the external file media.
Hope this helps,
Seetesh

Is there a way that a Stateful Session Bean can remove itself when a
transaction commits? Without this, the remove must be performed by the
client that starts the transaction, which can be difficult when there may be
non-stateful beans in-between.
Location: http://www.jguru.com/faq/view.jsp?EID=131690
Created: Aug 21, 2000 Modified: 2000-08-21 19:05:49.861
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Alex McManus
(http://www.jguru.com/guru/viewbio.jsp?EID=117866

You could leave this to the Container or do it yourself.

Container - A solution would be to set a timeout value for the stateful session bean
so that it will be removed after a shorter idle duration.

Developer - If the above is not sufficient and you need to explicitly clean up the
bean, you could try posting the Stateful Session Bean's handle in a JNDI context and
have another object check the context, obtain the handle and then call remove on
the home interface, passing in the handle as an argument. Remember that the
Handle is Serializable, so there could be many variations on this strategy.

Comments and alternative answers

Explicit remove versus timeout?


Author: Jirka Hanika (http://www.jguru.com/guru/viewbio.jsp?EID=1189077), Jun
28, 2005
Why can't I simply call remove just after the last call to the stateful session bean
returns to its (presumably stateless) caller, not relying on timeouts? I've verified that
the container (Jboss 4) will still duly call beforeCompletion and afterCompletion on
the stateful session bean.

It seems to me that calling remove explicitly is a cleaner solution, as long as you can
tell which call to the bean has been the last one in a transaction.

I haven't checked what the spec says about this, however.

Re: Explicit remove versus timeout?


Author: Jirka Hanika (http://www.jguru.com/guru/viewbio.jsp?EID=1189077),
Jun 29, 2005
OK, I have checked. Apparently this Jboss 4 behavior is a bug. The remove call
should have thrown RemoveException if called during the transaction.

Is there an example of a shopping cart using Stateful Session Beans and a


JSP client?
Location: http://www.jguru.com/faq/view.jsp?EID=131697
Created: Aug 21, 2000 Modified: 2000-08-21 18:57:42.892
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by srikanth thati
(http://www.jguru.com/guru/viewbio.jsp?EID=115168

You should download the sample Java Pet Store sample application, It's part of the
J2EE Blueprints. http://java.sun.com/j2ee/download.html

I've read that the Primary Key field can be a wrapper class. But, no where
has it been mentioned if it can be any Java API class. To be specific, can
java.util.Vector be a Primary Key class for my bean?
Location: http://www.jguru.com/faq/view.jsp?EID=131699
Created: Aug 21, 2000 Modified: 2000-08-21 19:08:27.141
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by SRI NAGESH NAYUDU
(http://www.jguru.com/guru/viewbio.jsp?EID=122079

I am not aware of any application Server that would allow a Vector to be specified as
a primary key type for an Entity Bean.

Logically when you think about it, there is no clear database type[s] that you would
map it to in a relational database.

If you are trying to make a compound Primary Key, then you should use a wrapper
class that contains simple types.

How can I pass init parameters to enterprise beans?


Location: http://www.jguru.com/faq/view.jsp?EID=131729
Created: Aug 21, 2000 Modified: 2000-08-24 16:15:49.452
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Ivan Stoyanov
(http://www.jguru.com/guru/viewbio.jsp?EID=102920

You can specify Environment Entries that are accesssible by your EJB's. Inside your
ejb-jar.xml you define the environment entries.

<env-entry>
<env-entry-name>theParameter</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>theValue</env-entry-value>
</env-entry>
You can access the variable inside your EJB using the Environment Naming Context
(in EJB 1.1)

Context ctx = new InitialContext();


String val = (String)ctx.lookup("java:comp/env/theParameter");

How can I make a clone or duplicate of an entity bean? Also, can I do so


within another EJB which does not have any knowledge about the entity
bean it is referring to? I need to build an EJB which will take an(y) entity
bean as input, make a copy and return the copy.
Location: http://www.jguru.com/faq/view.jsp?EID=131733
Created: Aug 21, 2000 Modified: 2000-08-24 16:15:12.811
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Mathivanan Elangovan
(http://www.jguru.com/guru/viewbio.jsp?EID=21981

You cannot make a clone of an Entity Bean. This is like inserting the same row into a
database twice.

What you may want to do is to make a copy of the values inside an Entity Bean,
using the Details Object design pattern. See the pattern Description for more details.

How can I access EJB from ASP?


Location: http://www.jguru.com/faq/view.jsp?EID=131737
Created: Aug 21, 2000 Modified: 2000-08-24 16:34:53.634
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Chandramouli Srinivasan
(http://www.jguru.com/guru/viewbio.jsp?EID=41323

You can use the Java 2 Platform, Enterprise Edition Client Access Services (J2EETM
CAS) COM Bridge 1.0, currently downloadable from
http://developer.java.sun.com/developer/earlyAccess/j2eecas/

Or, you can rewrite the ASPs as JSPs... :-)

Is it possible to get notified somehow if a certain amount of time elapses


during (within) a transaction or method call? I want to react if e.g. an EJB-
method doesn't react after a few seconds.
Location: http://www.jguru.com/faq/view.jsp?EID=131988
Created: Aug 22, 2000 Modified: 2000-08-24 16:25:31.74
Author: Nicholas Whitehead (http://www.jguru.com/guru/viewbio.jsp?EID=1260)
Question originally posed by Christoph Moser
(http://www.jguru.com/guru/viewbio.jsp?EID=124776

The EJB descriptor defined session timeout (sessionTimeout in the WebLogic


descriptor) will cause the remote call to throw an exception if the operation runs over
that time. This will cause the operation to be rolled back if it is running in a
transaction, but the caller will be notified by the exception so you can react
accordingly.

[Source code for ejb.xml, anyone? -Alex]


Comments and alternative answers

I think you mean: <transaction-descriptor> ...


Author: Christoph Moser (http://www.jguru.com/guru/viewbio.jsp?EID=124776),
Aug 24, 2000
I think you mean:
<transaction-descriptor>
<trans-timeout-seconds>2</trans-timeout-seconds>
</transaction-descriptor>

I only know session-timeout in web.xml regarding a http connection.

The problem is that a rollback occurs AFTER the timeout, but the exception is thrown
at the END of the transaction.

The other problem is - I want to set the timeout value manually, during runtime.

Re: I think you mean: <transaction-descriptor> ...


Author: Venkata Chaganti (http://www.jguru.com/guru/viewbio.jsp?EID=996780),
Sep 9, 2002
The timer option in EJB2.1 could provide you with what you need.

My database has a column of type DATETIME. What type of Java variable do


I use in the EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=132002
Created: Aug 22, 2000 Modified: 2000-08-24 16:22:39.892
Author: Nicholas Whitehead (http://www.jguru.com/guru/viewbio.jsp?EID=1260)
Question originally posed by hemanth venkataraman
(http://www.jguru.com/guru/viewbio.jsp?EID=117257

Question continues: [util.Date didn't work so i tried sql.Date and eventually


java.sql.Timestamp. But timestamp needs to be formatted in ejbStore to be put in
DB and also upon creation of the bean, timestamp must be formatted to be inserted
in the db. But i can't format within the ejbCreate method itself. Where is such
formatting to take place so that a java variable can be passed to a column of type
DATETIME?]

I am not sure why you cannot format in ejbCreate. I assume this is some sort of CMP
issue. However, we experienced a similar issue where we needed to reference a
database generated sequence in the creation of the entity bean, and the CMP
process did not give us access to the generated number in ejbCreate. In this case,
we used the ejbPostCreate method which is called directly after ejbCreate and I
believe is specifically intended to support operations like yours.

[OK, but the proper type is java.sql.Timestamp, right? -Alex]

See also How do I map a Date/Time field to an Oracle database with CMP?
When (manually) deploying an EJB where do you specify the JNDI name
that the bean is bound to in the JNDI tree?
Location: http://www.jguru.com/faq/view.jsp?EID=132923
Created: Aug 23, 2000 Modified: 2000-08-24 18:56:25.582
Author: satyanarayana sairam
(http://www.jguru.com/guru/viewbio.jsp?EID=132906) Question originally posed by
Henrik Buch (http://www.jguru.com/guru/viewbio.jsp?EID=121686

[Questioner continues: According to the EJB1.1 spec there is no relation between the
<ejb-name> tag in the deployment descriptor (or assembly descriptor) and the JNDI
name. I can see that a client can use a "logical" name that can be mapped via
vendor specific deployment info (e.g. orion-application-client.xml).]

When you are deploying the application in using Web Logic 4.5.1 server, in the
deployment wizard you can specify the JNDI name and using the same name you can
look up from the client.

[Is there any standard way to do it? If not, can someone give feedback with info for
other servers? -Alex]

Where can I find the API documentation for Enterprise JavaBeans (EJB)?
Location: http://www.jguru.com/faq/view.jsp?EID=134139
Created: Aug 24, 2000 Modified: 2000-08-24 16:08:30.543
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

The EJB API documentation is available from Sun's J2EE API documentation page.

When is the best time to use <ejb-link>? Do I have to use it everytime I


want to make a reference from an EJB to another EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=136512
Created: Aug 28, 2000 Modified: 2000-08-30 13:03:42.154
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by TH Lim
(http://www.jguru.com/guru/viewbio.jsp?EID=95720

[Questioner also submitted the following DD snippet:


<session>
...
<ejb-ref>
<ejb-ref-name>ejbAddress</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<home>AddressHome</home>
<remote>Address</remote>
<ejb-link>AddressEJB</ejb-link>
</ejb-ref>
...
</session>

<entity>
<ejb-name>AddressEJB</ejb-name>
<ejb-class>AddressBean</ejb-class>
<home>AddressHome</home>
<remote>Address</remote>
...
</entity>
] No - you don't have to use ejb-link every time you reference an enterprise bean
component. It allows an Application Assembler to reference an EJB by name without
the need to have unique names for all beans by constantly renaming them for the
J2EE application. And, ofcourse, such cannot be guaranteed if one buys third-party
bean components.

The example you have shown is one way that assumes the reference's EJB is in the
same ejb-jar file as the referencing bean. The other way is to use a path-name

<ejb-link>../customers/customer.jar#AddressEJB</ejb-link>

where the referenced bean is in a different jar file.

The Deployer is then responsible for binding the ejb-link references to the home of
the target bean.

Comments and alternative answers

What if the ejb we want to use/refer to is in another EAR?


Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Aug 7,
2002
How do you reference an ejb in another EAR? (mind you not in a different jar in the
SAME EAR, but an ejb in a DIFFERENT EAR altogether)
My answer is that(referencing or using an ejb in another EAR) is impossible because
another EAR will always have its own jndi tree. So we would be forced to have
duplicate classes in different EARs if we had to use a common ejb?

Re: What if the ejb we want to use/refer to is in another EAR?


Author: Vishal T (http://www.jguru.com/guru/viewbio.jsp?EID=1095449), Jul 21,
2003
Neal did you find out the answer to this question. I'm trying to write an EJB called
CommonMethods which is in another EAR as well and I wanted to know how I
can include it in all my EJB. Thanks for your help, Vishal T

Re[2]: What if the ejb we want to use/refer to is in another EAR?


Author: Kirill Fakhroutdinov
(http://www.jguru.com/guru/viewbio.jsp?EID=501201), Aug 27, 2003
J2EE 1.2, 1.3 specifications [see 5.3] clearly say: "allows to link an EJB
reference ... to an enterprise bean ... in the same J2EE application". So it is
clearly against J2EE specs to have EJB reference linked somehow to an EJB in
another EAR file.

Re[3]: What if the ejb we want to use/refer to is in another EAR?


Author: Kirill Fakhroutdinov
(http://www.jguru.com/guru/viewbio.jsp?EID=501201), Aug 27, 2003
But you still can use the global JNDI name of your EJB to locate and use it
from another application...

Re[4]: What if the ejb we want to use/refer to is in another EAR?


Author: Dirk Hogan
(http://www.jguru.com/guru/viewbio.jsp?EID=1168604), May 5, 2004
Yes, and I believe that this is the motivation for the <ejb-link> entry in
the first place: it allows ejb a to refer to ejb b (both in same .ear) even if
ejb b is not bound to the global JNDI tree (i.e. not available for general
consumption) via the app-server-specific deployment file.

Re[2]: What if the ejb we want to use/refer to is in another EAR?


Author: Sergey Manukyan
(http://www.jguru.com/guru/viewbio.jsp?EID=1151410), Mar 4, 2004
Folks, how about using service locator pattern in this case? As EJB link is a
kinda locates an EJB by some name for you, you can do it yourself in an
independent way through some config file.

Re: What if the ejb we want to use/refer to is in another EAR?


Author: Guru Radhakrishnan
(http://www.jguru.com/guru/viewbio.jsp?EID=1237197), Apr 7, 2005
Hi Friends, I was able to sucessfully call the EJB in another EAR from a Different
EAR in websphere. I created a ejb Client JAR from the called EJB Project in
WSAD( Or you can package the stubs manually if you are not using WSAD). I
added the Client JAR to the maifest class path in Calling EAR and Dropped it
under Calling EAR. I was able to access the EJB's services. That way you dont
have to rebuild the code when every time called EAR Changes due to reasons
anything apart from your interfaces. I have not tested this under clustered
environment. I deployed both the ears in the same node.

From R. Monson-Haefel's book on EJB I understand, that EJB clients that are
EJB's themselves, use a somewhat different (namingcontext-)lookup
method than 'regular' clients. But why ? Why the <ejb-ref> tag in the
deployment descriptor and why the 'java:comp/env' namespace ?
Location: http://www.jguru.com/faq/view.jsp?EID=136600
Created: Aug 28, 2000 Modified: 2001-01-25 20:45:47.599
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by murali krishna
(http://www.jguru.com/guru/viewbio.jsp?EID=89398

The short answer is that the extra layer of indirection gives flexibility. Remember that
the container is supposed to give you the ability to map each bean into a fairly
arbitrary place in the JNDI namespace. Since the ejb-ref tag allows you to indicate
the interface you're interested in and the JNDI name that its home will be bound to,
the Deployer can make different decisions about these things than the Bean
Developer did.

As an example, suppose an industry group defined a set of standard EJB interfaces


for, say, HR applications. Different vendors would implement EJB suites that
implemented these interfaces, and J2EE applications that used them. If the beans
were written using the <ejb-ref> tag, rather than 'knowing' one another's JNDI
names (which can be done, by the way), you could, theoretically, mix and match
EJBs and applications to build a solution that best fits your company, simply by
changing mappings. Of course, this is theoretical: at this stage of the technology, I'd
be really surprised if everyone involved actually did things 'right'.

The java:comp/env namespace was put into the 1.1 spec to simplify this and a
couple of other things. Putting all of these mappable elements under a consistent
JNDI context helps to ensure interoperability by encouraging consistency. Note that
this can also be used for things like global settings for a bean (say a threshold of
change to a salary that may only be done by someone in the 'HR Manager' role).

This all makes the most sense when you remember that EJB (and J2EE as a whole) is
a Component specification: since each of these things is a component, it should be
configurable to work with other components without code changes.

Note also that recent J2EE specs have implied that the client should be getting
references in much the same way. In fact, the 1.3 spec (available from javasoft.com
as a public draft) indicates that the application client deployment descriptor can
include <ejb-ref> stanzas

Comments and alternative answers

ejb reference
Author: pramod talesara (http://www.jguru.com/guru/viewbio.jsp?EID=1067448),
Mar 18, 2003
I am still not clear about ejb reference.Can any one explan me with some example.

Is there any default cache management system with Entity beans ? In other
words whether a cache of the data in database will be maintained in EJB ?
Location: http://www.jguru.com/faq/view.jsp?EID=136858
Created: Aug 28, 2000 Modified: 2000-11-05 16:12:24.651
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Karthikeyan Natarajan
(http://www.jguru.com/guru/viewbio.jsp?EID=129334

Caching data from a database inside the Application Server are what Entity EJB's are
used for.

The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean
state with the persistent storage(database).

Transactions also play an important role in this scenario. If data is removed from the
database, via an external application - your Entity Bean can still be "alive" the EJB
container. When the transaction commits, ejbStore() is called and the row will not
be found, and the transcation rolled back.

Comments and alternative answers


I wrote a simple CMP entity bean that maps to one...
Author: steven liu (http://www.jguru.com/guru/viewbio.jsp?EID=120740), Sep 1,
2000
I wrote a simple CMP entity bean that maps to one table in MSSQL7. I find that it
(EJB , ias ? ) will access the database everytime when I call any methods of that EJB.
I think that is because of transaction. But I can only choose 'Required', 'RequiresNew'
or 'Mandatory' for the transaction attribute. If I try to select others, the verify will fail.

My question is that: my CMP entity bean seems to work without any cache , what is
wrong ? ( My environment is IAS on windows and SQL7.0 . Thanks .)

Architecturally speaking, under what circumstances must I consider adding


EJB into the mix when building web-based applications using servlets and
JSP?
Location: http://www.jguru.com/faq/view.jsp?EID=137169
Created: Aug 28, 2000 Modified: 2000-08-28 21:39:26.129
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

The following thread within the Server-side discussion forum at Javaworld offers
some concrete guidelines as to when to add EJB into the mix when designing large
web-based applications.

Can I use the latest version of Tomcat inside Sun's J2EE implementation?
Location: http://www.jguru.com/faq/view.jsp?EID=140438
Created: Sep 1, 2000 Modified: 2000-09-06 13:47:18.86
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

The J2EE reference implementation ships with Tomcat. The classes for Tomcat are
located inside the \lib\j2ee.jar. If you wanted to use the latest version of Tomcat you
would have to replace the classes in this archive.

This would of course not be supported.

[Does anyone have experience/advice about updating this JAR? -Alex]

Does the EJB specification allow for such products as the Java Cryptography
Architecture (JCA) and other security APIs, to be used from within session
beans? What are the potential issues that would need to be addressed from
doing this?
Location: http://www.jguru.com/faq/view.jsp?EID=201418
Created: Sep 8, 2000 Modified: 2000-09-11 09:21:33.378
Author: Ron Kurr (http://www.jguru.com/guru/viewbio.jsp?EID=132270) Question
originally posed by Benjamin McCartney
(http://www.jguru.com/guru/viewbio.jsp?EID=109357

I don't believe the specification talks about using any of the crypto APIs or
frameworks. The spec talks about restricting access to particular methods on a bean
and that is handled by the container using information encoded in the deployment
descriptor. If you are just talking calling some crypto APIs, I can't think of anything
that would prevent you from doing cryto work from inside a session bean. Once you
are inside a bean, you can pretty do whatever you want, with just a few exceptions.
Comments and alternative answers

The 'exceptions' mentioned above are listed in section...


Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362), Sep
12, 2000
The 'exceptions' mentioned above are listed in section 18.1.2 of the EJB 1.1
specification under the heading - 'Programming Restrictions'

Can the bean class which implements either javax.ejb.EntityBean or


javax.ejb.SessionBean be inherited from any other class?
Location: http://www.jguru.com/faq/view.jsp?EID=201831
Created: Sep 10, 2000 Modified: 2000-09-11 09:24:29.398
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Harpreet Bakshi
(http://www.jguru.com/guru/viewbio.jsp?EID=104226

Yes it can, refer to the following sections of the EJB 1.1 specification:
Session Beans (Section 6.10.2)

The session bean class may have superclasses and/or superinterfaces. If the session
bean has superclasses, then the business methods, the ejbCreate methods, the
methods of the SessionBean interface, and the methods of the optional
SessionSynchronization interface may be defined in the session bean class, or in any
of its superclasses.

Entity Beans (Section 9.2.2)

The entity bean class may have superclasses and/or superinterfaces. If the entity
bean has superclasses, the business methods, the ejbCreate and ejbPostCreate
methods, the finder methods, and the methods of the EntityBean interface may be
implemented in the enterprise bean class or in any of its superclasses.

Keep in mind that the superclass must adhere to the rules and restrictions set out in
section 18.1.2 of the specification.

Is there a profiler application that runs with BEA Weblogic App Server
(v4.51) so that I can monitor my EJB's and server-side Java classes?
Location: http://www.jguru.com/faq/view.jsp?EID=201936
Created: Sep 10, 2000 Modified: 2000-09-11 09:28:25.547
Author: shilpa Tiwari (http://www.jguru.com/guru/viewbio.jsp?EID=138841)
Question originally posed by Ashok Nair
(http://www.jguru.com/guru/viewbio.jsp?EID=12502

Intuitive Systems Inc 's OptimizeIt is a profiler application that integrates with many
application servers including WebLogic 4.5.1.
OptimizeIt basically has an audit program running within WebLogic's VM once it is
integrated with WebLogic (this integration involves changes to the weblogic's policy
file and the weblogic's start script).

The OptimizeIt client ( user interface) then attches to this audit system which is
tracking the weblogic VM. This way you can attach to the weblogic server and see
the profiling information through the GUI. OptimizeIt also provides for distributed
profiling wherein you can attach to optimize its audit system running in a remote
machine's Virtual Machine (VM).

You can find the details and download the product from http://www.optimizeit.com

Is there any reason why value objects cannot have set methods?
Location: http://www.jguru.com/faq/view.jsp?EID=204044
Created: Sep 12, 2000 Modified: 2000-09-12 18:47:36.947
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Alan Josephson
(http://www.jguru.com/guru/viewbio.jsp?EID=19134

Alan's original question (in full) was:


The J2EE spec strongly recommends the use of Value Objects (simple, structure-like
classes) for passing data back and forth between EJBs and EJB clients. These objects
are characterized by get methods for accessing class variables and the use of
wholesale constructors. Is there a technical reason why these objects cannot have
set methods? Or is it purely to reinforce the notion that I am not directly interacting
with an EJB object? Specifically, I would like to get a value object from an EJB
method, update some of the data, and ship it back. Of course, value objects are
necessarily serializable.
In my opinion, he answered his own question: value objects may contain any
methods you like, including setters. It's just Java. In fact, I usually provide setters
for mine. If anyone knows of a reason not to, please submit feedback.
Comments and alternative answers

We are currently doing a big EJB development and all...


Author: chris hunter (http://www.jguru.com/guru/viewbio.jsp?EID=16315), Sep 13,
2000
We are currently doing a big EJB development and all our value objects (models)
have setters as well as sets in the constructor. We also provide an empty constructor
that creates an empty value object which we can then use the setters to populate.
Where a value object has a large number of properties but only a few need to be set,
this keep the code cleaner - its easier than haveing 20-30 nulls in the constructor.

Chris Hunter System Dynamics Ltd www.System-Dynamics.co.uk

Re: We are currently doing a big EJB development and all...


Author: Arun Balaji (http://www.jguru.com/guru/viewbio.jsp?EID=119257), Aug
10, 2001
Chris wrote:
"this keep the code cleaner - its easier than haveing 20-30 nulls in the constructor"
You could have overloaded versions of the constructors : - A protected version to
be used by the engine - and a public one to be used by the client.

Value objects are recommended when data has to be ...


Author: Paul Done (http://www.jguru.com/guru/viewbio.jsp?EID=94469), Sep 14,
2000

Value objects are recommended when data has to be returned from an EJB server to
the EJB client, if none of the data has to be updated. ie. The value objects are used to
transport read-only data.

It is the equivalent of the client requesting XML from the server tier, except you get
the tighter compile time binding and control, and you don't have to parse the returned
XML.

If, instead, an equivalent EJB reference with the same 'getter' methods is returned,
then each time the client calls a getter method on the reference EJB, this results in a
remote method call to the server tier. This is an uneccessary round trip, when the
object could have held the data locally itself.

So basically, value objects are recommended to enable your multi-tier application to


be more performant.

If you do need to update data, then you may need to use an EJB reference instead.
However, this fine grained querying/updating of data could become a severe
performance bottleneck, if lots of it is performed. The traffic between different tiers
needs to be minimised. Instead, EJBs should be used by clients for more coarse
granied method invocations.

For example, the client could call a session bean on the server to get a complex data
set (encapsulated in a value object), instead of just 1 row of data from 1 table. The
server session bean may have used many entity beans or jdbc directly, behind the
scenes on the server tier, however, this is hidden from the client. Once the client
recieves the complex value object, it can do as many local method calls, as it likes on
it to get the data. Then a new (or the same) object could then be constructed with all
the updated data. The client would then pass this object back to the server, to perform
the update, by calling the appropriate method on the remote session bean, passing the
new value object as the parameter.

EJB/RMI is sometimes touted as a way to write a multi-tier application, as if it is a


single tier application , without having to architect your design to cope with cross-tier
communications. In reality, though, any design has to compromise to take account of
these cross-tier performance issues.
See http://www.monson-haefel.com/ejbtips/ejbtip_2....
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 28, 2000
See http://www.monson-haefel.com/ejbtips/ejbtip_2.html

Can an EJB send asynchronous notifications to its clients?


Location: http://www.jguru.com/faq/view.jsp?EID=206459
Created: Sep 14, 2000 Modified: 2000-09-14 19:43:44.527
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Paul Chuang
(http://www.jguru.com/guru/viewbio.jsp?EID=132238

[. e.g. the client displays alarm status of devices. If I use EJB to periodically check
the database for alarm status change, how to program the EJB to forward notification
to clients when the status is changed? ]

Asynchronous notification is a known hole in the first versions of the EJB spec. The
recommended solution to this is to use JMS, which is becoming available in J2EE-
compliant servers.

The other option, of course, is to use client-side threads and polling. This is not an
ideal solution, but it's workable for many scenarios.

See also OK, so EJB doesn't support user-created threads. So how do I perform tasks
asynchronously? .

Is it better to use JRUN Connection Pooling or native Connection Pooling?


Location: http://www.jguru.com/faq/view.jsp?EID=207119
Created: Sep 15, 2000 Modified: 2000-09-17 14:14:23.557
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by chuck lyons
(http://www.jguru.com/guru/viewbio.jsp?EID=136859

As quoted by Allaire:
When Not to Use JRun Connection Pooling

If the JDBC driver that you are using already supports the JDBC 2.0 Connection
Pooling, Allaire recommends not using the JRun Connection Pooling mechanism for
that driver. The vendor is probably able to leverage database-specific features when
pooling that are much more efficient and/or robust than a generic connection pool
could provide."

See this link:


http://www.allaire.com/handlers/index.cfm?ID=17266&Method=Full&Title=JRun%20
3%2E0%20Connection%20Pooling&Cache=False

Should I use CMP or BMP for an application with complex data manipulation
& relations?
Location: http://www.jguru.com/faq/view.jsp?EID=208299
Created: Sep 17, 2000 Modified: 2000-09-17 15:44:33.499
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by srinivasa rao
(http://www.jguru.com/guru/viewbio.jsp?EID=139339

Generally, you should use CMP unless you're forced to use BMP due to limitations of
the mapping tools. Also, "complex" is relative; some relatively complex data models
can be captured with mapping tools, but some cannot.

(Please submit feedback if you disagree :-) )

Comments and alternative answers

I'd be cautious about CMP at this point (EJB 1.1 spec):...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Sep 20, 2000
I'd be cautious about CMP at this point (EJB 1.1 spec): different containers have
vastly different capabilities and make vastly different assumptions. If you know that
you're going to stay with a particular container for the forseeable future, and you
know that it will support your level of complexity, you should be mostly safe.
Container CMP implementation will still throw you for a loop or two, but if you don't
need portability between containers you should be able to work around these things.

Can I combine two or more finder functions with AND or OR operator to get
one result collection?
Location: http://www.jguru.com/faq/view.jsp?EID=208328
Created: Sep 17, 2000 Modified: 2000-09-17 15:56:16.053
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Seong Jin Cho
(http://www.jguru.com/guru/viewbio.jsp?EID=141453

You'd have to do that sort of thing on the client side. Naturally, since find* methods
can return many different types of Java objects, you'd have to write custom code
based on the signature of the particular methods you used. Easiest would be if your
find methods returned java.util.Set or java.util.List; you could then addAll() them
both to a java.util.Set for OR, and write a simple loop for AND, like
List result1 = bean.findBySomething();
List result2 = bean.findBySomethingElse();
Set resultAnd = new HashSet();
for (Iterator i = result1.iterator(); i.hasNext(); ) {
Object x = i.next();
if (result2.contains(x)) {
resultAnd.add(x);
}
}

For session beans, we can use the SessionSynchronization interface. For


entity beans, how do we have control over a transaction?
Location: http://www.jguru.com/faq/view.jsp?EID=208599
Created: Sep 17, 2000 Modified: 2000-09-18 00:18:03.278
Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040)
Question originally posed by Parag Bhagwat
(http://www.jguru.com/guru/viewbio.jsp?EID=52244

The SessionSynchronization interface is used by the Session beans to Synchronize


the Instance variables after a rollback or after a commit operation, because container
does not have any other way to inform the bean of these operations.

With Entity beans, this is not a problem as the Container automatically calls the
ejbLoad method that refreshed the values from the database.

I hope it clarifies the doubt.

Can I set the data represented by the BMP Entity Bean to null in ejbStore,
once it's updated in the database?
Location: http://www.jguru.com/faq/view.jsp?EID=211129
Created: Sep 20, 2000 Modified: 2000-09-20 11:12:03.969
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Prashant Altekar
(http://www.jguru.com/guru/viewbio.jsp?EID=207066

[Question continues:
Every business method is always called after an ejbLoad. Therefore the bean has no
reason to hold on to the memory for the data between an ejbStore and subsequent
ejbLoad. This becomes important when such data is huge and the bean is accessed
infrequently. ]

Theoretically, you could set your data to null after ejbStore, unless your container
implements a caching optimization that skips ejbLoad in some cases (even then you
could turn it off)

However, the purpose of the EJB specification is to allow application programmers


(Bean Providers, in your case) to operate in blissful ignorance of resource and
transaction management concerns. A well-written container will swap unused beans
out if neccessary. In fact one instance of your entity bean implementation class
might be used to represent one logical entity (say with primary key value '1234') in
one transaction and another logical entity (primary key value '5678') in the next
transaction a couple milliseconds later. Because of this, it is rather important that
your ejbLoad method initialize all fields, to avoid side-effects.

Having said this, the real answer is "Go ahead, but don't worry about it unless 'huge
data' means multi-megabyte stuff"

Which application server is best for EJB deployment? [Go crazy, folks: I
expect a nice flame war on this one :-) -A]
Location: http://www.jguru.com/faq/view.jsp?EID=211362
Created: Sep 20, 2000 Modified: 2000-09-21 10:13:57.496
Author: Ravi kalidindi (http://www.jguru.com/guru/viewbio.jsp?EID=41528)
Question originally posed by Tariq Mahmood Gill
(http://www.jguru.com/guru/viewbio.jsp?EID=29492
Weblogic is definitely better among other servers.i worked on weblogic and
websphere.weblogic is best for deployment.i am hearing that Iplanet server too
giving lot of troubles.
ravi kalidindi
Comments and alternative answers

Gemstone J is the premiere application server. We have...


Author: Ike Kotlyarsky (http://www.jguru.com/guru/viewbio.jsp?EID=46599), Sep
22, 2000
Gemstone J is the premiere application server.

We have evaluated numerous application servers, including WebLogic, Inprise and


WebShpere. When it comes to deploying enterprise applications and when scalability
, fault tolerance and high availability are the issues Gemstone by far is the winner.

It's a shame an IBM can call their product an Application server. It is nothing more
than a Servlet engine which you have to bring down every 8 hours dew to the Naming
services failures. No wonder they giving it away for free. Well it is not for free. The
big blue still finds the way to back stab their client by charging consulting fees for a
failure of a product.

Re: Gemstone J is the premiere application server. We have...


Author: me x (http://www.jguru.com/guru/viewbio.jsp?EID=505632), Sep 27,
2001
Gemstone is year(s) behind the J2EE specification, deployment and development
are painfully slow, bugs take a long time to be fixed, and the app server (for Java
at least) is no longer supported. But other than that.... it sucks.

http://www.jboss.org, nuff said.


Author: Bruce Durling (http://www.jguru.com/guru/viewbio.jsp?EID=4932), Sep 22,
2000
http://www.jboss.org, nuff said.

My vote is for BEA Weblogic server. I am working with...


Author: girish bhatia (http://www.jguru.com/guru/viewbio.jsp?EID=27703), Sep 27,
2000
My vote is for BEA Weblogic server. I am working with weblogic since last 2 years
and have pretty much developed a preference for this server. with release 5.1, it
support the xml deployment descriptor and provides a nice way of hot deploying the
beans without restarting the server. Webgain has added another plus with this app
server. I have not yet much worked with webgain, but seems that webgain and
weblogic combination is a wining combination for web development. -Girish Bhatia

Yeh i also prefer Weblogic server for deployement ...


Author: rama mohan gupta (http://www.jguru.com/guru/viewbio.jsp?EID=123355),
Sep 28, 2000
Yeh i also prefer Weblogic server for deployement purpose that other present
application servers available in the market. But according to me Websphere is also
good for serverside transactions.

I would use anything BUT Websphere. Websphere (3.02)...


Author: Peter Abelsson (http://www.jguru.com/guru/viewbio.jsp?EID=49686), Oct 2,
2000
I would use anything BUT Websphere. Websphere (3.02) administration is a mess,
everything you do in the administration interface is painfully slow. I can't understand
how IBM actually charges money for such an imature and buggy product, they should
be ashamed. If people complain about Microsoft releasing buggy products they
should give Websphere a try and they will consider Micorosft products virtually
buggfree. The only reason you would use Websphere is if higher management was
fooled into buying it by IBM-sales. Use Weblogic, Orion (www.orionserver.com),
Allaire Jrun, jBoss or anything else. Don't be fooled by big blue.

Which application server is best for EJB deployment?...


Author: Michael Taylor (http://www.jguru.com/guru/viewbio.jsp?EID=19453), Nov
3, 2000
Which application server is best for EJB deployment? Not JRUN3.0. I've been
evaluating this Application Server for a week. It is absolutely impossible. Being
entirely html based, you are completely left with editting property files and xml by
hand (if you know which ones to edit). The documentation does not help much either.
You have to browse through their example codes to discover required vender specific
property file settings. JRUN3.0 doesn't even have a simple xml deployment descriptor
tool. Even JBOSS gives you that and its free! In conclusion, this is a cheap, you get
what you pay for, application server. Use anything else...

Cretainly IBM WebSphere is not the right server for...


Author: SivaKumar Parthasarathy
(http://www.jguru.com/guru/viewbio.jsp?EID=269373), Dec 6, 2000
Cretainly IBM WebSphere is not the right server for deploying EJB's. I am having
troubles locating correct documentation on deployment in WebSphere.

Java:API:EJB:Products Best Application Server


Author: Anand Gopal (http://www.jguru.com/guru/viewbio.jsp?EID=429707), May
28, 2001
Weblogic & Websphere both are good for deployment ..I worked on these servers &
NAS (Netscape Application Server ) also .. If u want only good deployment then
Weblogic is slightly better than Websphere ., If u want good deployment plus good
debugger then choose Websphere .... NAS is pretty slow compare to these above
servers ... for LDAP, NDS is better .. for Web sever also Netscape product NES is
better ...

Re: Java:API:EJB:Products Best Application Server


Author: Praveen AB (http://www.jguru.com/guru/viewbio.jsp?EID=1120460), Oct
8, 2003
I have been working on WEBLOGIC since 3 years. I have worked on weblogic
version 5.1 onwards. According to me no other application server till today can
beat weblogic. Its deployment and performance are wonderful. The latest
weblogic workshop is also good. I have worked on IBM Websphere as well as
JBoss. They are ok only.

Re[2]: Java:API:EJB:Products Best Application Server


Author: sudhakar p R (http://www.jguru.com/guru/viewbio.jsp?EID=1224404),
Jan 31, 2005
I think deployment on Weblogic 6.1 is extremely easier compared to
websphere.websphere admin console is certainly crap..weblogic is way ahead
of websphere in admin console..its pretty fast,eeasy and more important,
intuitive!Well, Jrun asfar asi know , its doedesont qualify to be called an app
server.it sucks!!

I want to access a session EJB deployed on a Websphere 3.02 from the web
container of a Weblogic 4.51 Server. Both servers are running on machines
behind the firewalls of two different corporate networks. What are the
viable solutions here?
Location: http://www.jguru.com/faq/view.jsp?EID=215121
Created: Sep 25, 2000 Modified: 2000-09-28 19:26:28.397
Author: Shyam L (http://www.jguru.com/guru/viewbio.jsp?EID=29689) Question
originally posed by Peter Makumbi
(http://www.jguru.com/guru/viewbio.jsp?EID=57706

You deploy the EJB on the Websphere server and include the deployed EJB jar file in
the classpath of the client on the Weblogic server. All other things remain the same.
Comments and alternative answers

I want to comment on the answer by Shyam L. Syham...


Author: Peter Makumbi (http://www.jguru.com/guru/viewbio.jsp?EID=57706), Oct 2,
2000
I want to comment on the answer by Shyam L.

Syham says that you simply deploy on Websphere (WS) and access from Weblogic
(WL). It is simple to see that this won't work. WS 3.02 and WL 4.5.1 use different
JNDI RMI SPI impelementations. WS uses an IBM implementation based on IIOP,
whereas WL uses the propriatary T3 Protocol. So this can only work if you use the
IBM JNDI implementation on the WL server. But once again you will later have
problems with getting RMI over IIOP through the corporate firewalls. So My original
question actually poses two questions.

Pemak

Re:I want to comment on the answer by Shyam L. ..


Author: rajesh kohir (http://www.jguru.com/guru/viewbio.jsp?EID=470184), Sep
19, 2001
Hi Peter, Have u got the solution for ur problem?. i am also facing samr problem.
My Servlets sits on iPlanet Web Server and EJB on Web Logic. Now i have to call
EJB fuctions from servlet. it is failling at lookup() function and saying class not
found Exception. Kindly Please Provide Answer as soon as possible. my email id
:Kohir_rajesh@yahoo.com -Rajesh Kohir

To Peter Makumbi
Author: Rajesh S (http://www.jguru.com/guru/viewbio.jsp?EID=460704), Jul 24,
2001
I am facing the same problem as described by you. Did you find any answers for the
question. If so could you please provide me the solution in this forum. You can also
email be at s_rajesh75@yahoo.co.in.

You can't access EJB's across firewall


Author: Raees Uzhunnan (http://www.jguru.com/guru/viewbio.jsp?EID=281081), Feb
14, 2002
You can't access EJB's across firewall, They work on IIOP protocol. You may have to
introduce SOAP to your architecture to facilitate object access across firewalls

When I try to run J2EE SDK Deploytool.bat it doesn't start and gives:
Exception in thread "main" java.lang.NullpointerExcception. How can I fix
this?
Location: http://www.jguru.com/faq/view.jsp?EID=217722
Created: Sep 28, 2000 Modified: 2000-09-28 19:20:31.021
Author: raviprolu pavan kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=217700) Question originally posed by
Vicky Jain (http://www.jguru.com/guru/viewbio.jsp?EID=134906

Maybe I can tell you some points which you have to remember while using
deploytool. These steps maybe helpful to anybody using the tool.

1. When first running the deploytool set the JAVA_HOME and J2EE_HOME. Maybe
you have done this. In case you did not do then you have to set the Homes.

2. If you get 'out of environment space' then adjust the environment space in the
DOS window

3. Once you have opened the UI and used it, and you are about to close it, make
sure that 'No applications are open'. All applications should be closed. Otherwise if
you close the UI with some applications open, next time you cannot open the tool.

I think this is your problem.

If in case this is your problem follow these steps,


i) cleanup all the deployed applications
ii) uninstall J2EE
iii)remove the directory after backing up your work
iv) install J2EE again
v) copy back your backup into j2ee
The process is cumbersome. So avoid any open applications on the deploytool UI
before exiting deploytool. I hope Sun will correct this bug soon.

Comments and alternative answers

You may like to try and rename the folder where you...
Author: Munusamy Shanmugavelu
(http://www.jguru.com/guru/viewbio.jsp?EID=228254), Oct 13, 2000
You may like to try and rename the folder where you have saved the application .ear
files and start the deploytool again

What is an intermediate data access object and what are the advantages
and disadvantages of using it?
Location: http://www.jguru.com/faq/view.jsp?EID=217790
Created: Sep 28, 2000 Modified: 2000-09-28 19:29:19.386
Author: WEICONG WANG (http://www.jguru.com/guru/viewbio.jsp?EID=217785)
Question originally posed by pradeep patra
(http://www.jguru.com/guru/viewbio.jsp?EID=40386

Check http://www.monson-haefel.com/ejbtips/ejbtip_2.html
Comments and alternative answers

Um, that's describing a "value object" or...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 28, 2000
Um, that's describing a "value object" or "bulk accessor," which *might* be the same
thing as an intermediate data access object. I'd also think that an object that contains
JDBC calls (for example) would also fit that term.

Re: Um, that's describing a "value object" or...


Author: Arun Balaji (http://www.jguru.com/guru/viewbio.jsp?EID=119257), Aug
10, 2001
I am not sure why WEICONG WANG has posted the link for a Bulk Accessor
a.k.a Value Object

Value Object (VO) and Data access object (DAO) are two distinct patterns - they
serve different purposes.

A VO is a simple wrapper to send coarse grained data across the network


efficiently (instead of many fine grained getters which are costly.)

A DAO is designed to remove SQL logic from a BMP to a stand alone class to
abstract different data sources.
You could also reuse this DAO class to access it from a Session bean ;-)

See the J2EE design Pattern catalog for details:


http://java.sun.com/j2ee/blueprints/design_patterns/index.html

What happens when a client calls an entity bean's home interface create()
method and an entity bean already exists with that primary key, created
previously by another client ? Also what happens when a client calls an
entity bean's home interface findByPrimaryKey() method and an entity bean
does not already exist with that primary key ?
Location: http://www.jguru.com/faq/view.jsp?EID=218876
Created: Sep 29, 2000 Modified: 2000-10-03 10:27:35.489
Author: Anil Datt (http://www.jguru.com/guru/viewbio.jsp?EID=20887) Question
originally posed by paul martin
(http://www.jguru.com/guru/viewbio.jsp?EID=200835

If the primary key already exists DuplicateKeyException is thrown, i.e if your


Create method is defined to throw a CreateException, CreateException is thrown.
DuplicateKeyException is the sub class of CreateException.

For findByPrimarykey ObjectNotFoundException is thrown, i.e if your


findByPrimarykey method is defined to throw a FinderException, FinderException
is thrown. ObjectNotFoundException is the sub class of FinderException.

What is the difference between session and entity beans? When should I
use one or the other?
Location: http://www.jguru.com/faq/view.jsp?EID=221545
Created: Oct 3, 2000 Modified: 2000-10-03 10:09:38.175
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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).

Please see What is an entity bean? and What is a session bean? for more
information.

Is it possible to use EJB in architecting a multi-user collaborative


application? If so, how might it work, and what are some pitfalls to avoid?
Location: http://www.jguru.com/faq/view.jsp?EID=221563
Created: Oct 3, 2000 Modified: 2000-10-03 10:40:23.059
Author: Ron Kurr (http://www.jguru.com/guru/viewbio.jsp?EID=132270) Question
originally posed by Troy Echols
(http://www.jguru.com/guru/viewbio.jsp?EID=56375

EJBs are useful in a variety of situations. If you wish to build your application using
components, require transactions, or don't wish to manage some of the basic
infrastructure needed for a server (such as thread and connection pooling), then an
EJB container may be the way to go.

I think the first step is to decide which EJB spec you want to design against. EJB 1.0
and EJB 1.1 have some differences that you might want to account for in your
design. Collaboration implies to me that some database persistence is needed. You'll
need to decide if you should use entity beans to fill that role. If you need pub-sub
notification or point-to-point message queues, you'll need to verify that the JMS and
EJB vendors can operate together transactionally. Although the EJB spec does
"gurantee" a certain amount of standarization between vendors, you'll still find
differences between containers. You might want to build an abstraction that can help
isolate you from those differences. Your build process will also need to account for
the different EJB tools that each vendor supplies.

If you are sure that you'll never switch EJB vendors, you can probably ignore the
previous advice. If you try to be vendor agnostic, however, be aware of some of the
neat things that vendors give you that isn't part of the spec, such as clustering.

If scaling is an issue, try to be as stateless a possible. Using Stateless Session beans


is helpful in that area. Finally, your developers must be fully aware that their EJBs
will be operating in a multi-threaded environment and code accordingly. Too much
synchronization will slow down the system and not enough may corrupt it. Developer
education and debugging/analysis tools can help in that area. Threading is hard to
get right and it doesn't help that each platform's thread scheduling can behave
differently (such as NT vs. Solaris).

Is it possible to use container-managed persistence and take advantage of


database triggers and sequences to populate the primary key? If so are
there any good examples?
Location: http://www.jguru.com/faq/view.jsp?EID=221605
Created: Oct 3, 2000 Modified: 2000-10-03 10:41:24.739
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Paul Osborne
(http://www.jguru.com/guru/viewbio.jsp?EID=126223

I'll talk about sequence type mechanisms first: triggers probably won't work for
reasons I'll discuss later.

The technique you'd want to use would be to retrieve your new key value in your
ejbCreate method(s) and assign it to the appropriate field in your bean. That way the
CMP mechanism in the container can pick it up and will have an identity for your
bean. Note that your ejbCreate method needs to return an instance of your primary
key class (in EJB 1.1 - if you're still at 1.0, consider a different container)

You should be able to get your value with a little bit of BMP looking code: get the
DataSource from JNDI (ctx.lookup("java:comp/env/jdbc/MyConnection") type
things), get a Connection from the DataSource, then execute the SQL ("SELECT
myseq.nextval from dual" if i remember Oracle correctly). Remember to close the
connection to ensure taht it is re-pooled properly.

Triggers probably won't work (assuming you were going to use them to assign values
to the primary key columns directly). This is because most containers really, really
think they need to know the value of your primary key ahead of time, largely (I
believe) to make sure that their cache is right, but also because they really need to
explicitely check for key-violations themselves so that they can throw
DuplicateKeyException (catching and interpreting the SQLException from the JDBC
driver would be vendor dependent and would also have to assume that the primary
key columns are actually defined as primary keys - not a safe assumption for a
container to make, unfortunately)

By the same token, you'll not be able to get your CMP container to emit SQL that hits
your sequence within the insert statement: it requires assumptions that container
developers just can't make (like the existence and syntax of your RDBMS' sequence
feature, as well as all of the above).

Comments and alternative answers

Are you sure ?


Author: Jeff Halleux (http://www.jguru.com/guru/viewbio.jsp?EID=443307), Jul 24,
2001
Section 9.4.2 of the EJB Spec states : ...the implementation of the ejbCreate(...)
methods should be coded to return null. The returned value is IGNORED by the
Container.

JFH

Can my ejbFind methods have return types like RowSet or Vector, or should
it be only of type Enumeration?
Location: http://www.jguru.com/faq/view.jsp?EID=222462
Created: Oct 4, 2000 Modified: 2000-10-06 22:06:36.259
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Prashanthi Pokala
(http://www.jguru.com/guru/viewbio.jsp?EID=215308

The 1.1 spec. says that ejbFindXXX methods must return either a primary key or a
collection of primary keys, and refers to the section (9.1.8) where the return types of
home interface finder methods is defined. This specifies either Enumeration or
Collection. Since, in Java 2, Vector implements Collection, you should be able to
return a vector, but given the restriction in section 9.1.8, you will probably have to
declare your return type as Collection. Declaring Vector as your return type might
work in some containers, but I wouldn't expect it to be portable.

Returning RowSet will just not work. as the container will not know what to do with
it.

Comments and alternative answers

Can my ejbFind methods have return types like RowSet or Vector, or should it
be only of type Enumeration?
Author: Parag Bharambe (http://www.jguru.com/guru/viewbio.jsp?EID=741714), Feb
6, 2002

Suppose I have an option of using vector and Enumerator for finder query which
return me multiple queries? Which one will give me better performance?

Suppose multiple records are retrived from Database. Is it Application server cache
the retrived data , or each record is fetched from Oracle database cache?

Is there any performance problem with calling one EJB from another EJB
running in the same container?
Location: http://www.jguru.com/faq/view.jsp?EID=222470
Created: Oct 4, 2000 Modified: 2000-10-06 22:24:36.278
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by gurdeep singh
(http://www.jguru.com/guru/viewbio.jsp?EID=215882

There are two potential performance issues here, one of which has been eliminated
by most (if not all) container vendors, and the other of which many container
vendors have optional optimization for.

The first issue is that given naive implementations of the JNDI context objects that
the beans use to look each other up, the calls might go through RMI, which involves
quite a bit of overhead even within a process. Again, though most if not all container
vendors optimize this right out of your way. Don't worry about this one.

The second potential issue, though, comes from the spec. The EJB specification
dictates that the container copy all method parameters and return values on these
calls. Here is the quote from section 18.2.3: <quote> Specifically, the EJB Container
is not allowed to pass non-remote objects by reference on inter-EJB invocations
when the calling and called enterprise beans are collocated in the same JVM. Doing
so could result in the multiple beans sharing the state of a Java object, which would
break the enterprise bean’s semantics. </quote> All this copying has obvious
performance implications. However, most container vendors allow this behavior to be
overridden for performance reasons.

Is it possible to have a Container Managed Persistent Entity Bean which


refers to a view rather than a table.
Location: http://www.jguru.com/faq/view.jsp?EID=224680
Created: Oct 8, 2000 Modified: 2000-10-11 20:02:28.088
Author: Damien Bootsma (http://www.jguru.com/guru/viewbio.jsp?EID=222870)
Question originally posed by Madhu Menon
(http://www.jguru.com/guru/viewbio.jsp?EID=29982

Yes it is possible. Using Views is a good way of mapping multiple tables to one Entity
Bean.

Remember that you will also need to write a Primary Key class for your Entity Bean.
Refer to http://www.jguru.com/jguru/faq/view.jsp?EID=20875 for details.
Comments and alternative answers

if it is possible to create a bean for multiple tables...


Author: Banda Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=389958), Apr
5, 2001
if it is possible to create a bean for multiple tables, then, is it possible to do dml
(delete/insert/update) operations on this entity bean for multiple tables?? please
clarify ?

Re: if it is possible to create a bean for multiple tables...


Author: samson su (http://www.jguru.com/guru/viewbio.jsp?EID=232778), Apr 6,
2001
I think this depends, some database products allow you to update the underlying
data thru updating the view, but most not. I always use weblogic & cloudscape
(pooled by weblogic) to work. I found that i must clear the "update at the end of
each transaction" option in the "optimization" page in weblogic's EJB
DeployerTool. Otherwise I can do nothing, any operation, even a readonly one
such as findByPrimaryKey(), will generate an error saying "view is not
updatable". After clearing this option, readonly operations work well as I
expected.

What is a value object? Why would I use one? What are some problems with
them?
Location: http://www.jguru.com/faq/view.jsp?EID=224988
Created: Oct 9, 2000 Modified: 2000-10-11 19:47:53.853
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

A Value Object, aka a Bulk Accessor or Bulk Data Class, is a lightweight Java class,
separate from your EJB class, that contains properties or instance variables
corresponding to each of your EJB's properties.

Paul Done, in feedback to Is there any reason why value objects cannot have set
methods?, defined value objects very well:

Value objects are recommended when data has to be returned from an EJB server to
the EJB client, if none of the data has to be updated. ie. The value objects are used
to transport read-only data.

It is the equivalent of the client requesting XML from the server tier, except you get
the tighter compile time binding and control, and you don't have to parse the
returned XML.

If, instead, an equivalent EJB reference with the same 'getter' methods is returned,
then each time the client calls a getter method on the reference EJB, this results in a
remote method call to the server tier. This is an uneccessary round trip, when the
object could have held the data locally itself.
So basically, value objects are recommended to enable your multi-tier application to
be more performant.

If you do need to update data, then you may need to use an EJB reference instead.
However, this fine-grained querying/updating of data could become a severe
performance bottleneck, if lots of it is performed. The traffic between different tiers
needs to be minimised. Instead, EJBs should be used by clients for more coarse-
granied method invocations.

For example, the client could call a session bean on the server to get a complex data
set (encapsulated in a value object), instead of just 1 row of data from 1 table. The
server session bean may have used many entity beans or jdbc directly, behind the
scenes on the server tier; however, this is hidden from the client. Once the client
recieves the complex value object, it can do as many local method calls as it likes on
it to get the data. Then a new (or the same) object could then be constructed with all
the updated data. The client would then pass this object back to the server, to
perform the update, by calling the appropriate method on the remote session bean,
passing the new value object as the parameter.

EJB/RMI is sometimes touted as a way to write a multi-tier application, as if it is a


single tier application , without having to architect your design to cope with cross-tier
communications. In reality, though, any design has to compromise to take account of
these cross-tier performance issues.

One problem with using Value Objects is that they are indeed passed by value, not
by reference. If the data are updated on the server, a client may be accessing an
out-of-date value stored in his local copy of the value object. Furthermore, if you use
value objects to *store* data back on the server, you may inadvertently be reverting
changes to fields that you did not set, but that a different client changed in the
meantime.

Another is that it is simply annoying to write one! It's like, I just wrote all these
accessor methods on the *real* bean, and now I have to write them again on this
fake one! Also, as you upgrade your bean code, you need to remember to update
your value object code as well, leading to possible subtle migration bugs.

EJBDoclet is an open-source product from DreamBean Software than allows you to


generate various EJB-files from a commented bean source-file, including a bulk data
class. This somewhat mitigates the previous complaint.

See also:

• Is there any reason why value objects cannot have set methods?
• Tip 2 - Bulk Accessors in Entity Beans
• EJBDoclet

Can I use a Java 1.1 client to access an EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=227355
Created: Oct 12, 2000 Modified: 2000-10-18 18:14:41.027
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by Matze Schroeder
(http://www.jguru.com/guru/viewbio.jsp?EID=142150

This is dependant on the EJB Container that you are using.

All the EJB interfaces are Java 1.1 compatible. EJB's that are written to be used by
both JDK 1.1 and 1.2 should be aware of the differences between the two versions.
These are listed inside section 18 of the EJB 1.1 specification.

[RC - If you know of a container that can support JDK 1.1 clients, please
submit as feedback]

Comments and alternative answers

I know that WebLogic 4.51 will work with Java 1.1....


Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212),
Oct 19, 2000
I know that WebLogic 4.51 will work with Java 1.1. I have deployed an EJB
application with WebLogic 4.51 running as the EJB and Servlet container using Java
1.1.8b.

I am developing a BMP Entity bean. I have noticed that whenever I the


create method is invoked, the ejbLoad() and the ejbStore() methods are
also invoked. I feel that once my database insert is done, having to do a
select and update SQL queries is major overhead. is this behavior typical of
all EJB containers? Is there any way to suppress these invocations?
Location: http://www.jguru.com/faq/view.jsp?EID=228576
Created: Oct 14, 2000 Modified: 2000-10-17 15:40:36.652
Author: Parag Bhagwat (http://www.jguru.com/guru/viewbio.jsp?EID=52244)
Question originally posed by manikandan chandrasekaran
(http://www.jguru.com/guru/viewbio.jsp?EID=1532

This is the default behaviour for EJB. The specification states that ejbLoad() will be
called before every transaction and ejbStore() after every transaction.

Each Vendor has optimizations, which are proprietary for this scenario. We will
outline the properties for the popular servers below:

WebLogic 5.1

1. The db-is-shared option, which is set in the weblogic-ejb-jar.xml file.


This option by default set to true, but can be overridden. This option can be
used if the WebLogic Server has exclusive access to the database. Using this
option ejbLoad()will be called only once when the user obtains remote
interface and then after any transaction rollback. This cannot be used in a
cluster
2. The Cache Strategy option can be set to read-only. Using this strategy the
Container will never invoke ejbStore() and will limit calls to ejbLoad() as
specified by the read-timeout-seconds options. Both options are also set in
the weblogic-ejb-jar.xml file.
3. The is-modified-method-name option, which is set in the weblogic-ejb-
jar.xml file and is used to specify a method that the container will invoke
before ejbStore(). If this method returns true then ejbStore() will be
called, if it returns false, then it will not invoke ejbStore().

[RC - Please submit answers for other containers as feedback so we can provide a
complete list]
Comments and alternative answers

Passivate goes the same way


Author: Geraldo Xexeo (http://www.jguru.com/guru/viewbio.jsp?EID=524001), Jan
14, 2002
It seems to me that this happens also when passivating an BMP.

CMP Only
Author: Jeff Davenport (http://www.jguru.com/guru/viewbio.jsp?EID=842956), Apr
17, 2002
In WebLogic 6.x, the is-modified-method-name option only applies for CMP. It is not
allowed for BMP. I do not know if this is the case in WebLogic 5.1 as well.

Is it possible to derive my EJB class from a standard Java class?


Location: http://www.jguru.com/faq/view.jsp?EID=228911
Created: Oct 15, 2000 Modified: 2000-10-18 18:31:16.237
Author: Damien Bootsma (http://www.jguru.com/guru/viewbio.jsp?EID=222870)
Question originally posed by Amar Gadkari
(http://www.jguru.com/guru/viewbio.jsp?EID=142811

Yes it is possible. Although, naturally you must make sure that the methods of the
EntityBean or SessionBean interfaces (depending on which type of EJB you are
writing) are implemented either in the Bean class or its' superclasses.
When descending from an existing class, you should be aware of the EJB
programming restrictions outlined in section 18.1.2 of the EJB 1.1 specification. For
example, You must be careful not to extend from any of the java.io.* classes or
java.lang.Thread.

When are stubs & skeletons created for my EJB components? is it at


development time, deployment time or run time?
Location: http://www.jguru.com/faq/view.jsp?EID=230549
Created: Oct 17, 2000 Modified: 2000-10-17 15:57:57.913
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
Naveen Ajjampur (http://www.jguru.com/guru/viewbio.jsp?EID=127318

The time of creation of stubs and skeletions for EJB components varies from server
to server.

The creation of stubs and skeletons for the popular servers is outlined below:
Inprise Application Server 4.x
The stubs and skeletons can be created during development time, for development
and testing with the command line utility of with JBuilder. The stubs and skeletons
for the EJB can also be created during deployment using the IAS Console. There is
also an option to create a Client Jar file. The Client Jar file contains the necessary
stubs and interfaces for the EJB which a client requires to invoke the EJB.

WebLogic Server 4.5.x, 5.x


The stubs and skeletons are created at deployment time using the command line
utility called weblogic.ejbc. In WebLogic 5.x, there is also a Deployer Tool available
that will invoke the ejbc utility automatically.

jBoss Server
In jBoss, the stubs and skeletons are not required to be generated by the developer
or deployer. The Server takes care of the creation and downloading of stubs.

[RC- Please submit info for other servers as feedback]

Comments and alternative answers

No stubs and skeleton found in Weblogic 6.1


Author: Seetesh H (http://www.jguru.com/guru/viewbio.jsp?EID=1038574), Dec 17,
2002
Hi,
How are the stub and skeleton files created in Weblogic 6.1 at deployment/compile
time?
Seetesh

Creation of stubs and skeletons - WebSphere


Author: Dror Fries (http://www.jguru.com/guru/viewbio.jsp?EID=1234390), Mar 23,
2005
Hi, Can someone describe what happens for WebSphere ? Is there a way for the stubs
and skeletons to be created when deploying - automatically (by some setting or else) ?
or must I create them at development stage ? Thanks DrorF

Are there any online EJB tutorials?


Location: http://www.jguru.com/faq/view.jsp?EID=231621
Created: Oct 18, 2000 Modified: 2000-10-18 19:00:00.767
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
Ambika Palta (http://www.jguru.com/guru/viewbio.jsp?EID=227461

Take the jGuru Enterprise JavaBeans Technology Fundamentals short course at


http://developer.java.sun.com/developer/onlineTraining/EJBIntro

What is the default transaction attribute for an EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=232149
Created: Oct 19, 2000 Modified: 2000-10-26 06:47:01.737
Author: sailaja nadella (http://www.jguru.com/guru/viewbio.jsp?EID=225889)
Question originally posed by WEICONG WANG
(http://www.jguru.com/guru/viewbio.jsp?EID=217785

There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec
says that the deployer must specify a value for the transaction attribute for those
methods having container managed transaction.
Comments and alternative answers

Default transaction attribute for Enterprise java bean


Author: surya navi (http://www.jguru.com/guru/viewbio.jsp?EID=388862), Mar 27,
2001
In weblogic, the default transaction attribute for EJB is SUPPORTS.

Re: Default transaction attribute for Enterprise java bean


Author: Seetesh H (http://www.jguru.com/guru/viewbio.jsp?EID=1038574), Dec
17, 2002
Hi, Weblogic 6.1 has Required by default. Seetesh

Re[2]: Default transaction attribute for Enterprise java bean


Author: reji mohamed
(http://www.jguru.com/guru/viewbio.jsp?EID=1138612), Jan 12, 2004
for weblogic 8 it's SUPPORTS...i think it's the same with weblogic 7

Default transaction attribute for was 5.1.x


Author: Rakesh Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=1256795),
Aug 5, 2005
Can somebudy provide me the supporting doc or link for default transaction attribute
in Websphere 5.1.x .In WAS6.0 its "Required".

Is there any way to force an Entity Bean to store itself to the db? I don't
wanna wait for the container to update the db, I want to do it NOW! Is it
possible?
Location: http://www.jguru.com/faq/view.jsp?EID=232157
Created: Oct 19, 2000 Modified: 2000-10-26 06:35:49.787
Author: sailaja nadella (http://www.jguru.com/guru/viewbio.jsp?EID=225889)
Question originally posed by Stéphane Félix
(http://www.jguru.com/guru/viewbio.jsp?EID=210800

Specify the transaction attribute of the bean as RequiresNew. Then as per section
11.6.2.4 of the EJB v 1.1 spec EJB container automatically starts a new transaction
before the method call. The container also performs the commit protocol before the
method result is sent to the client.

What is the Session wraps Entity Pattern? What are the motivations behind
it?
Location: http://www.jguru.com/faq/view.jsp?EID=232943
Created: Oct 20, 2000 Modified: 2000-10-23 21:40:01.55
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by nadella srikanth
(http://www.jguru.com/guru/viewbio.jsp?EID=72838

This pattern is really just a quick way of saying "Clients access the system only
through Session Beans, which encapsulate all details of the system's Entity Beans."

From my perspective, there are two primary motivations for this: to provide good
transactional definition and improve performance, and to hide implementation details
by providing a coarse-grained interface to the system.

As far as transaction definition and implementation goes, this pattern helps by


allowing each call into the session beans to be a complete unit of work (AKA
transaction). In J2EE based systems where the client calls entity beans directly either
the client has to manage the transaction explicitely, or each call to an entity runs in
its own transaction. In the first case (client managed transactions) we wind up with a
lot of low-level exception handling code than we really want in application code. It
becomes difficult to ensure that these exceptions are being handled correctly
everywhere in an application (although good architecture can mitigate this risk). In
the second case (each call running in its own transaction) performance will suffer
greatly - most application servers will (by default) call ejbLoad at the beginning of
each transaction and ejbStore at the end of each transaction. If you have 10 getter
methods that must be called in a unit of work, that leads an incredibly slow system.
Another reason that this 'naive' design is bad is that if you are modifying data, there
is probably some set of data that the user expects to be modified as a unit (a unit of
work). If you do not have some way of controlling transaction scope, and take the
default of one transaction per call, you do not provide this ensurance to your users.

The second motivation is to hide implementation details and keep the system
interface relatively narrow. In systems where this is important (and that's really any
system with a projected lifetime of over 2 weeks 8^}) ), data that is displayed is
usually extracted from the entity beans and put into 'View' classes by session beans.
This gives you a narrow system interface (the session interfaces and View classes)
while allowing you the modularity and cohesion benefits of a fine-grained
implementation, as well as (possibly) the development time savings of CMP.

Comments and alternative answers

Facade Pattern
Author: prajakt samant (http://www.jguru.com/guru/viewbio.jsp?EID=272793), Mar
22, 2001
The above scenario is also known as Facade Pattern wherein the stateless Session
beans form a "facade" to Entity Beans ,which actually reduces network traffic as
stateless beans could be swapped in between clients,eventually improving the
performance.

Re: Facade Pattern


Author: Samir satam (http://www.jguru.com/guru/viewbio.jsp?EID=337041), Apr
8, 2001
How does it reduce network traffic?
Java:API:EJB
Author: hua lu (http://www.jguru.com/guru/viewbio.jsp?EID=419440), May 10, 2001
1. suppose you call the session bean (SB)once, and the session bean calls multiple
entity beans (EB). If your SB and EB are located in the same machine, then many
application servers would allow (optimize) the communications between the SB and
the EBs to carry less overhead than usual remote access (though that's slightly against
the EJB specification). So you practically end up with one real remote access. 2.
suppose you don't use SB as facade, then each call from the client to each one of the
EBs is a remote access. Then you end up with multiple remote accesses. That's the
reason why using SB as facade reduces traffic.

Who offers hosting of EJBs?


Location: http://www.jguru.com/faq/view.jsp?EID=234267
Created: Oct 23, 2000 Modified: 2000-10-23 21:50:14.146
Author: Badri Kuppa (http://www.jguru.com/guru/viewbio.jsp?EID=98194) Question
originally posed by rainer wasserfuhr
(http://www.jguru.com/guru/viewbio.jsp?EID=224279

The following sites host EJB applications

• Digex - http://www.digex.com
• ejip.net - http://www.ejip.net

Comments and alternative answers

Also check out http://www.webappcabaret.com They offer free hosting.


Author: Ian Beaumont (http://www.jguru.com/guru/viewbio.jsp?EID=45887), Jun 12,
2001
Also check out http://www.webappcabaret.com They offer free hosting.

When using Stateful Session Beans, What will happen if an EJB client
program terminates without calling the Stateful Sesson Bean's remove()
method?
Location: http://www.jguru.com/faq/view.jsp?EID=234431
Created: Oct 23, 2000 Modified: 2000-10-23 22:10:22.223
Author: manish sethi (http://www.jguru.com/guru/viewbio.jsp?EID=233027)
Question originally posed by Yongfeng Xiao
(http://www.jguru.com/guru/viewbio.jsp?EID=216776

Referring to page 57 of the EJB 1.1 specification. A stateful session bean would come
into Doesn't Exist state if one of the following happens:

1. Call remove() on the EJBObjects's stub from the Client


2. Call remove(handleToEJBObject) on EJBHome's stub from client.
3. System Exception in bean
4. Bean timeout
5. Container crash
As in your question you have ruled out the possibility of 1, 2, and 3 so bean will be in
Exists state until one of 4 or 5 happens. Most likely 4.

Comments and alternative answers

good
Author: sravan reddy (http://www.jguru.com/guru/viewbio.jsp?EID=962689), Jul 24,
2002
its a nice explanation

Is necessary to use the remove method?


Author: alex herrera (http://www.jguru.com/guru/viewbio.jsp?EID=989751), Aug
27, 2002
Im using stateful session beans with helpers and when i use then in JSP, the helper
doesnt use the remove method. I just equals the object (bean) to null. Is that
allright?

Re: Is necessary to use the remove method?


Author: Saurabh Banerjee
(http://www.jguru.com/guru/viewbio.jsp?EID=1093180), Jun 11, 2003
You should invoke the remove(). Refer to EJB specs section 7.1 figure 3. Your
bean will be in "Exists and Not Referenced" state until a server crash or bean
timeout. So if you store a handle and call handle.getEJBObject() you will be
able to get the reference before the server crash or timeout.

In EJB 2.0, What are dependent value classes?


Location: http://www.jguru.com/faq/view.jsp?EID=238463
Created: Oct 27, 2000 Modified: 2000-11-01 23:01:44.356
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by vikash mall
(http://www.jguru.com/guru/viewbio.jsp?EID=214765

Value classes basically are a "happy" compromise between die-hard object


encapsulation on the server-side and make-easy performance considerations on the
client side.

For example, consider an EJB client requesting a customer addrees from a Customer
EJB. Assume the customer address is a serializable object containing Street address,
State, Zip, etc. You have 2 options - either pass the serializable object asis to the
client over IIOP or provide individual methods on the Customer EJB that return each
piece of information. While the first breaks encapsulation the second will be shot
down by your architect for performance reasons! Also the scenario makes sense for
inter-EJB calls as well to preserve encapsulation.

Enter value objects in EJB 2.0. Value objects are basically a client view of your
persistent object. The Customer bean provider creates this view from the persistent
representation. In order for the container to be able to create these instances, the
appropriate IDL stubs must be deployed on the container when the bean is deployed.
Optionally containers may download them on demand - the spec doesn't impose
either alternative. For more details & examples, refer to the EJB 2.0 specification!

Comments and alternative answers

performance ok...but sync-ing probs pop up, right?


Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Nov
30, 2001
You will have sync-ing probs with this approach. Different clients can "set" things
differently and hence result in inconsistent state of object.

Dependent Value Classes


Author: Ted Barbusinski (http://www.jguru.com/guru/viewbio.jsp?EID=352014), Jul
17, 2002
The author of this FAQ seems to have confused the "Value Object" design pattern
with EJB 2.0 Dependent Value Objects. EJB 2.0 Dependent Value Objects are not
client view "value objects" offering a client view of your persistent object. They are
actual fields within your CMP ejb that are comprised of more than one java primitive
data type. They can be persisted as serialized objects with your ejb and recovered at
any time. They are accessed using accessor and mutator methods just like your CMP
field methods.

:-)
Author: george varghese (http://www.jguru.com/guru/viewbio.jsp?EID=1143700),
Feb 4, 2004
Dependent value class A dependent value class is a concrete class that is the value of a
cmp-field. A dependent value class may be a class that the Bean Provider wishes to
use internally within an entity bean with container-managed persistence, and/or it may
be a class that the Bean Provider chooses to expose through the remote (or local)
interface of the entity bean. A dependent value class can be the value of a cmp-field; it
cannot be the value of a cmr-field. The get accessor method for a cmp-field that
corresponds to a dependent value class returns a copy of the dependent value class
instance. The assignment of a dependent value class value to a cmp-field using the set
accessor method causes the value to be copied to the target cmp-field. A dependent
value class must be serializable. The internal structure of a dependent value class is
not described in the EJB deployment descriptor.

Is there anything special about sending mail with JavaMail when using EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=240549
Created: Oct 30, 2000 Modified: 2002-03-30 19:49:27.279
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by vini vipin (http://www.jguru.com/guru/viewbio.jsp?EID=239441

The javax.mail libraries are a standard part of of J2EE, so the whole API is there.
Even the JavaBeans Activation Framework is there, which is required by JavaMail.
However, you're only allowed to send mail, not receive.
With J2EE, you are required to obtain the javax.mail.Session instance from a JNDI
lookup rather than creating it yourself, but other than that it's the same as sending
mail using JavaMail from a standalone app.

You can look at the Java Pet Store example, which does this.

Also, see What does this messaging exception mean:


javax.mail.NoSuchProviderException:
No provider for Address type: rfc822

I am running a Weblogic on a Sun...

Comments and alternative answers

With Weblogic Server 5.1, I have seen an implementation...


Author: Kian Hui Teo (http://www.jguru.com/guru/viewbio.jsp?EID=64456), Oct 31,
2000
With Weblogic Server 5.1, I have seen an implementation of a mail bean before.
Basically, just remember to include the mail.jar inside the weblogic classpath setting
if you are using service pack 5 and below.

You will also need to configure a smtp host for sending out your mail. You can set this
inside your weblogic.properties file. Actual documentations on this can be found on
the weblogic documentation website at http://www.bea.com Currently, the mail bean
has already been implemented on production systems and working fine.

What are the free EJB containers available? Which version of the EJB
specification do they support? Are they free for development and
production?
Location: http://www.jguru.com/faq/view.jsp?EID=241193
Created: Oct 31, 2000 Modified: 2000-10-31 06:37:34.37
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
Habib El-Zoghbi (http://www.jguru.com/guru/viewbio.jsp?EID=38223

Some application servers are free for development and production, whilst some are
free for development, but require a runtime license. Note that you should confirm
from each site whether or not any licensing terms have changed

• jBoss 2.0 from http://www.jboss.org supports EJB 1.1, and is free for
development and production
• JRun Server 3.0 from http://www.allaire.com supports EJB 1.1, and is free for
development
• Enhydra from http://www.enhydra.org supports EJB 1.1, and is free for
development and production
• OpenEJB from http://www.openejb.org supports EJB 1.1, and is free for
development and production
The EJB 1.1 spec eliminated "runAs" security delegation. Is there some
other way to achieve this effect now? For example, how can I enable
session bean method A, which is running as "guest" to call entity bean
method B which only allows some role not containing "guest" to execute it?
Assume I will do some kind of authentication in method A prior to the call to
B (and only do the call to B on behalf of authorized callers) so this makes
sense.
Location: http://www.jguru.com/faq/view.jsp?EID=245708
Created: Nov 5, 2000 Modified: 2000-11-05 15:43:36.93
Author: Rhett Guthrie (http://www.jguru.com/guru/viewbio.jsp?EID=80532)
Question originally posed by Bob Hall
(http://www.jguru.com/guru/viewbio.jsp?EID=222264

Do the guest-specific authorization in Bean B. Doing this is not as clean as the old
runAs mechanism, but it will work.

What are some standard design patterns that are used in EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=247099
Created: Nov 6, 2000 Modified: 2000-11-07 22:12:12.677
Author: venkat r (http://www.jguru.com/guru/viewbio.jsp?EID=237873) Question
originally posed by bindu devarapalli
(http://www.jguru.com/guru/viewbio.jsp?EID=239587

Some standard design patterns used in EJB include the command and decorator
patterns. An extensive list of patterns for use in EJB can be found at
http://c2.com/cgi/like?EjbDesignPatterns

How can I find out the cause of a


javax.transaction.TransactionRolledbackException?
Location: http://www.jguru.com/faq/view.jsp?EID=247150
Created: Nov 6, 2000 Modified: 2000-11-13 19:03:43.299
Author: shilpa Tiwari (http://www.jguru.com/guru/viewbio.jsp?EID=138841)
Question originally posed by Raghunandan Mysore
(http://www.jguru.com/guru/viewbio.jsp?EID=112837

A TransactionRolledBackException would occur if :

1. There has been an exception within the scope of the transaction. If you have
proper logging in your program and log all the possible exceptions then you
could easily see the reason of a TransactionRolledBackException. Or more
precisely the exception which led to the rollback. This Exception could be seen
in the stack trace if you dump your stack trace.
2. If the transaction timed out before the completion of the task. In this case
case you could see in the stack trace that the transaction was timed out and
then the TransactionRolledBackException as it would be thrown once
timeout occurs.

What's the main difference between throwing an javax.ejb.EJBException


and throwing an java.rmi.RemoteException from within a EJB? When should
each be thrown?
Location: http://www.jguru.com/faq/view.jsp?EID=249857
Created: Nov 9, 2000 Modified: 2000-11-13 19:07:44.99
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Benjamin Chi
(http://www.jguru.com/guru/viewbio.jsp?EID=232856

The main difference is that throwing remote exception from within the bean is
deprecated: your bean methods (including ejbLoad, ejbStore and their ilk) should
throw EJBException. Other things to note from the spec are that the current
transaction will be rolled back (it wouldn't be if you threw an application exception),
and the client will see it as a RemoteException, even though you threw an
EJBException.
Comments and alternative answers

When throwing a EJBException, that is a SystemExce...


Author: Guilherme Ceschiatti
(http://www.jguru.com/guru/viewbio.jsp?EID=252922), Nov 13, 2000
When throwing a EJBException, that is a SystemException, the EJB Container will
rollback the transaction without user intervention. The EJB Container then
encapsulates EJBException in the RemoteException to deliver it to the client.

Re: When throwing a EJBException, that is a SystemExce...


Author: Todd Huss (http://www.jguru.com/guru/viewbio.jsp?EID=389670), Mar
28, 2001
You should never explicitly throw a RemoteException as of EJB1.1 or later.
Instead you should either throw an EJBException (or subclass thereof) in the case
of a system exception or a subclass of Exception in the case of an application
exception. The EJB Spec talks about this in detail in the "Exception Handling"
section.

How can we interact with COM/DCOM components from a EJB component ?


Location: http://www.jguru.com/faq/view.jsp?EID=254368
Created: Nov 15, 2000 Modified: 2000-11-15 14:56:16.813
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
jeetender davai (http://www.jguru.com/guru/viewbio.jsp?EID=253290

A list of tools that integrate Java with the Microsoft platform is available here. These
tools can be used, as long as they stay within the EJB specification requirements set
out in section 18.1.2 of the EJB 1.1 specification.

Is it possible to stop the execution of a method before completion in a


SessionBean?
Location: http://www.jguru.com/faq/view.jsp?EID=254734
Created: Nov 15, 2000 Modified: 2000-11-15 18:56:41.868
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Ramakrishna Rallapalli
(http://www.jguru.com/guru/viewbio.jsp?EID=215737
Stopping the execution of a method inside a Session Bean is not possible without
writing code inside the Session Bean. This is because you are not allowed to access
Threads inside an EJB, refer to section 18.1.2 of the EJB 1.1 specification.

One possible solution (that requires coding) would be to set the transaction that the
Session Bean is running within to be rolled back. To do this, use the
setRollBackOnly() method of the javax.transaction.UserTransaction interface.
This method would of course require that your Session Bean is using transactions.

If the Session Bean is processing many long running requests then it could provide
an optimization by checking the transaction status using the getRollBackOnly() call
of the javax.ejb.SessionContext object.

Is it possible to access a CORBA object from a EJB? I am using VisiBroker


4.0 for my CORBA objects and J2EE 1.2.1 for my EJB.
Location: http://www.jguru.com/faq/view.jsp?EID=254760
Created: Nov 15, 2000 Modified: 2000-11-15 19:09:33.488
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by kyin yan
(http://www.jguru.com/guru/viewbio.jsp?EID=239598

Yes it is, you'll probably want to use the VisiBroker ORB from the EJB, to override the
default ORB, use the following properties:

org.omg.CORBA.ORBClass=com.inprise.vbroker.orb.ORB
org.omg.CORBA.ORBSingletonClass=com.inprise.vbroker.orb.ORB
These properties can be set on the commandline (using -Dorg...) or using a file
named orb.properties.

In CMP how can I define a finder method equivalent to a 'SELECT * FROM


TABLE'?

[RC - Please give reference to the particular AppServer you are using]
Location: http://www.jguru.com/faq/view.jsp?EID=256842
Created: Nov 17, 2000 Modified: 2000-11-21 10:44:45.924
Author: shiva prasad (http://www.jguru.com/guru/viewbio.jsp?EID=123366)
Question originally posed by Praveen kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=84503

• Weblogic 5.1.0 - Define the following Finder syntax in your weblogic-ejb-


jar.xml deployment descriptor.

<finder>
<method-name>All</method-name>
<method-params></method-params>
<finder-query<(1 = 1)]]></finder-query>
</finder>

Comments and alternative answers


In Weblogic 4.5.1 define the following finder syntax...
Author: uttara donde (http://www.jguru.com/guru/viewbio.jsp?EID=239829), Nov 22,
2000
In Weblogic 4.5.1 define the following finder syntax in finder descriptions
"findByAll()" "(= 1 1)"

In Websphere using <bean>FinderHelper write the...


Author: evyatar shoresh (http://www.jguru.com/guru/viewbio.jsp?EID=90755), Nov
22, 2000
In Websphere using <bean>FinderHelper write the following:
public static final string findByAllWhereClause="1=1";
and define a method in the Home interface as follows:
public Enumeration findByAll() throws RemoteException;

Is it legal to have static initializer blocks in EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=257106
Created: Nov 18, 2000 Modified: 2000-11-27 14:22:53.803
Author: ganaparthy balasubramanyam
(http://www.jguru.com/guru/viewbio.jsp?EID=257097) Question originally posed by
ravi srivatsav (http://www.jguru.com/guru/viewbio.jsp?EID=44460

Although technically it is legal, static initializer blocks are used to execute some piece
of code before executing any constructor or method while instantiating a class. Static
initializer blocks are also typically used to initialize static fields - which may be illegal
in EJB if they are read/write - see section 18.1.2.
In EJB this can be achieved by including the code in either the ejbCreate(),
setSessionContext() or setEntityContext() methods.

Is it possible to specify multiple JNDI names when deploying an EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=258023
Created: Nov 20, 2000 Modified: 2000-11-21 10:17:47.525
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Guillaume Bedard
(http://www.jguru.com/guru/viewbio.jsp?EID=252289

No. To achieve this you have to deploy your EJB multiple times each specifying a
different JNDI name.

Is it possible to write two EJB's that share the same Remote and Home
interfaces, and have different bean classes? if so, what are the
advantages/disadvantages?
Location: http://www.jguru.com/faq/view.jsp?EID=258282
Created: Nov 20, 2000 Modified: 2000-11-28 13:59:47.825
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Alan Gault
(http://www.jguru.com/guru/viewbio.jsp?EID=131380

It's certainly possible. In fact, there's an example that ships with the Inprise
Application Server of an Account interface with separate implementations for
CheckingAccount and SavingsAccount, one of which was CMP and one of which was
BMP.

Note that if you just want to map the same EJB to two data sources, you can just
deploy it twice under different names.

Comments and alternative answers

Sharing interfaces might be possible, but not trivial....


Author: Rickard Nilsson (http://www.jguru.com/guru/viewbio.jsp?EID=259069), Nov
22, 2000
Sharing interfaces might be possible, but not trivial. If you deploy with Sun
Deployment Tool 1.2.1 you will get a java.lang.ClassCastException:
MyBean2EJB_EJBObjectImpl when you execute a method in MyBean2EJB, which
shares Remote and Home interface with MyBean1EJB. If you delete MyBean1EJB
and redeploy the application, this exception goes way.

The best way is while deploy it as two different beans...


Author: Rahul kumar Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=4809),
Dec 4, 2000
The best way is while deploy it as two different beans and use different JNDI names
for lookup, that will avoid the conflict you are hitting.

Is is possible for an EJB client to marshall an object of class java.lang.Class


to an EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=261142
Created: Nov 23, 2000 Modified: 2000-11-24 15:11:42.869
Author: Prashant Mirajkar (http://www.jguru.com/guru/viewbio.jsp?EID=53347)
Question originally posed by Partha Pratim Das
(http://www.jguru.com/guru/viewbio.jsp?EID=245213

Technically yes, spec. compliant NO! - refer to section 18.1.2 of the EJB 1.1
specification (page 273).
"The enterprise bean must not attempt to query a class to obtain information about
the declared members that are not otherwise accessible to the enterprise bean
because of the security rules of the Java language."

For BMP, I don't want all the variables to be updated in the database when
only one variable has been changed in each of the business methods. Is it a
good practice to load and store values from and to database inside the
business methods rather than ejbStore() and ejbLoad()?
Location: http://www.jguru.com/faq/view.jsp?EID=262837
Created: Nov 26, 2000 Modified: 2000-11-28 13:48:16.388
Author: Matthias David (http://www.jguru.com/guru/viewbio.jsp?EID=17908)
Question originally posed by Mahesh chandra Puvvada
(http://www.jguru.com/guru/viewbio.jsp?EID=231051

Placing load and store commands inside business methods is not a good practice.
Imagine if you have several calls to business methods to the bean, in this case you
would have database access on each business method call.
Using the ejbStore() and ejbLoad() methods guarantee that the database access
takes place when it is really necessary, e.g. between transcations.
If only some of the variables change between calls of ejbLoad() and ejbStore() then
an approach to use would be to store which variables have changed using transient
boolean flags and then write only these variables to the database.

Are enterprise beans allowed to use Thread.sleep()?


Location: http://www.jguru.com/faq/view.jsp?EID=267170
Created: Dec 1, 2000 Modified: 2000-12-05 18:09:33.129
Author: Xavier Schaefer (http://www.jguru.com/guru/viewbio.jsp?EID=267049)
Question originally posed by Ulrich Kraemer
(http://www.jguru.com/guru/viewbio.jsp?EID=256233

Here is the answer from the Java 2 Enterprise Edition Developer's Guide (v. 1.2.1) :

"Enterprise beans make use of the services provided by the EJB container, such as
life-cycle management. To avoid conflicts with these services, enterprise beans are
restricted from performing certain operations:

• ...
• Managing or synchronizing threads
• ... "

Where can I find a vendor-independent Job Scheduling Framework for


J2EE?
Location: http://www.jguru.com/faq/view.jsp?EID=276094
Created: Dec 12, 2000 Modified: 2000-12-12 10:34:38.845
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
Simon Juden (http://www.jguru.com/guru/viewbio.jsp?EID=275869

Check out this article from Sims Computing


Comments and alternative answers

(A) Here's a direct link to Sim's Flux task scheduling...


Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4), Dec 12,
2000

(A) Here's a direct link to Sim's Flux task scheduling component.

(B) Another way to do this is to use an application server which support's JMX.
Basically, create a JMX MBean component which uses the JMX timer services and
then fires off e.g., a session bean when the associated timer expires.

How can I use JUnit to test J2EE/EJB applications?


Location: http://www.jguru.com/faq/view.jsp?EID=276550
Created: Dec 12, 2000 Modified: 2002-04-04 12:09:42.503
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out Jeff Schnitzer's JUnitEE package and the Wiki EJB Unit Testing page.
Comments and alternative answers

There's also a good article from the JavaWorld arc...


Author: Sid Haniff (http://www.jguru.com/guru/viewbio.jsp?EID=300834), Jan 22,
2001
There's also a good article from the JavaWorld archives.
http://www.javaworld.com/javaworld/jw-05-2000/jw-0526-testinfect.html

JUnitEE link broke


Author: Damien Joldersma (http://www.jguru.com/guru/viewbio.jsp?EID=412803),
Mar 22, 2002
The JUnitEE link posted on this page is broken, http://junitee.sourceforge.net works
better now.

Re: JUnitEE link broke


Author: Erik Meade (http://www.jguru.com/guru/viewbio.jsp?EID=774835), Apr
4, 2002
Thanks, I fixed it. Should show up next update of the site.

Try Jakarta Cactus and TagUnit


Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382), Jun
30, 2002
Try these tools:
http://jakarta.apache.org/cactus/
http://www.tagunit.org/

What optimizations can be made to increase the performance of finder


methods, especially when retrieving large result sets?
Location: http://www.jguru.com/faq/view.jsp?EID=277869
Created: Dec 14, 2000 Modified: 2001-01-25 20:43:43.962
Author: Xavier Schaefer (http://www.jguru.com/guru/viewbio.jsp?EID=267049)
Question originally posed by Nicholas Whitehead
(http://www.jguru.com/guru/viewbio.jsp?EID=1260

Here is a very good presentation of patterns to improve the performance of your


beans.
The method that I used, and that showed very good results, is the following.

• For each Entity Bean class, create a serializable base class (i.e. the Entity
Bean class should inherit from this class).
• Move all public attributes, getters and setters to this class (they are not
needed any more in the Bean class, but are inherited).
• Add a returnBase method in the Entity Bean, which returns a copy of its
data, in the form of a base class instance (i.e. a standard java class).
• Avoid direct client - Entity Bean interaction, but wrap the entity bean by a
session bean.
• When undertaking a select statement,
o the client asks the intermediate session bean to call the finder,
o the intermediate session bean calls the returnBase method for each
EJB and stores all the resulting instances in a Vector.
o The vector is returned to the client in one throw !

Comments and alternative answers

Another optimization that is useful for finders that...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Dec 21, 2000
Another optimization that is useful for finders that return large datasets is to eschew
the finder completely: the intermediate session bean described above can simply
execute SQL and return the serializable base class described above (or an equivalent
serializable object)

This does break encapsulation to some extent (by giving the session bean knowledge
of the database structure), but it also avoids hitting the database n+1 times (as using a
finder might). There are also ways of structuring your persistence layer to avoid this
breaking of encapsulation, particularly for BMP beans.

Re: Another optimization that is useful for finders that...


Author: Venkatesh Balakumar
(http://www.jguru.com/guru/viewbio.jsp?EID=430540), Sep 30, 2002
I think the DAO Pattern will be helpfull in this aspect. It can be found in the
following link
Sun's Java BluePrints Patterns Catalog.

Cheers,
Venkat.

Enterprise JavaBeans by Monson-Haefel, Third Edition (O'Reilly)


Author: Stan Jordan (http://www.jguru.com/guru/viewbio.jsp?EID=512836), Feb 1,
2002
There is an excellent discussion of this topic on pages 351-353 of this book. He
eschews the finder in favor of JDBC. Worth reading.

What are the benefits of using a Stateless Session Bean over using a class
purely consisting of static methods?
Location: http://www.jguru.com/faq/view.jsp?EID=281106
Created: Dec 18, 2000 Modified: 2000-12-19 13:39:08.584
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Danny So
(http://www.jguru.com/guru/viewbio.jsp?EID=236938
Mostly container management of transactions and the ability to 'easily' call remote
code. Really, the two solutions work at different scales: a Stateless Session Bean is
useful when you can define a set of (fairly coarse grained) atomic transactions that
are related by a common theme, where a bunch of static methods in a class are
more useful for (rather fine grained) utility code.

One common use of Stateless Session Beans is to implement a facade over a set of
entity beans, in order to allow the client to be transaction-ignorant. In this pattern
the session bean defines a set of transactions that it implements using entity beans.
See FAQ question "What is the Session wraps Entity Pattern? What are the
motivations behind it?" for more information.

Comments and alternative answers

Beyond the technical advantages of Session Beans, one...


Author: Xavier Schaefer (http://www.jguru.com/guru/viewbio.jsp?EID=267049), Dec
20, 2000
Beyond the technical advantages of Session Beans, one of the great advantages of this
concept that is has got a one-to-one trace to analysis classes of the unified software
development process, therefore allowing clear design guidelines.

• Boundary classes become html or jsp pages.


• Entity classes become Entity Beans
• Control classes become Session Beans.

Another difference is in the number of database in...


Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), Dec
26, 2000
Another difference is in the number of database instances/connections required. In the
case of a Java class with static methods, you would need to open/close the connection
for each method. (There are ways around this if you design for it.) In stateless session
beans, the EJB server which manages the pool of the session beans has the connection
to the database and therefore there is no need to open close per a session bean method
call. (Of course, there are situations here where you would want to talk to a totally
separate database, etc. and then have to design/account for this as well.)

Can an Entity Bean call a stored procedure using Container Managed


Persistence ? If yes, how?
Location: http://www.jguru.com/faq/view.jsp?EID=281113
Created: Dec 18, 2000 Modified: 2000-12-20 09:39:02.416
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Philip Liu
(http://www.jguru.com/guru/viewbio.jsp?EID=34697

If you mean "can you map the CMP Bean's persistence operations through stored
procedures?", the answer depends on the sophistication of your chosen container's
mapping tool and how tightly it integrates with your database. Sophisticated
mapping tools are free to map your bean's CMP fields to whatever they want,
however they want. However, many CMP tools are much simpler and expect to map
to relational tables.

Now, if your question was more generally "Can a CMP bean call a stored procedure?",
for example from a business method, or from ejb<Post>Create(...), the answer is a
definite yes. Just specify the resource-reference in your ejb-jar.xml (as you will
anyway), look up the DataSource to get a Connection, the do all the
CallableStatement JDBC stuff you want.

Comments and alternative answers

Can an Entity Bean call a stored procedure using Container Managed


Persistence ? If yes, how?
Author: dreaddy Mck (http://www.jguru.com/guru/viewbio.jsp?EID=385159), Mar
22, 2001
Can some submit an example of specifing the resource-reference in your ejb-jar.xml
(as you will anyway), and looking up the DataSource to get a Connection

Re: Can an Entity Bean call a stored procedure using Container Managed
Persistence ? If yes, how?
Author: Steven Martin (http://www.jguru.com/guru/viewbio.jsp?EID=430104),
Jun 11, 2001
Was any code ever posted? I'd like to use EJBS to do that wrapping as well.
thanks, Steven

Re: Re: Can an Entity Bean call a stored procedure using Container
Managed Persistence ? If yes, how?
Author: V Shah (http://www.jguru.com/guru/viewbio.jsp?EID=226807), Oct
23, 2001
Can CMP call a stored procedure ? I need to have an ORACLE stored
procedure called for every insert/update/delete. How would I go about doing
this ? Thanks

Re: Re: Re: Can an Entity Bean call a stored procedure using
Container Managed Persistence ? If yes, how?
Author: praveen Kumar Nagunoori
(http://www.jguru.com/guru/viewbio.jsp?EID=542975), Nov 13, 2001
Yes u can call a database stored procedure in cmp beans just specify the
database connection resources in the ejb-jar.xml and get the connection in
the call back methods and call ur operation related stored procedure in the
call back methods using CallableStatements. But my suggestion is why u
want to call the stored procedures why dont u apply that in business logic u
implemnt in session beans.

Re[4]: Can an Entity Bean call a stored procedure using Container


Managed Persistence ? If yes, how?
Author: Neo Gigs
(http://www.jguru.com/guru/viewbio.jsp?EID=748386), Apr 17, 2002
Hi there,

From some source out there where BMP only can call a stored
procedure....

Unless there are some codes that prove what u said..?

Thanks

Neo

Re[2]: Can an Entity Bean call a stored procedure using Container


Managed Persistence ? If yes, how?
Author: Will Bracken (http://www.jguru.com/guru/viewbio.jsp?EID=840566),
Apr 16, 2002
Yeah, I'd be interested in seeing an example or a link to a tutorial on how to do
it in WebSphere Studio or something.

What is the difference between an Application Server and a Web Server?


Location: http://www.jguru.com/faq/view.jsp?EID=282323
Created: Dec 19, 2000 Modified: 2000-12-20 10:05:22.308
Author: sharad chaudhary (http://www.jguru.com/guru/viewbio.jsp?EID=62937)

A Web Server understands and supports only HTTP protocol whereas an Application
Server supports HTTP,TCP/IP and many more protocols. Also many more features
such as Caches,Clusters,Load Balancing are there in Application Servers which are
not available in Web Servers. We can also Configure Application Servers to work as
Web Server. In short, Applicaion Server is a super set of which Web Server is a sub
set.

[See also What are all the different kinds of servers? (Such as Web Servers,
Application Servers, etc) ]

Comments and alternative answers

Web servers do offer caches, clustering and load b...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Dec 21, 2000
Web servers do offer caches, clustering and load balancing - in fact, these are far
easier to implement for web servers than application servers, because web servers are
far simpler.
Also, HTTP is an application layer protocol that runs over TCP/IP.

Your final summary is fairly good, but I think the best description is that Web servers
are HTTP servers, whereas an application server runs application code in the context
of some higher level API (servlets, EJB, ASP, Enhydra's compiled HTML thingy)

Now, given Apache's module APIs, is it a web server or an application server?

Re: Web servers do offer caches, clustering and load b...


Author: Balaji Sundararajan
(http://www.jguru.com/guru/viewbio.jsp?EID=439659), Jun 15, 2001

Even if we take it literally, a web server serves web pages so an application server
should serve with application (logic).

The application logic (here, the business logic) is embedded in some form, let that
be an EJB or CORBA component, and the application server allows us to get the
services provided by those components.

IMHO, the qualities such as load balancing, fail-over support, caching are all non-
funtional requirements that are applicabale to any distributed application (web
server, db server, app server etc.)

Re[2]: Web servers do offer caches, clustering and load b...


Author: Barath Ganesan
(http://www.jguru.com/guru/viewbio.jsp?EID=1212633), Nov 23, 2004
In my context,a web server is just a publishing server.whereas an application
server provides some services like security, and as said before clustering and
caches on its own.we jus have to configure in order to use these services.in
case of a web server it is the burdon of the programmer to do all these. A web
server provides services only to web clients whereas an application server
provides services to any application which is running in a distributed
environment.

Re: Web servers do offer caches, clustering and load b...


Author: Matt Rokenbrod (http://www.jguru.com/guru/viewbio.jsp?EID=955561),
Jul 18, 2002
Can multiple Application Servers Run on the same webserver on the same
computer?

Re: Web servers do offer caches, clustering and load b...


Author: Krupakar Jonnalagadda
(http://www.jguru.com/guru/viewbio.jsp?EID=1204169), Oct 8, 2004
Apache's module apis is an application server.

WebServer just serves HTTP Request, while Application...


Author: Anurag Goel (http://www.jguru.com/guru/viewbio.jsp?EID=285633), Dec 25,
2000
WebServer just serves HTTP Request, while Application Server consist of Servlet
Engine, and serve WebServer. WebServer contains only HTML files and send only
HTML file any other file requested which has to be compiled dynamically based on
the request, Webserver will get it from Application Server. Application Server consist
of Servlet Engine,JVM and other parsers which interpret the required class files and
send it to Webserver.

It should also be noted that while many AppServers...


Author: Alex Varanese (http://www.jguru.com/guru/viewbio.jsp?EID=334606), Feb
20, 2001
It should also be noted that while many AppServers (such as BEA's WebLogic) are
indeed a superset of web server functionality, they aren't generally used that way.
WebLogic is often used for it's enterprise capabilities and then augmneted by allowing
Apache to handle the strictly HTTP-related side of things.

Re: It should also be noted that while many AppServers...


Author: Sanjay Kumar Gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=1083738), May 12, 2003
Summary: A normal web server can handle Http request means it can provide
static web pages, images, css etc. For generating dynamic web contents it requires
support for JSP, Servlets etc in Java & ASp in Microsoft respectively. So A java-
enabled webserver means it has JVM & servlet engine which can run java servlets
or JSp if it has JSP container. In such a case, the web server on receiving http
request which can be handled by a servlet, passes it on to servlet which will
handle it & may generate an HTML page which web server delivers to
webbrowser. An application server can provide services based on various
protocols including HTTP, meaning web service can be inbuilt or can be
configured with it. Application servers serve application code to application
clients. It provides several services like transaction processing, resource pooling
i.e. database connection pooling, Security features, clustering etc.

Re[2]: It should also be noted that while many AppServers...


Author: prasenjit biswas
(http://www.jguru.com/guru/viewbio.jsp?EID=1228123), Apr 8, 2005
You can't run EJB or any business logic in Javawebserver.An application
server should have the capability to run business logic in it.That's why we can't
say that JWserver a application server.

Application vs Webserver
Author: siraj ahmed (http://www.jguru.com/guru/viewbio.jsp?EID=405469), Apr 18,
2001
If application server has inbuilt jvm and servlet engine then why we call
javawebserver2.0 as "webserver" it can handle the servlet request then its also an
application server. Please comment....

Re: Application vs Webserver


Author: rahul bose (http://www.jguru.com/guru/viewbio.jsp?EID=219615), Sep 4,
2001
can a web server exists by itself without any appserver Thanks, rahul

Re: Re: Application vs Webserver


Author: praveen Kumar Nagunoori
(http://www.jguru.com/guru/viewbio.jsp?EID=542975), Nov 13, 2001
Yes Webserver can exists by itself as it supports all the basic facilties to serve
the purpose of a simple webhosting

Why does an update trigger is activated when I access a method in a CMP


EJB mapped to the table with that trigger?
Location: http://www.jguru.com/faq/view.jsp?EID=283925
Created: Dec 21, 2000 Modified: 2000-12-27 18:15:04.69
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by HERNAN RODRIGUEZ
(http://www.jguru.com/guru/viewbio.jsp?EID=65693

Probably because the EJB container is storing the bean when the transaction
commits, even though you didn't modify it. Some containers have various ways of
optimizing around this, from comparing the data (IAS 4.0) to allowing you to
implement an 'isModified' bethod returning boolean (WebLogic). The container you're
using may allow something like this.

What is EJBDoclet?
Location: http://www.jguru.com/faq/view.jsp?EID=285175
Created: Dec 24, 2000 Modified: 2000-12-24 01:22:49.179
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

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.

Is it legal to use JDBC code inside the business methods of an Entity Bean?
What are the implications of doing so?
Location: http://www.jguru.com/faq/view.jsp?EID=287585
Created: Dec 27, 2000 Modified: 2001-01-01 02:35:20.703
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by amol kher
(http://www.jguru.com/guru/viewbio.jsp?EID=274801

Yes it is allowed. The implications rather depend on your bean and your application.
The biggest implication is in your transactions: if you call your entity business
methods directly from a client, each method will be executed as its own transaction,
so you can expect ejbLoad, your business method, and ejbStore to all be called for
each method. This tends to be a lot of datbase activity, which is why guys like me
advocate the Ssession wraps Entity' pattern. See this FAQ for more details on
'Session wraps Entity'

Another potential problem rises from doing this within a CMP entity bean: you have
to be careful not to modify tables behind the container's back: containers are allowed
to cache CMP entity data (the spec defines three 'commit options', A, B, and C) and
modifying the tables directly can cause the container's cache to be inconsistent in
some cases.

With BMP beans the situation is simpler, and making JDBC calls from normal business
methods can allow you to optimize your application in some situations. For example,
if your application's object model consists of a few very coarse grained entities that
each have several sets of dependent objects, you can use a 'lazy fetch'
implementation to retrieve dependents only when you know they're going to be
used.

Are there any performance issues that have to be considered while using
EJB Components from COM environments?
Location: http://www.jguru.com/faq/view.jsp?EID=287841
Created: Dec 28, 2000 Modified: 2001-01-01 02:36:23.591
Author: Lee Fuller (http://www.jguru.com/guru/viewbio.jsp?EID=109421) Question
originally posed by Nikhil Kapre
(http://www.jguru.com/guru/viewbio.jsp?EID=49106

Certainly. The level of performance degradation depends on the architecture used,


which might include calling into the local JVM to call a particular class (which might
then use RMI to get into a particular EJB component), using MSMQ and JMS to
loosely couple the two architectures, using SOAP/Web services to loosely couple
architectures or using an EJB to CORBA/COM bridge.

Personally, I would choose a loosely coupled architecture, with the anticipation of fast
performance not being a requirement. If re-using an existing EJB component, then
this performance hit will have to factored into the expectations, if a new component,
then it is best to keep it all COM(+) for maximum performance. (IMHO)

In EJB 2.0, What is an abstract persistence schema?


Location: http://www.jguru.com/faq/view.jsp?EID=290107
Created: Dec 31, 2000 Modified: 2001-01-01 02:28:46.864
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by vikash mall
(http://www.jguru.com/guru/viewbio.jsp?EID=214765

For a full description and an example, see Read all about EJB 2.0 by Richard Monson-
Haefel in JavaWorld. Basically, the persistence manager maps an entity bean to a
database based on the bean-persistence manager contract / abstract persistence
schema.

What is EJB QL?


Location: http://www.jguru.com/faq/view.jsp?EID=294899
Created: Jan 5, 2001 Modified: 2001-01-07 13:47:33.181
Author: malay thakkar (http://www.jguru.com/guru/viewbio.jsp?EID=294890)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

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:

1. Finder methods that are defined in the home interface of an entity bean and
which return entity objects.
2. 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.

From the EJB 2.0 spec:

The Enterprise JavaBeans query language, EJB QL, is used to define finder queries
for entity beans with container managed persistence. EJB QL lets the Bean Provider
specify finder methods in a portable way. It is a specification language that can be
compiled to a target language, such as SQL, of a persistent store used by a
persistence manager. This allows the responsibility for the execution of finder queries
to be shifted to the native language facilities provided for the persistent store (e.g.,
RDBMS), instead of requiring finder queries to be executed directly on the persistent
manager’s representation of the entity beans’ state. As a result, finder methods are
both portable and optimizable.
Comments and alternative answers

code?
Author: Ilija Jovanoski (http://www.jguru.com/guru/viewbio.jsp?EID=515190), Oct
9, 2001

This is good but can we see some code with explanation where to put the methods...
Thanks!

Re: code?
Author: Murthy Yadlapati (http://www.jguru.com/guru/viewbio.jsp?EID=536293),
Nov 1, 2001
Look at the following article for examples:
about ejb 2.0 and EJBQL

Re: Re: code?


Author: Ilija Jovanoski
(http://www.jguru.com/guru/viewbio.jsp?EID=515190), Nov 2, 2001
Many thanks!
What is the difference between a "Coarse Grained" Entity Bean and a "Fine
Grained" Entity Bean?
Location: http://www.jguru.com/faq/view.jsp?EID=295657
Created: Jan 7, 2001 Modified: 2001-01-07 16:45:41.67
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by manish sharma
(http://www.jguru.com/guru/viewbio.jsp?EID=285743

Here's my definition, such as it is. A 'fine grained' entity bean is pretty much directly
mapped to one relational table, in third normal form. A 'coarse grained' entity bean is
larger and more complex, either because its attributes include values or lists from
other tables, or because it 'owns' one or more sets of dependent objects. Note that
the coarse grained bean might be mapped to a single table or flat file, but that single
table is going to be pretty ugly, with data copied from other tables, repeated field
groups, columns that are dependent on non-key fields, etc.

Fine grained entities are generally considered a liability in large systems because
they will tend to increase the load on several of the EJB server's subsystems (there
will be more objects exported through the distribution layer, more objects
participating in transactions, more skeletons in memory, more EJB Objects in
memory, etc.)

The other side of the coin is that the 1.1 spec doesn't mandate CMP support for
dependent objects (or even indicate how they should be supported), which makes it
more difficult to do coarse grained objects with CMP. The EJB 2.0 specification
improves this in a huge way.

Can an EJB Remote interface extend other interfaces as well as


javax.ejb.EJBObject?
Location: http://www.jguru.com/faq/view.jsp?EID=296411
Created: Jan 8, 2001 Modified: 2001-01-09 09:52:23.795
Author: Brian Keeton (http://www.jguru.com/guru/viewbio.jsp?EID=276091)
Question originally posed by Alexander Ivantsov
(http://www.jguru.com/guru/viewbio.jsp?EID=43897

As with other interfaces in Java, the remote interface can extend multiple interfaces.
In fact, it's common to pull the business methods out of the remote interface and
define them in a separate interface. This new interface can then be extended by the
remote interface and implemented by the bean class. The advantage here is that
now the compiler can do the checking for you to make sure the bean class is
implementing the method signatures that are exposed by the remote interface. You
wouldn't want the bean class to implement the remote interface directly because it
would then be required to implement the methods from EJBObject. You'll see this
referred to as using a "business interface" in Monson-Haefel's book.

Are there any examples and best practices for implementing the hashCode()
and equals() methods for a compound primary key class?
Location: http://www.jguru.com/faq/view.jsp?EID=296598
Created: Jan 8, 2001 Modified: 2001-01-09 05:59:49.552
Author: John Francis (http://www.jguru.com/guru/viewbio.jsp?EID=296576)
Question originally posed by paul martin
(http://www.jguru.com/guru/viewbio.jsp?EID=283798
Try this article at www.ejbnow.com
Comments and alternative answers

hashCode() and equals() methods


Author: Avinash Salimath (http://www.jguru.com/guru/viewbio.jsp?EID=26087),
May 28, 2001

Examples for implementing the hashCode() and equals() methods for a compound
primary key class are: <body>

Equals(): Assuming primarykey class name as "PrimaryKeyClass" and having two


primary keys "primarykey1" and "primarykey2" then

public boolean equals (Object obj) {


if (obj instanceof PrimaryKeyClass) {
PrimaryKeyClass otherkey = (PrimaryKeyClass) obj;
if( (otherkey.primarykey1 == primarykey1) && (otherkey.primarykey2 ==
primarykey2) )
return true;
else
return false;
} else
return false;
}

hashcode() method will be like this:

public int hashCode () {


StringBuffer sb = new StringBuffer();
sb.append(primarykey1);
sb.append(primarykey2);
String keys = sb.toString();
int hashCode = keys.hashCode();
return hashCode;
}

In reference to EJB, what is the meaning of scalable?, how does EJB support
scalability?
Location: http://www.jguru.com/faq/view.jsp?EID=298862
Created: Jan 10, 2001 Modified: 2001-01-16 19:54:50.067
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Anand Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=288893

First, remember that scalability is only one of the goals of the EJB sped: some of the
others are portability, automated transaction management, standardization of life-
cycle management, ease of development, and compatability/interoperability. A lot of
the scalability goal can really be considered as supporting scalability while not forcing
the code writers to jump too many hoops. In other words, ensuring that scalability is
purely a design or application architecture issue and doesn't become a coding issue.

Another point to remember is that scalability is really a hardware matter: all software
can do is make the problem more or less difficult.

My take at 'scalable' in enterprise level systems is that the duration of any


transaction will degrade more slowly than the transaction rate increases. In other
words, the goal would be linear degradation, with a small coefficient. Of course in
reality it isn't linear to infinite loads, but we do want it to remain linear to as high a
transaction rate as possible. Another attribute related to scalability is stability: even
if our load is such that we are getting a lot slower, we shouldn't crash.

Note that this does not mean 'fast.' I expect EJB implementations to be slower than
equivalent CORBA distributed systems that ignore transactions and security. I also
expect EJB based implementations of Web applications to be slower than the
equivalant Servlet/JSP -> JDBC/Data Access Object implementation. The
performance 'knee' of the EJB application will be higher in both cases - if it's a well
designed EJB application that accounts for and makes use of EJB features.

One of the scalability support features is the EBJObject itself: because the client
doesn't call the bean directly, but only through a redirection layer, the container can
interpose in the call and make a decision as to how to handle the call. This might
involve a pool of bean instances, in which multiple beans can assume the same
entity, or it can involve blocking while the last transaction executes (note, though,
that a stateful session bean can balk by throwing an exception if access is attempted
from two different transactions at once). The container's implementation and
configuration is the limiting factor here.

Other scalability gains come in places where the spec doesn't neccessarily define
behavior: container vendors are free to implement their client-side stubs in any way
they see fit - in some cases, the vendor can implement client stubs in such a way as
to take advantage of their clustering capabilities.

Of course, clusters of application servers would be a bear to write code for if there
weren't a simple way of writing transactional code to run on them. Here, EJB enables
scalability by defining a declaritive transaction model. The alternative would be to
write directly to one of the distributed transaction APIs (Xopen or the CORBA
Transaction Service, for example). Using these APIs directly tends to make code
fairly hairy.

Another scalability feature for designers and architects to take advantage of is the
Stateless Session Bean. The EJB specification allows containers to pool instances of
these and rotate through them on a request by request (invocation by invocation)
basis. Your client can hold a single reference to a stateless session but in making 10
method calls to it, it may actually be serviced by 10 different instances of the bean.
This enables scalability in a couple of ways:
1. methods on stateless session beans can be designed to be transactions, thus
keeping critical sections short and increasing throughput by avoiding waits on
locks.
2. Total memory utilization by the server will be less than if the container had to
have one instance of the bean per client reference

The passivation/activation mechanism is another scalability feature. With this


feature, the container can keep a certain number of bean instances in memory, but
swap state in and out of them so that that pool appears to the outside world as if it is
far larger. This can keep a server running with a decent throughput even if its load is
far higher than it might otherwise be able to handle

What is the role of serialization in EJB?


Location: http://www.jguru.com/faq/view.jsp?EID=301817
Created: Jan 13, 2001 Modified: 2001-01-20 14:24:31.453
Author: Tom McClure (http://www.jguru.com/guru/viewbio.jsp?EID=301803)
Question originally posed by Laxmi bannai
(http://www.jguru.com/guru/viewbio.jsp?EID=234299

A big part of EJB is that it is a framework for underlying RMI: remote method
invocation. You're invoking methods remotely from JVM space 'A' on objects which
are in JVM space 'B' -- possibly running on another machine on the network.

To make this happen, all arguments of each method call must have their current
state plucked out of JVM 'A' memory, flattened into a byte stream which can be sent
over a TCP/IP network connection, and then deserialized for reincarnation on the
other end in JVM 'B' where the actual method call takes place.

If the method has a return value, it is serialized up for streaming back to JVM A.
Thus the requirement that all EJB methods arguments and return values must be
serializable. The easiest way to do this is to make sure all your classes implement
java.io.Serializable.

Comments and alternative answers

Yes, besides the answer above, I would like to add...


Author: Mihir Kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=312865), Jan
25, 2001
Yes, besides the answer above, I would like to add that: To save the state of a stateful
session bean. The EJB container is a CTM and has to do efficient management of
resources - as a result it has to passivate beans and use its resources optimally. The
passivation strategy used commonly is Java serialization, of course, the strategy is
vendor specific. The above discussion is relevant to the passivation of the stateful
session beans wherein it is necessary to save the state of the stateful session bean
when it is about to be passivated - ie, being disassociated from the EJBObject.

How to serialize large objects ?


Author: Thomas Carrie (http://www.jguru.com/guru/viewbio.jsp?EID=499238), Oct
8, 2001
What if I want to serialize a large object (a few Mb) and use it as a stream on the
server side.

I think that serialization mechanism is not a good solution to that problem : it is slow
(no // between network, client and server) and it uses a lot of memory.

Does anyone have a good solution to that problem ?

Re: How to serialize large objects ?


Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382),
May 8, 2002
In EJB 2.0, you can use Local interfaces. The advantage: you can avoid object
serialization for method calls within the same JVM

What is the correct DTD URL (DOCTYPE) for use with a messaging bean? [I
am trying to deploy messaging bean using Weblogic 5.1 SP3. This comes as
an example with weblogic. In the ejb-jar.xml for messaging bean, the
DOCTYPE is defined as : DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems,
Inc.//DTD Enterprise JavaBeans 2.0//EN"
"http://java.sun.com/j2ee/dtds/ejb_2_0.dtd" I found that the url to the
DTD is incorrect. I am unable to deploy my bean. ]
Location: http://www.jguru.com/faq/view.jsp?EID=303322
Created: Jan 15, 2001 Modified: 2001-01-16 07:02:32.632
Author: Matthew Kershaw (http://www.jguru.com/guru/viewbio.jsp?EID=243677)
Question originally posed by Archana Karnik
(http://www.jguru.com/guru/viewbio.jsp?EID=68139

I believe someone asked this question to Umit Yalcinalp in the EJB2.0 Java DevConn
chat on 19-Sep-00. The answer given was "we have not published it yet, except
listing it in the specification. This is because we currently have a draft of the
specification and we needed to be flexible as we make changes to the spec. We plan
to make it available when we have the Proposed Final Draft released."
The DTD has yet to be released.
http://developer.java.sun.com/developer/community/chat/JavaLive/2000/jl0919.htm
l
Comments and alternative answers

Try: http://java.sun.com/dtd/ejb-jar_2_0.dtd
Author: Mihir Kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=312865), Jan
25, 2001
Try: http://java.sun.com/dtd/ejb-jar_2_0.dtd

Try this DTD for weblogic-ejb-jar.xml http://www.b...


Author: Tirumal Chamarti (http://www.jguru.com/guru/viewbio.jsp?EID=44418), Jan
28, 2001
Try this DTD for weblogic-ejb-jar.xml
http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd
Is there any way to read values from an entity bean without locking it for
the rest of the transaction (e.g. read-only transactions)? We have a key-
value map bean which deadlocks during some concurrent reads. Isolation
levels seem to affect the database only, and we need to work within a
transaction.
Location: http://www.jguru.com/faq/view.jsp?EID=303935
Created: Jan 16, 2001 Modified: 2001-01-20 14:26:16.291
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by Alex McManus
(http://www.jguru.com/guru/viewbio.jsp?EID=117866

The only thing that comes to (my) mind is that you could write a 'group accessor' - a
method that returns a single object containing all of your entity bean's attributes (or
all interesting attributes). This method could then be placed in a 'Requires New'
transaction. This way, the current transaction would be suspended for the duration of
the call to the entity bean and the entity bean's fetch/operate/commit cycle will be in
a separate transaction and any locks should be released immediately.

Depending on the granularity of what you need to pull out of the map, the group
accessor might be overkill.

Why am I able to call a business method using the same Remote Interface
reference after I called the remove() method of a Stateless Session Bean??
Location: http://www.jguru.com/faq/view.jsp?EID=307891
Created: Jan 20, 2001 Modified: 2001-01-20 14:40:32.385
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Arun Prasad Paramahamsan
(http://www.jguru.com/guru/viewbio.jsp?EID=257985

Figure 6.9.3 - Client-invoked remove() from the EJB 1.1 specification answers
your question.

For Stateless Session Beans, the container may choose to optimize and re-use the
EJB instance.

Comments and alternative answers

For Stateless session bean two method calls to a bean...


Author: rajesh agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=101019), Jan
25, 2001
For Stateless session bean two method calls to a bean may not invoke the methods
from the same bean. Moreover, the remove() method does not mean physically
removing the bean.

The remove() method on the stateless session bean ...


Author: Mihir Kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=312865), Jan
25, 2001
The remove() method on the stateless session bean causes the bean instance to return
back to the pool. Now, if you are calling a remote method after the remove, then
another instance from the pool will be taken up to service that request. Thus, it
appears to the client that the bean was never removed. However, actually it was
returned back to the pool. Also, which bean instance is going to serve that request
depends upon the pooling strategy, if its LIFO, the same instance will be serving the
request again. As the Specs say: "To the client, it appears as if the client controls the
life cycle of the session object. However, the container handles the create and remove
calls without necessarily creating and removing an EJB instance."

Calling client's remove() method does not invoke the...


Author: prajakt samant (http://www.jguru.com/guru/viewbio.jsp?EID=272793), Feb
5, 2001
Calling client's remove() method does not invoke the corresponding
ejbRemove(),which is actually called during physical remove of the stateless session
bean.
Client's remove() method just returns the bean back to the pool.

Re: Calling client's remove() method does not invoke the...


Author: abhishek agrawal (http://www.jguru.com/guru/viewbio.jsp?EID=117348),
Feb 27, 2002
It appears that sometime container can return same instance of stateless bean
because of optimizaton. But if first call from client has modified some member
variable of bean then getting same instance of bean is too risky. Please clear this
confusion

What is the advantage of using Entity bean for database operations, over
directly using JDBC API to do database operations? When would I use one
over the other?
Location: http://www.jguru.com/faq/view.jsp?EID=308342
Created: Jan 21, 2001 Modified: 2001-02-01 15:53:58.627
Author: Suresh Rangan (http://www.jguru.com/guru/viewbio.jsp?EID=308330)
Question originally posed by sujatha karuppiah
(http://www.jguru.com/guru/viewbio.jsp?EID=218765

Entity Beans actually represents the data in a database. It is not that Entity Beans
replaces JDBC API. There are two types of Entity Beans Container Managed and Bean
Mananged.

In Container Managed Entity Bean - Whenever the instance of the bean is created
the container automatically retrieves the data from the DB/Persistance storage and
assigns to the object variables in bean for user to manipulate or use them. For this
the developer needs to map the fields in the database to the variables in deployment
descriptor files (which varies for each vendor).

In the Bean Managed Entity Bean - The developer has to specifically make
connection, retrive values, assign them to the objects in the ejbLoad() which will be
called by the container when it instatiates a bean object. Similarly in the ejbStore()
the container saves the object values back the the persistance storage. ejbLoad and
ejbStore are callback methods and can be only invoked by the container.
Apart from this, when you use Entity beans you dont need to worry about database
transaction handling, database connection pooling etc. which are taken care by the
ejb container. But in case of JDBC you have to explicitly do the above features.

Comments and alternative answers

The answer is fine, but i want to add onething here.


Author: Banda Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=389958), Apr
5, 2001
what suresh told is exactly perfect. ofcourse, this comes under the database
transations, but i want to add this. the great thing about the entity beans of container
managed, whenever the connection is failed during the transaction processing, the
database consistancy is mantained automatically. the container writes the data stored
at persistant storage of the entity beans to the database again to provide the database
consistancy. where as in jdbc api, we, developers has to do manually. thank you -
Srinivas

Advantages
Author: lyndon mendoza (http://www.jguru.com/guru/viewbio.jsp?EID=411396), Apr
27, 2001
I think the questioner wanted to know if there is an advantage in using entity beans as
opposed to using just the jdbc api. There are a lot of advantages to using Entity Beans
but if speed is paramount it may not be the best solution. If you have an existing
system with tons of existing and well-tested stored procs don't just throw them away. I
am guessing this is the main reason why you asked the question in the first place. You
can leverage these procs with the use of jdbc api.

nice intrepretation but...


Author: Anthony, Cheuk Tung LAI
(http://www.jguru.com/guru/viewbio.jsp?EID=1079401), Apr 25, 2003
It is a nice piece of intrepretation but if we delegate all the task to container to
manage, it seems there are some uncertainty in some errors.

Where and when should I use the context.getPrimaryKey() method rather


than just accessing the Primary Key field(s) directly?
Location: http://www.jguru.com/faq/view.jsp?EID=309978
Created: Jan 23, 2001 Modified: 2001-01-29 17:11:09.38
Author: Sathyanarayana Katakam
(http://www.jguru.com/guru/viewbio.jsp?EID=245368) Question originally posed by
TH Lim (http://www.jguru.com/guru/viewbio.jsp?EID=95720

context.getPrimaryKey() is used when an instance is associated with an EJB


object, and is used during the callback methods (ejbActivate, ejbPassivate, etc
..) and business methods.

This method should be called once the bean is associated with an EJBObject. As, if
the bean is not associated with one, then you will get an IllegalStateException. The
earliest you can call this method without getting an exception is in the
ejbPostCreate() mtehod.

Comments and alternative answers

I found that in some BMP examples, Context.getPrim...


Author: TH Lim (http://www.jguru.com/guru/viewbio.jsp?EID=95720), Jan 29, 2001
I found that in some BMP examples, Context.getPrimaryKey() is used to get the
primary key in the method ejbLoad(). Why one has to do so as the primary key is
aleady stored in its variable?

Re: I found that in some BMP examples, Context.getPrim...


Author: Zahid Iqbal (http://www.jguru.com/guru/viewbio.jsp?EID=58168), Sep 4,
2001
Well, though in some cases it will still work if one is not making use of
Context.getPrimaryKey() (and is simply using EJB variable), but it is not a safe
method to use EJB (PK) variable for this purpose. Let me explain it with an
example.

Suppose the user calls findByPrimaryKey() method on Employee (BMP) Entity


EJB by passing it emp-id=1000. After the container delegates the request to
ejbFindByPrimaryKey() method, it will query the database to check for the
existence of employee for the requested emp-id. Since the
ejbFindByPrimaryKey() is required to return the PrimaryKey value in case the
record is found in the database, so it's upto the programmer either he/she explicitly
set the value of EJB pk variable in this method (though it is not required as it
should be done in ejbLoad()). In our example we consider that there is no such
explicit assignment. So after that container initializes ejb instance based on the
primary key value and then calls ejbLoad() method, it'll not be possible to retrieve
pk value using EJB vairable(s). So the only way to do so is to call
Context.getPrimaryKey() that will return pk value (emp-id=1000 in this case) that
was returned earlier through ejbFindByPrimaryKey() method.

So the above example shows that Context.getPrimaryKey() should be used in


ejbLoad() that will work in all scenarios.

Usually we should get the primary key from the context...


Author: raviprolu pavan kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=217700), Jan 30, 2001
Usually we should get the primary key from the context when we cannot ensure that
the bean has a consistent value because the same bean instance is not used everytime
to execute every call a client makes.

The bean is swapped from and to the pool. So when we use callback methods like
ejbLoad or ejbStore, we should not use the bean instance' primary key but get it from
the bean context which is a more permanent storage than the poolable bean.

When an instance is activated from a pool, a context is attributed to the instance


which has a more permanent state of the bean than the instance itself.

So usually while coding the callback methods like ejbPostCreate,()ejbLoad(),


ejbActivate()and all the finder methods ejbFindByPrimaryKey() ejbFindByX() we
should use context.getPrimaryKey()

And rest of the coding may be done using the bean's key attribute.

Can I use the Apache Web Server with the Sun J2EE Reference
Implementation?
Location: http://www.jguru.com/faq/view.jsp?EID=314392
Created: Jan 28, 2001 Modified: 2001-01-29 17:14:41.91
Author: Sebastian Kim (http://www.jguru.com/guru/viewbio.jsp?EID=314386)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

The answer to your question is yes and no: Under the Jakarta project of Apache, the
product Tomcat, which extends the Apache Web Server, allows you to run your basic
servlets, JSPs and the like.

However, if you want to utilize J2EE's EJB functionality, you need to use an EJB
container, which neither Apache nor Apache+Tomcat is (or rather has). If you're
going down the open source road and sticking to Apache, the appropriate solution is
JBoss (jboss.org). If you're open at this point, but want to stay away from BEA
Weblogic or IBM Websphere, try Enhydra (enhydra.com) by Lutris.

A list of free EJB Containers is listed here.

Comments and alternative answers

If your question is "Can I use Apache as my w...


Author: Uma Maheswari Kandasamy
(http://www.jguru.com/guru/viewbio.jsp?EID=310809), Mar 7, 2001
If your question is "Can I use Apache as my webserver and the j2ee implementation
kit as my app server?" then it should be possible. Though I have not worked under
this combination, I know we can have apache as the webserver and weblogic as the
app server.

Re: If your question is "Can I use Apache as my w...


Author: Richard Robinson
(http://www.jguru.com/guru/viewbio.jsp?EID=395750), Jul 24, 2001

I have Apache 1.3.x (12?) running on a Linux box at home, that has also got the
Sun J2EE reference implentation running. And yes, it works.

If you read the Minimalist User's Guide (for Tomcat 3.2.3 I believe) it talks about
where you can configure Apache and Tomcat so that Apache handles everything
(HTML, GIF, etc) other than servlets and JSPs.

Go to jakarta.apache.org for document.

The EJB container implements the EJBHome and EJBObject classes. For
every request from a unique client, does the container create a separate
instance of the generated EJBHome and EJBObject classes?

Location: http://www.jguru.com/faq/view.jsp?EID=315785
Created: Jan 29, 2001 Modified: 2001-01-31 22:04:14.634
Author: vasanth s (http://www.jguru.com/guru/viewbio.jsp?EID=314566) Question
originally posed by prakash prabhu
(http://www.jguru.com/guru/viewbio.jsp?EID=91561

The EJB container maintains an instance pool. The container uses these instances for
the EJB Home reference irrespective of the client request. while refering the EJB
Object classes the container creates a separate instance for each client request.
Comments and alternative answers

Hi, The instance pool maintainence is up to the i...


Author: Uma Maheswari Kandasamy
(http://www.jguru.com/guru/viewbio.jsp?EID=310809), Mar 7, 2001
Hi, The instance pool maintainence is up to the implementation of the container. If the
container provides one, it is available otherwise it is not mandatory for the provider to
implement it.

Having said that, yes most of the container providers implement the pooling
functionality to increase the performance of the app server. How it is implemented, it
is again up to the implementer.

Coming back to the question and assuming that the container supports pooling ....

1) The home interface can be pooled since it is doesnot hold the state of the client.
Similarly the stateless session BEAN OBJECT INSTANCE can be pooled.
2)The other type of BEAN OBJECT INSTANCES (Stateful session bean and entity
bean) holds the state of the client at any point of the time. So the Bean OBJECT
INSTANCES cannot be pooled here. Maybe, the CLASS INSTANCES can be pooled
and whenever a BEAN OBJECT INSTANCE of this type of beans is idle, it is
passivated and that CLASS INSTANCE is given to the next client.

Note the difference between the CLASS INSTANCE and the OBJECT INSTANCE.

CLASS and OBJECT INSTANCE The instance pool maintainence is up to


the i...
Author: r d (http://www.jguru.com/guru/viewbio.jsp?EID=385239), Mar 22, 2001
I am not clear about this in your previous reply. Will client not need OBJECT
INSTANCE to work with?

The instance pool maintainence is upto the impleme...


Author: Uma Maheswari Kandasamy
(http://www.jguru.com/guru/viewbio.jsp?EID=310809), Mar 7, 2001
The instance pool maintainence is upto the implementation of the container. If the
container provides one, it is available otherwise it is not mandatory for the provider to
implement it.

Having said that, yes most of the container providers implement the pooling
functionality to increase the performance of the app server. How it is implemented, it
is again up to the implementer.

Coming back to the question and assuming that the container supports pooling ....

1. The home interface can be pooled since it is does not hold the state of the
client. Similarly the stateless session BEAN OBJECT INSTANCE can be
pooled.
2. The other type of BEAN OBJECT INSTANCES (Stateful session bean and
entity bean) hold the state of the client at any point of the time. So the Bean
OBJECT INSTANCES cannot be pooled here. Maybe, the CLASS
INSTANCES can be pooled and whenever a BEAN OBJECT INSTANCE of
this type of beans is idle, it is passivated and that CLASS INSTANCE is given
to the next client.

Note the difference between the CLASS INSTANCE and the OBJECT INSTANCE.
The class instance is the one with no values attached to the class attributes and hence
no state maintained. The object instance always holds the state of that object.

Why don't Session Beans have to be re-entrant?


Location: http://www.jguru.com/faq/view.jsp?EID=317316
Created: Jan 31, 2001 Modified: 2001-01-31 22:07:36.201
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by murali P
(http://www.jguru.com/guru/viewbio.jsp?EID=300299

It's not that they don't have to be re-entrant: they cannot be reentrant. The spec
says "The container must ensure that only one thread can be executing an instance
at any time" (EJB 1.1 Spec. 6.11.6). This is partly to simplify development of the
EJB: the bean developer needn't concern himself with concurrency issues. The other
major factor is that Session beans are seen as extenstions of the client - multiple
threads implies multiple clients, which does not fit with this view of an extension.
Granted that stateless sessions are used more as facades over entities or service
interfaces than as 'extensions of the client', the programming model (and the
container's developer's task) are much simpler if we restrict session beans to one
thread of execution at any one time. Also, because of the way that stateless session
beans are pooled by the container, allowing two threads in one at once is not really
needed.

Of course, the 'Gotcha' here is that session beans can't be 'called back' to from
another EJB even within the same transaction. The reason that Entity beans are
allowed to be reentered (if their deployment descriptor says they're built that way) is
that there are (arguably) more cases when an entity might need to be called back
than there are for sessions.

Comments and alternative answers

session bean reeentrance: easy answer


Author: prajakt deshpande (http://www.jguru.com/guru/viewbio.jsp?EID=707071),
Jan 3, 2002
EJB Spec 1.1 6.5.6 Serializing session bean methods A container serializes calls to
each session bean instance. Most containers will support many instances of a session
bean executing concurrently; however, each instance sees only a serialized sequence
of method calls. Therefore, a session bean does not have to be coded as reentrant.

Where can I find the DTD's for EJB Deployment Descriptors?


Location: http://www.jguru.com/faq/view.jsp?EID=318375
Created: Feb 1, 2001 Modified: 2001-02-01 17:01:16.523
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by KiranKumar Ramamurthy
(http://www.jguru.com/guru/viewbio.jsp?EID=228971

• EJB 1.1
http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd
• EJB 2.0
http://java.sun.com/dtd/ejb-jar_2_0.dtd

When using EJB and making use of connection pools. How can changes to
the database be audited per user?
Location: http://www.jguru.com/faq/view.jsp?EID=318819
Created: Feb 1, 2001 Modified: 2001-02-02 12:11:16.527
Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492) Question originally posed by
Chris Melville (http://www.jguru.com/guru/viewbio.jsp?EID=305546

This is quite not the case with EJBs. When you create a connection pool, the J2EE
server is the client for the database. Since a J2EE environment is a shared
environment, the practice is setup a very small number of connection pools, and
recycle the same pool of connections across several invocations (across several
"users").

The notion of a database user does not therefore exist. For instance, you may have
1000 concurrent HTTP sessions, but only 10% of them may be using connections
actively. In such cases if you try to allocate connections on user bases, you'll have
too many idle connections, ultimately paying performance penalty.

To answer your question, there is no direct and simple way of determining who
changed what. A reasonable approach is to constrain the methods on various beans
based on user roles, and log/audit certain business events (not database events).

An alternate approach follows(thanks to Siva Visveswaran In order to do this we


basically need to distinguish between the database user (used for connection
therefore pooled) and the application user (not used to connect to db but perhpas
part of an access control group that may vey well mirror your pools).

For this we typically don't rely on DBMS logging but instead perform application level
logging using LAST_UPDATED_USER and LAST_UPDATE _TIMESTAMP columns on the
table. Okay so how do we populate the LAST_UPDATED_USER with the real user
who's updating the information? We can obtain it from the Session/Entity context in
the EJB.

Comments and alternative answers

Sometimes you need to audit changes in the database...


Author: Adam Skobodzinski (http://www.jguru.com/guru/viewbio.jsp?EID=130115),
Feb 5, 2001
Sometimes you need to audit changes in the database on "per user" basis. This is
especially true if you setup security in a database at the "row level". I use this
technique for virtual private databases (VPD). I want to make sure that user can see
only its own data and it is best if this security chcek is done at the database level. If
you want to put entity beans into this solutions you have to create database pools for
each user and deploy beans accordingly. This is not a very scalable solution. Is there
any way around this?

What about setting the res-auth to Application and...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Feb 5, 2001
What about setting the res-auth to Application and calling
DataSource.getConnection(String user, String password)?

My take on this is, application level logging is c...


Author: Shiv Swamy (http://www.jguru.com/guru/viewbio.jsp?EID=324245), Feb 8,
2001
My take on this is, application level logging is cumbersome and too expensive for
performance based application but if you have business critical application with a
need to maintain history, in that case you can have an auditing mechanism where you
can store the username, fieldchanged, newvalue, oldvalue, timestamp. This can be
made as a history object that is connected to a table in the database.

When using EJB and making use of connection pools. How can changes to the
database be audited per user?
Author: Allen Fogleson (http://www.jguru.com/guru/viewbio.jsp?EID=344251), Jun
3, 2001
We actually had a client insist on this since the DB vendor had convinced the client
that only the database could effectively audit transactions. So we were forced into
designing a system that did this. What we ended up doing was not using any entity
beans, and all calls to the database used the datasource.getConnection(user, password)
method. Im not sure how the container manages that, probably instantiates a new
connection object, thus killing all the performace gained using a pool, but it worked.
(slow... and im sure that will be the complaint next, but it worked)

In EJB 2.0, What is a cmr-field. How can I differentiate between a cmr-field


and a cmp-field?
Location: http://www.jguru.com/faq/view.jsp?EID=319227
Created: Feb 2, 2001 Modified: 2001-02-13 08:29:21.802
Author: prajakt samant (http://www.jguru.com/guru/viewbio.jsp?EID=272793)
Question originally posed by vikash mall
(http://www.jguru.com/guru/viewbio.jsp?EID=214765

CMR stands for Container Managed Relation Field.

In EJB 2.0 Persistence of CMP bean is managed by a Persistence manager


The developer has to write his bean implementation class as abstract and Persistence
Manager generates a concrete class for the bean.

I will try to give an Example:-


Bean Developers Class:-
public abstract EmployeeBean implements
javax.ejb.EntityBean {

public abstract void setFirstName(String firstName);


public abstract String getFirstName();
public abstract void setAddress(Address addr);
public abstract Address getAddres();

}//end of class

where Address is another abstract class(dependant object) having streetno,zip and


other details

In Deployment Descriptor:-

<cmp-field><field-name>firstName</field-name></cmp-field>

<cmr-field>
<cmr-field-name>myaddress</cmr-field-name>
<cmr-field-type>Address</cmr-field-type>
</cmr-field>

Thus when Persistence manager generates the concrete class for above abstract
class.It creates a variable "firstName" of type String as CMP and "myaddress" which
of type Address, which is a CMR or also called as dependant object.
Regards
Prajakt
Comments and alternative answers

How the Dependant objects are mapped?


Author: RATHAKRISHNAN K
(http://www.jguru.com/guru/viewbio.jsp?EID=230041), Oct 24, 2001
firstName has been mapped to a field as given, but how about the Address Object's
fields? How do we specify mapping between the fields of Address objects and that of
the table in the DB?

correction
Author: Venugopal Thachappilly
(http://www.jguru.com/guru/viewbio.jsp?EID=286533), Jul 23, 2002
Atleast in the latest specification of EJB 2.0, the above said is not entirely correct.
CMR is a relationship between two entity beans and the relationship is also managed
by the container. In the above example, address wouldn't be a value object, but a full
fledged entity bean. Refer to the spec or a book for details.

How can EJB's be accessed through Firewalls?


Location: http://www.jguru.com/faq/view.jsp?EID=319285
Created: Feb 2, 2001 Modified: 2001-02-02 11:44:26.74
Author: Suresh Rangan (http://www.jguru.com/guru/viewbio.jsp?EID=308330)
Question originally posed by shoban babu
(http://www.jguru.com/guru/viewbio.jsp?EID=87955

With RMI over IIOP, RMI based EJB servers can be mixed with RMI based or CORBA
Based EJB servers because everyone are propagating context information using IIOP.

RMI has the ability to tunnel through Firewalls. This is very slow and arduous
process, and it is really a security loophole. Special IIOP Firewall Proxies are
developed and available that will permit IIOP traffic to pass through. If you are using
IIOP protocol, any RMI or CORBA code you write will navigate the firewall.

Limitations are the effectiveness of the proxies. ie you will have to have proxies on
both client and server.

One cant set up a B2C site with a IIOP proxy thinking that will be a solution for the
problem. Only for limited applications where the server and client can be controlled,
IIOP proxy add value.

IONA provides a proxy called WonderWall and Borland provides the VisiBroker
GateKeeper.
Comments and alternative answers

You could also use the Simple Object Access Protocol...


Author: Steve Sarandos (http://www.jguru.com/guru/viewbio.jsp?EID=321309), Feb
5, 2001
You could also use the Simple Object Access Protocol (SOAP). This technology
sends remote procedure calls in XML format which will pass right thru the firewall on
the HTTP port (like a web page). The performance might be a little slower than IIOP
but it will work without having to reconfigure the firewall or install proxies. An open
source Java version is available at xml.apache.org.

Re: You could also use the Simple Object Access Protocol...
Author: Prasanna Singh (http://www.jguru.com/guru/viewbio.jsp?EID=280922),
Mar 27, 2001
I was trying to authenticate firewall inorder to send SOAP message accross the
internet and i was using java authenticate class. But did not work for me. What is
the correct way to do the authentication ? thanks

Re: Re: You could also use the Simple Object Access Protocol...
Author: ce ce (http://www.jguru.com/guru/viewbio.jsp?EID=238982), Mar 27,
2001
I think it depends on what type of authentication the firewall/proxy is
expecting. If your firewall wants NTLM level authentication then java may
cause you a problem since when the HTTP request goes out and the firewall
returns an NTML authentication msg the JVM may see that as an error. What
type of firewall are you using?

How can EJB's be accessed through Firewalls?


Author: L Gilbert (http://www.jguru.com/guru/viewbio.jsp?EID=748154), Feb 5,
2002
You can also use IIOPS to tunnel IIOP via SSL e.g. port 447. This relies on the client
side ORB to establish the session. For setup, see: Chapter 8 of:- WebSphere Advanced
Edition: Security
http://publib-b.boulder.ibm.com/Redbooks.nsf/RedbookAbstracts/sg246520.html

Does EJB 1.1 support mandate the support for RMI-IIOP ? What is the
meaning of "the client API must support the Java RMI-IIOP programming
model for portability, but the underlying protocol can be anything" ?
Location: http://www.jguru.com/faq/view.jsp?EID=319549
Created: Feb 2, 2001 Modified: 2001-02-02 16:26:35.097
Author: Nick Minutello (http://www.jguru.com/guru/viewbio.jsp?EID=222214)
Question originally posed by sanjeev jain
(http://www.jguru.com/guru/viewbio.jsp?EID=211266

EJB1.1 does mandate the support of RMI-IIOP.

OK, to answer the second question:


There are 2 types of implementations that an EJB Server might provide: CORBA-
based EJB Servers and Proprietry EJB Servers. Both support the RMI-IIOP API but
how that API is implemented is a different story. (NB: By API we mean the interface
provided to the client by the stub or proxy).

A CORBA-based EJB Server actually implements its EJB Objects as CORBA Objects (it
therefore encorporates an ORB and this means that EJB's can be contacted by
CORBA clients (as well as RMI-IIOP clients)

A proprietry EJB still implements the RMI-IIOP API (in the client's stub) but the
underlying protocol can be anything. Therefore your EJB's CANNOT be contacted by
CORBA clients.

The difference is that in both cases, your clients see the same API (hence, your client
portability) BUT how the stubs communicate with the server is different.

Does RMI-IIOP support dynamic downloading of classes?


Location: http://www.jguru.com/faq/view.jsp?EID=320155
Created: Feb 3, 2001 Modified: 2001-02-13 08:37:58.472
Author: RaghuRam Vudathu (http://www.jguru.com/guru/viewbio.jsp?EID=319533)
Question originally posed by Alex McManus
(http://www.jguru.com/guru/viewbio.jsp?EID=117866

No, RMI-IIOP doesn't support dynamic downloading of the classes as it is done with
CORBA in DII (Dynamic Interface Invocation).Actually RMI-IIOP combines the
usability of Java Remote Method Invocation (RMI) with the interoperability of the
Internet Inter-ORB Protocol (IIOP).So in order to attain this interoperability between
RMI and CORBA,some of the features that are supported by RMI but not CORBA and
vice versa are eliminated from the RMI-IIOP specification.You can download from the
Sun Microsystems RMI-IIOP home page.

And on the other hand if your question is

Does RMI-IIOP support code downloading for Java objects sent by value
across an IIOP connection in the same way as RMI does across a JRMP
connection?
Then the answer is Yes.

Comments and alternative answers

The JDK 12 redeisgn RMI


Author: zhen liu (http://www.jguru.com/guru/viewbio.jsp?EID=385991), Apr 4, 2001
The JDK 12 support the dynamic class loading.

I would like to bind my EJB object (container managed or bean managed) to


Oracle 8 DBMS_ALERT or DBMS_PIPE so that my object is notified whenever
there is an update in the database by some batch process. Is it possible to
do? If so, how?
Location: http://www.jguru.com/faq/view.jsp?EID=322782
Created: Feb 7, 2001 Modified: 2001-02-13 08:30:20.201
Author: Alexey Ryndin (http://www.jguru.com/guru/viewbio.jsp?EID=221245)
Question originally posed by mrinal mitra
(http://www.jguru.com/guru/viewbio.jsp?EID=241593

If you use Oracle 8 you can use ORACLE ADVANCE QUERYING and subscribe for it
with JMS, so you object can register some message listener, which will be notified
when message sent by your batch process will arrive. For more detail information
how to lookup Oracle Advance Querying system and to subscribe your JMS receiver
or subscriber, look
http://technet.oracle.com/docs/products/oracle8i/doc_library/817_doc/appdev.817/a
85456.pdf. (You may need to register yourself on technet.oracle.com first).
Comments and alternative answers

Would this architecture actually work with CMP & BMP?


Author: Pratap Das (http://www.jguru.com/guru/viewbio.jsp?EID=129542), Mar 26,
2001
How would a non-Message Driven Bean be able to receive this JMS message from
Oracle? Wouldn't its passivation have an impact on this architecture? Would you
clarify a bit more about this solution? --Das

Re: Would this architecture actually work with CMP & BMP?
Author: Stu Charlton (http://www.jguru.com/guru/viewbio.jsp?EID=423826),
May 17, 2001
Entities and Sessions can't directly receive messages from JMS. You would need
an active object to montior the JMS queue, which would then act as an EJB client.
See the J2EE Patterns on http://developer.java.sun.com for an example of adapting
JMS onto EJB's without message-driven beans.

What is a Message Driven Bean, What functions does a message driven bean
have and how do they work in collaboration with JMS?
Location: http://www.jguru.com/faq/view.jsp?EID=327430
Created: Feb 13, 2001 Modified: 2001-02-13 08:45:45.329
Author: ranjay sinha (http://www.jguru.com/guru/viewbio.jsp?EID=290360)
Question originally posed by vasanth s
(http://www.jguru.com/guru/viewbio.jsp?EID=314566

Message driven beans are the latest addition to the family of component bean types
defined by the EJB specification. The original bean types include session beans,
which contain business logic and maintain a state associated with client sessions, and
entity beans, which map objects to persistent data.

Message driven beans will provide asynchrony to EJB based applications by acting as
JMS message consumers. A message bean is associated with a JMS topic or queue
and receives JMS messages sent by EJB clients or other beans.

Unlike entity beans and session beans, message beans do not have home or remote
interfaces. Instead, message driven beans are instantiated by the container as
required. Like stateless session beans, message beans maintain no client-specific
state, allowing the container to optimally manage a pool of message-bean instances.
Clients send JMS messages to message beans in exactly the same manner as they
would send messages to any other JMS destination. This similarity is a fundamental
design goal of the JMS capabilities of the new specification.

To receive JMS messages, message driven beans implement the


javax.jms.MessageListener interface, which defines a single "onMessage()" method.

When a message arrives, the container ensures that a message bean corresponding
to the message topic/queue exists (instantiating it if necessary), and calls its
onMessage method passing the client's message as the single argument. The
message bean's implementation of this method contains the business logic required
to process the message:

public void onMessage(javax.jms.Message message)


// code to handle message

Note that session beans and entity beans are not allowed to function as message
beans.

Comments and alternative answers

You can learn more about asynchronous messaging and...


Author: Suresh Rangan (http://www.jguru.com/guru/viewbio.jsp?EID=308330), Feb
13, 2001
You can learn more about asynchronous messaging and message beans here.

See this article


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 11, 2001
The article EJB 2 Message-Driven Beans by Dion Almaer walks through creating and
using a MessageDrivenBean.

Message Driven Bean


Author: Manjula Gundluri (http://www.jguru.com/guru/viewbio.jsp?EID=738246),
Jan 29, 2002
When we have JMS already present to handle asynchronous messages,then why we
have Message Driven beans in EJB2.0

Re: Message Driven Bean


Author: Ashutosh Rai (http://www.jguru.com/guru/viewbio.jsp?EID=769095), Feb
23, 2002
A quote from this article will probably answer your question. The aricle:
EJB 2 Message-Driven Beans by Dion Almaer.
The quote:
"That was pretty easy. That is the great thing about MDBs. We don't have lots of ugly
JMS code (like we had in the client, or like we would have if we wrote the consumer
from scratch)"

-ashutosh
When calling an EJB from another EJB should they both be packaged in
same JAR?. Are the any preferences for Weblogic or any other servers?
Location: http://www.jguru.com/faq/view.jsp?EID=332819
Created: Feb 19, 2001 Modified: 2001-02-25 07:49:39.083
Author: Alexey Ryndin (http://www.jguru.com/guru/viewbio.jsp?EID=221245)
Question originally posed by Junaid Shamim
(http://www.jguru.com/guru/viewbio.jsp?EID=136546

Definitely not. You can use any object published in JNDI by looking up it by name,
obtain reference to it and narrowing this reference. As far as I know this can be done
with any J2EE compatible server.

The only possible catch is to have the client classes available to the calling bean. See
What classes does a client application need to access EJB?

Comments and alternative answers

But If the beans are in the same J2EE Application unit ...
Author: Jonathan Morrissey (http://www.jguru.com/guru/viewbio.jsp?EID=330060),
Mar 19, 2001
I agree with the previous answer that the beans do not need to be in the same jar, but
it's worth knowing that if they are in the same container you can use EJB references
(see EJB spec 1.1, page 207, Sect 14.3). I have used this in my current project with a
performance gain of over 50%. Regards, Jonathan

What about a J2EE application accescing a EJB in another EJB Applicaction?


Author: Luis Soeiro (http://www.jguru.com/guru/viewbio.jsp?EID=447389), Jun 28,
2001
I am trying to have an EJB in one J2EE application (.ear file), A, access an EJB in
another J2EE application, B. If you just setup JNDI names and EJB references,
application "A" can't find B's Home Interface. If you get the generated application
"B" Client jar (with the required Stubs) and add it to the application "A" EJB jar, you
get another error at runtime, meaning App "A" can't still find the EJB located in the
deployed App "B". Is there any special packaging necessary?

MDB to Stateless session bean call


Author: Ashutosh Rai (http://www.jguru.com/guru/viewbio.jsp?EID=769095), Feb
23, 2002
Hi, I am trying to call a method on a stateless session bean. The session bean is in a
seperate ear file. Both the beans are getting deployed successfully. But the jndi lookup
is not working. When we use a standalone client, we specify the naming provider
using a jndi.properties file. For calling a bean from another bean how does the calling
bean get naming provider info?

In my case, I am getting a "name not found" exception. Is it essential to give a


reference to the session bean in the MDB deployment descriptor? I feel that the call
should be similar to using a standalone client, if not what is the difference?
I am using Oracle j2ee container (orion)
Thanks
-ashutosh

Can I re-use the same Primary key class for various Entity Beans?
Location: http://www.jguru.com/faq/view.jsp?EID=342031
Created: Mar 1, 2001 Modified: 2001-03-01 15:23:42.06
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Roy abraham
(http://www.jguru.com/guru/viewbio.jsp?EID=340391

Yes, you sure can.


Comments and alternative answers

same Primary ket class


Author: Mahesh Bhagia (http://www.jguru.com/guru/viewbio.jsp?EID=429170), May
26, 2001
How will you be able same Primary key for various Entity bean, because according to
EJB specification, pk for eg BuyerBean is BuyerPK, that means PK name is related to
the name of the Entity Bean

Re: same Primary ket class


Author: vijay Yellai (http://www.jguru.com/guru/viewbio.jsp?EID=431786), May
31, 2001
that is just a naming convention used for readability and understanding. Normally
it would be easier for another develeoper to maintain ones code if the PK class was
named after the bean it belongs to. This is possible beacuse the association of the
primary key is done only during the deploment and the deployer can associate any
PK class with any bean aslong as the fields in the PK class exist with the same
name in the bean as persistant fields

Can you control when passivation occurs?


Location: http://www.jguru.com/faq/view.jsp?EID=342056
Created: Mar 1, 2001 Modified: 2002-09-25 07:14:48.493
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Kim Johansson (http://www.jguru.com/guru/viewbio.jsp?EID=329972

The developer, according to the specification, cannot directly control when


passivation occurs. Although for Stateful Session Beans, the container cannot
passivate an instance that is inside a transaction. So using transactions can be a a
strategy to control passivation.

The ejbPassivate() method is called during passivation, so the developer has


control over what to do during this exercise and can implement the require optimized
logic.
Some EJB containers, such as BEA WebLogic, provide the ability to tune the
container to minimize passivation calls.

Taken from the WebLogic 6.0 DTD -


"The passivation-strategy can be either "default" or "transaction". With the default
setting the container will attempt to keep a working set of beans in the cache. With
the "transaction" setting, the container will passivate the bean after every
transaction (or method call for a non-transactional invocation)."

Where can I find an example of the command pattern implemented with


EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=342497
Created: Mar 2, 2001 Modified: 2001-03-07 07:32:55.824
Author: Jonathan Morrissey (http://www.jguru.com/guru/viewbio.jsp?EID=330060)
Question originally posed by Devendra Partap
(http://www.jguru.com/guru/viewbio.jsp?EID=64273

There is a discussion of this pattern on the serverSide site titled Command Pattern
(Abstracted value-objects in/out of EJB).

How to create serialized deployment descriptor in EJB 1.0?


Location: http://www.jguru.com/faq/view.jsp?EID=345478
Created: Mar 6, 2001 Modified: 2001-03-07 07:34:33.48
Author: Jayesh Nazre (http://www.jguru.com/guru/viewbio.jsp?EID=44356)
Question originally posed by Preeti Aggarwal
(http://www.jguru.com/guru/viewbio.jsp?EID=338884

Well most of the Application servers have tools for creating the deployment
descriptor. But if they do not have it, then you can use the SessionDescriptor class
for creating a deployment descriptor for session beans and EntityDescriptor class for
entity beans. For further reference refer the following JavaDoc

But remember that EJB 1.1 uses XML for specifying the deployment descriptor and
these classes have since been deprecated.

Where I could find good literature on J2EE architecture?


Location: http://www.jguru.com/faq/view.jsp?EID=346382
Created: Mar 7, 2001 Modified: 2001-03-07 08:18:31.866
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Dnyanesh Bendre
(http://www.jguru.com/guru/viewbio.jsp?EID=274207

The best place to start is the J2EE Blue Prints located at


http://java.sun.com/j2ee/blueprints/index.html
Comments and alternative answers

Sun includes a good J2EE Developer's Guide with their...


Author: Rahul Khimasia (http://www.jguru.com/guru/viewbio.jsp?EID=55768), Mar
7, 2001
Sun includes a good J2EE Developer's Guide with their J2EE reference
implementation soft documentation. The included guide is in HTML format, but you
can also download a PDF version from
http://java.sun.com/j2ee/j2sdkee/devguide1_2_1.pdf.

The blueprint is not a valid architecture


Author: ben menasha menasha
(http://www.jguru.com/guru/viewbio.jsp?EID=399216), May 27, 2001
The blueprint (despite how it is marketed) is really just a showcase of many different
technologies. To anyone who has developed a commerce site or any complex web
application the petstore is massive, unmaintable and complex. The whole model
architecture is duplicated in both the web app and ejb module, the amount of code for
the functionality products is nothing to be proud off. In fact the intro states that that
for a real project this is overkill and one should not develop this an exacting MVC
architecture as it is costly and duplicates effort all over the place. J2EE application
should primarly be designed just as any OO application is written, the services that
J2EE provides can be used and should be used when needed, but I personaly don't
think that the petstore is a good example of application architecture. Althugh it is a
great sample app for showing off all the technologies at once.

Where can I find "EJB/J2EE coding standards" ?


Location: http://www.jguru.com/faq/view.jsp?EID=346527
Created: Mar 7, 2001 Modified: 2001-03-11 16:08:12.033
Author: Jonathan Morrissey (http://www.jguru.com/guru/viewbio.jsp?EID=330060)
Question originally posed by Yatin Sanghvi
(http://www.jguru.com/guru/viewbio.jsp?EID=87651

Here are some useful links on this topic:

• The J2EE Blue Prints


• The ServerSide.com patterns

There is also a useful thread on the topic of J2EE naming standards here .
Comments and alternative answers

RE: Where can I find "EJB/J2EE coding standards" ?


Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985), Mar
25, 2001
I'm not aware about generally accepted coding standards around.

Looking at the Sun site, in "Java Live" chat about J2EE standardization, there're
people asking for coding standards to Sun: check this link:
http://developer.java.sun.com//developer/community/chat/JavaLive/2000/jl0201.html.

How can I use a local DTD to validate ejb-jar.xml instead of going to SUN's
server as specified in DOCTYPE element?
Location: http://www.jguru.com/faq/view.jsp?EID=347169
Created: Mar 8, 2001 Modified: 2002-12-01 15:45:28.793
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
nicole li (http://www.jguru.com/guru/viewbio.jsp?EID=281530

You can do this by specifying a local DTD-file in the SYSTEM property of the
DOCTYPE element. Here is an example:

If your DTD was located inside a localfolder - "C:/localdtd" then your DOCTYPE
element should be as follows:

<!DOCTYPE ejb-jar SYSTEM "file:C:/localdtd/ejb-jar.dtd">

Comments and alternative answers

No don't change the doctype! You'll have to change...


Author: Gene De Lisa (http://www.jguru.com/guru/viewbio.jsp?EID=38746), Mar 16,
2001
No don't change the doctype! You'll have to change it back! Look at the
org.xml.sax.EntityResolver interface. if you have sun's implementation look at
com.sun.xml.parser.Resolver

The Weblogic 6.0 ejbc only permit the PULBLIC DOCTYPE


Author: Qiao Lian (http://www.jguru.com/guru/viewbio.jsp?EID=410298), Apr 26,
2001
I edit the XML with local DTD, then the Weblogic 6.0 ejbc report error DOCTYPE.
The error do not uccor when I use the PUBLIC DOCTYPE.

Can the activation/passivation of beans be tuned so that passivation is NOT


done unless absolutely necessary. Which servers support this, and how?
Location: http://www.jguru.com/faq/view.jsp?EID=348928
Created: Mar 11, 2001 Modified: 2001-03-11 16:14:47.094
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by David Mullineux
(http://www.jguru.com/guru/viewbio.jsp?EID=55639

Please see this FAQ.


Comments and alternative answers

ACTIVATION/PASSIVATION
Author: OBUCHI MACHINI (http://www.jguru.com/guru/viewbio.jsp?EID=297581),
Apr 3, 2001
Yes,this can be tuned accordingly.. The APPSERVER Which I know of is
"WEBLOGIC 5.1 ". In this u can tune the Activation/Passivation

Re: ACTIVATION/PASSIVATION
Author: Gautam Mehta (http://www.jguru.com/guru/viewbio.jsp?EID=390509),
Apr 13, 2001
can u explain it in a bit detail Thanks Gautam

Re: ACTIVATION/PASSIVATION
Author: lakshman prasad (http://www.jguru.com/guru/viewbio.jsp?EID=423825),
Jun 17, 2001
Dear Obuchi, Can explain little more about how to do this tunning in weblobic app
sever.

How can I pass a ResultSet from an EJB to a client? what are the best
classes to use?
Location: http://www.jguru.com/faq/view.jsp?EID=349555
Created: Mar 12, 2001 Modified: 2001-03-15 13:41:49.123
Author: Jonas Bergqvist (http://www.jguru.com/guru/viewbio.jsp?EID=81465)
Question originally posed by Alec Smecher
(http://www.jguru.com/guru/viewbio.jsp?EID=319506

It is better that you iterate through the ResultSet on the server side and return a
Vector of Vectors (or something else similar) representing the rows and columns of
the ResultSet. Everything that is sent between the EJB server and the EJB client
should of course be serializable (due the to RMI specification). A ResultSet is NOT
serializable and therefore you should (can) not return a ResultSet.
Comments and alternative answers

Use can use CachedRowSet to pass ResultSet back to client and to other beans.
Author: Stan UA1OUT (http://www.jguru.com/guru/viewbio.jsp?EID=555595), Nov
21, 2001
Check out sun.jdbc.rowset.CachedRowSet class.

It can be used to disconnect a rowset from the DB and passed back to the client. Since
cached rowset implements javax.sql.RowSet the client can manipulate the
disconnected instance of the cached class as usual.

To be able to use CachedRowSet you have to download and put on your client's and
server's classpath rowset.jar file.

The above is described in more details in "Data transfer Rowset" EJB pattern.

Regards,

Stan

How can I get the underlying JDBC connection which the CMP bean is using?
Location: http://www.jguru.com/faq/view.jsp?EID=351799
Created: Mar 15, 2001 Modified: 2001-03-15 15:00:32.431
Author: sukumar kaukuntla (http://www.jguru.com/guru/viewbio.jsp?EID=351793)
Question originally posed by prateek saxena
(http://www.jguru.com/guru/viewbio.jsp?EID=304604

Technically speaking you can't. But you can access a JDBC connection within the
same transaction from a CMP bean using the following XML deployment descriptor :

<enterprise-beans>
<entity>
<resource-ref>
<description>Datasource for the myDB database</description>
<res-ref-name>jdbc/myDB</res-ref-name>
<res-type>java.sql.Datasource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
...
</entity>
....
</enterprise-beans>
Comments and alternative answers

sir i need some EJB examples can u provide it to me?...


Author: sudhes kumar palaniswamy
(http://www.jguru.com/guru/viewbio.jsp?EID=352874), Mar 16, 2001
sir i need some EJB examples can u provide it to me? my emailid is sudhes@usa.net
thanking u sudhes india

Might be possible...
Author: Ivo Limmen (http://www.jguru.com/guru/viewbio.jsp?EID=327483), Apr 9,
2001
The J2EE 1.2 specifications state that retrieving the JDBC connection should but
possible but it might be having a context that is not stated as specified in the
specifications. This is a piece of the specifications:
This specification recommends, but does not require, that all resource factory
references be organized in the subcontexts of the application component’s
environment, using a different subcontext for each resource manager type. For
example, all JDBC™ DataSource references should be declared in the
"java:comp/env/jdbc" subcontext, all JMS connection factories in the
"java:comp/env/jms" subcontext, all JavaMail connection factories in the
"java:comp/env/mail" subcontext, and all URL connection factories in the
"java:comp/env/url" subcontext.
This means that you will have to lookup in your console application at the used
naming facilities and see what the naming context is for the JDBC connections. You
can use a context lookup to retrieve the Bean's JDBC datasource.

With regard to Entity Beans, what happens if both my EJB Server and
Database crash, what will happen to unsaved changes? Is there any
transactional log file used?
Location: http://www.jguru.com/faq/view.jsp?EID=412828
Created: Apr 30, 2001
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by ponraj sivaram
(http://www.jguru.com/guru/viewbio.jsp?EID=314542

Actually, if your EJB server crashes, you will not even be able to make a connection
to the server to perform a bean lookup, as the server will no longer be listening on
the port for incoming JNDI lookup requests. You will lose any data that wasn't
committed prior to the crash. This is where you should start looking into clustering
your EJB server.
Comments and alternative answers

Answer
Author: Uma Maheswari Kandasamy
(http://www.jguru.com/guru/viewbio.jsp?EID=310809), May 6, 2001
Hi, Any unsaved and uncommited changes are lost the moment your EJB Server
crashes. If your database also crashes, then all the saved changes are also lost unless
you have some backup or some recovery mechanism to retrieve the data. So consider
database replication and EJB Clustering for such scenarios, though the occurence of
such a thing is very very rare. Thx, Uma

Database's log files will take care of them


Author: Rahul kumar Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=4809),
May 7, 2001
All databse have the concept of log files(for exampe oracle have redo log files
concept). So if data bases crashes then on starting up they fill look up the log files to
perform all pending jobs. But is EJB crashes, It depend upon the container how
frequenlty it passivates or how frequesntly it refreshes the data with Database

For Entity Beans, What happens to an instance field not mapped to any
persistent storage,when the bean is passivated ?
Location: http://www.jguru.com/faq/view.jsp?EID=412829
Created: Apr 30, 2001
Author: Jonathan Morrissey (http://www.jguru.com/guru/viewbio.jsp?EID=330060)
Question originally posed by bob miller
(http://www.jguru.com/guru/viewbio.jsp?EID=342494

The specification infers that the container never serializes an instance of an Entity
bean (unlike stateful session beans). Thus passivation simply involves moving the
bean from the "ready" to the "pooled" bin. So what happens to the contents of an
instance variable is controlled by the programmer. Remember that when an entity
bean is passivated the instance gets logically disassociated from it's remote object.

Be careful here, as the functionality of passivation/activation for Stateless Session,


Stateful Session and Entity beans is completely different. For entity beans the
ejbPassivate method notifies the entity bean that it is being disassociated with a
particular entity prior to reuse or for dereferencing and possible garbage collection.
Unlike stateful session beans the state does not need to be stored in secondary
storage as by definition it already exists in permanent storage.
How can I connect to multiple databases using CMP I have 6 SQL servers
running on Windows NT platform. I need to connect to one of these
depending on customer login . How can I achieve this using CMP? I can not
pass fixed connection String to the container as everytime I am changing
SQL server depending on Customer.
Location: http://www.jguru.com/faq/view.jsp?EID=421472
Created: May 14, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Subodh Chintawar (http://www.jguru.com/guru/viewbio.jsp?EID=416739

Theoretically you can achieve it with CMP, but using 6 different instances of the
application server, or 6 'applications' on your application server (if it will allow you).
Each application will connect to one of your 6 databases.
Based on the login of your customer, you get the correct InitialContext().

Comments and alternative answers

Other ideas..
Author: Stu Charlton (http://www.jguru.com/guru/viewbio.jsp?EID=423826), May
17, 2001
Some extended CMP implementations should allow for multiple mappings inside an
EJB JAR. WebGain's TopLink, for instance, might be able to do this, since it adds a
lot of features outside the realm of CMP.

Re: Other ideas..


Author: Cornel Antohi (http://www.jguru.com/guru/viewbio.jsp?EID=491370),
Sep 15, 2001
A question: i can use only one BMP that will receive the databaseURL as
parameter ? That are the implications ?

6 diff databases
Author: bidarkar jay kumar (http://www.jguru.com/guru/viewbio.jsp?EID=440821),
Jun 18, 2001
i trie using weblogic5.1(though older) but it worked when i used to connect to 3
different databases.i guess this should happen in any case.

Other Ideas!.. Using Different Connection Pools


Author: Sridhar Panatula (http://www.jguru.com/guru/viewbio.jsp?EID=232093), Oct
2, 2001
In computing environments where there is no container kind of stuff, I would have
made a connection to a server depending upon the login by associating groups with
servers and thus giving a different servername and other details to connect.
Like Different DSN name in Windows Environment.
I would try to achieve the same thing here by using different connection pools and
associating groups of users with Connection Pool.
I would query for the login properties before selecting the dbConn(Conection pool
name).
Good Luck,

Does WebSphere support EJB 2.0?


Location: http://www.jguru.com/faq/view.jsp?EID=424210
Created: May 18, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
ram t (http://www.jguru.com/guru/viewbio.jsp?EID=244164

No, it doesn't. At this point in time, the EJB 2.0 specification is not completely
finalized.

Why can't a Stateless SEssion Bean implement the SessionSynchronization


interface? it might also want to be notified of the transaction events.
Location: http://www.jguru.com/faq/view.jsp?EID=424215
Created: May 18, 2001 Modified: 2002-01-09 06:43:11.325
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Feng Xue (http://www.jguru.com/guru/viewbio.jsp?EID=56913

It's just because a Stateless Session Bean does not have state. The container does
not guarantee (like for the Stateful SEssion Bean) that the bean that will be used on
two method calls, will be the same.
Comments and alternative answers

Here is a more precise answer.


Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), May 18, 2001

To be precise, for the sake of argument, let's say that a stateless bean can maintain (it
can, in fact) state.

During a transaction, a client can invoke one or more methods on a bean. However,
the container does not guarantee that the same bean instance is used for all calls.
Imagine a pool of instances participating in a group of concurrent trasnactions. Since
an instance can participate in multiple ongoing transactions, it can not compensate (or
synchronize) itself due to transaction commit/rollback. You can try to visualize this by
trying to write some code for synchronization.

It would make sense with container-managed transactions


Author: Heikki Linnakangas (http://www.jguru.com/guru/viewbio.jsp?EID=722172),
Jan 16, 2002
If you used container-managed transactions, so that a new transaction is created for
each method call, using SessionSynchronization on a stateless session bean would
actually make sense.

I tried to do that because I wanted to trace the transaction boundaries to a log file, to
measure how long it takes to perform a transaction, and how long the commit takes. I
was quite confused because it didn't work, until I found out that
SessionSynchronization doesn't work with stateless session beans.

Re: It would make sense with container-managed transactions


Author: Sivakumar Janarthanan
(http://www.jguru.com/guru/viewbio.jsp?EID=1036581), Dec 11, 2002
yes, I agree that it would have been very helpful if session synchronization
interface had been provided for stateless session beans with container managed
transactions. In my current project, I have a requirement where, if a transaction
gets rolled back, I need to do some database updates (or need to write some status
information to a flat file) in a totally new transaction. With no session
synchronization support for stateless session beans which use container managed
transaction, it is really hard to do it. One of the ways could be, for each of the
business method in the stateless session bean, if the business method is the
initiator of the transaction and before the control is getting out of the method, I
need to check whether the transaction is getting rolled back and if so, call another
session bean method with a transaction attribute of "REQUIRED NEW" and do
the database updates. This needs to be enforced by the programmer only and it
might be error prone. Instead, if the EJB specs had allowed session
synchronization interface for stateless session beans which uses container
managed transactions, it would have been very helpful in this kind of scenario.

Where can I learn (more) about Application Servers?


Location: http://www.jguru.com/faq/view.jsp?EID=431183
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru AppServer FAQ.

Where can I learn (more) about becoming certified in Java technology?


Location: http://www.jguru.com/faq/view.jsp?EID=431185
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Certification FAQ.

Where can I learn (more) about CORBA (Common Object Request Broker
Architecture)?
Location: http://www.jguru.com/faq/view.jsp?EID=431188
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru CORBA FAQ.


Where can I learn (more) about Java running on IBM's AS/400 series
computers?
Location: http://www.jguru.com/faq/view.jsp?EID=431194
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Java400 FAQ.

Where can I learn (more) about Java's reusable software components,


JavaBeans?
Location: http://www.jguru.com/faq/view.jsp?EID=431197
Created: May 30, 2001 Modified: 2001-06-16 16:04:06.477
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru JavaBeans FAQ.

Comments and alternative answers

Advanced Java Programming


Author: Naveen Madenhalli (http://www.jguru.com/guru/viewbio.jsp?EID=1253053),
Jul 13, 2005
If a applet client wants to send a request to a server, what are the various steps to be
followed?

Where can I learn (more) about JDBC, Java's Database Connectivity


solution?
Location: http://www.jguru.com/faq/view.jsp?EID=431206
Created: May 30, 2001 Modified: 2001-07-24 09:55:24.202
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru JDBC FAQ.

Where can I learn (more) about Java's support asynchronous and


publish/subscribe messaging using JMS (Java Message Service)?
Location: http://www.jguru.com/faq/view.jsp?EID=431210
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru JMS FAQ.

Where can I learn (more) about using JNDI (Java Naming and Directory
Interface)?
Location: http://www.jguru.com/faq/view.jsp?EID=431212
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru JNDI FAQ.

Where can I learn (more) about using design patterns with Java?
Location: http://www.jguru.com/faq/view.jsp?EID=431238
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Patterns FAQ.

Where can I learn (more) about Java Servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=431246
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Servlets FAQ.

Comments and alternative answers

Advanced Java Programming


Author: Naveen Madenhalli (http://www.jguru.com/guru/viewbio.jsp?EID=1253053),
Jul 13, 2005
Explain the various steps involved in building your own bean with suitable example

Where can I learn (more) about Java's support for developing multi-
threaded programs?
Location: http://www.jguru.com/faq/view.jsp?EID=431248
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Threads FAQ.

Where can I learn (more) about Java's support for transaction processing?
Location: http://www.jguru.com/faq/view.jsp?EID=431948
Created: May 31, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Transactions FAQ.

Where can I learn (more) about JCA (Java Connector Architecture)?


Location: http://www.jguru.com/faq/view.jsp?EID=431958
Created: May 31, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the Sun's Java Connector Architecture homepage.

How do we express the relationships between EJB Entity Beans in UML?


Location: http://www.jguru.com/faq/view.jsp?EID=431997
Created: May 31, 2001
Author: jim conallen (http://www.jguru.com/guru/viewbio.jsp?EID=242550)
Question originally posed by Peter Lin
(http://www.jguru.com/guru/viewbio.jsp?EID=387708
I wish I had a quick answer for you, but the real answer lie in the activities of the
JSR 26 committee. This group is currently working on a formal extension (profile) to
the UML for modeling EJBs. I've seen some draft work, but can't say with any
authority what the final outcome will be.

With that comment aside, I'd suggest that you model relationships with associations,
and draw them in class diagrams. Component diagrams, are only suitable for
expressing dependencies (a weak form of relationship).

Associations are used to model the concept of an instance maintaining a relationship


to another instance. A dependency just shows that the class is dependent on another
element. That is, if the interface changes or something like that, as opposed to a
state change in the dependent object.

Comments and alternative answers

Modeling relationships between EJBs


Author: Ara Kassabian (http://www.jguru.com/guru/viewbio.jsp?EID=57884), Jul 6,
2001
To some extent, the answer depends on whether your model is a business (analysis)
model or a design model.

If it is a business model, then your classes are just business (domain) objects, many of
which map to EJBs. In that case, you just draw relationships (association or
inheritance) between the business objects as dictated by the semantics of the business
domain. How those associations are implemented is not a concern at this level.

If your model is a design model, on the other hand, your classes represent EJBs. In
the JSR 26 referred to by Jim Conallen, stereotypes are used to identify whether a
class is an entity bean, session bean, etc. The stereotypes are in fact a sort of
shorthand. An entity bean actually consists of a group of Java classes: the
implementation class, the remote interface, the stubs/skeletons, the local interface,
etc. An association or an inheritance relationship between EJBs may be implemented
in different ways, depending on which design pattern(s) you use. Some standard
patterns are now emerging (see Sun's EJB blueprint directory, jGuru, and elsewhere).
However, I do not believe any of them have been codified into stereotypes or any sort
of shorthand notation as yet. So, IMHO, expressing relationships between entity
beans in a UML model means chossing between two options:

1. Draw all the EJB classes explicitly in the class diagram and draw the relationships
as you intend to implement them.

2. If you are going to be consistent in your implementation (always a good idea :-),
use a shorthand notation (e.g., stereotypes) for the EJBs and for the relationships, and
document the shorthand using supporting class diagrams (where you explicitly draw
all the classes and associations).
Hope this answers the question somewhat.

Entity Beans with no primary keys Is it possible to create an Entity


Bean(CMP) based on table that does not have a primary key.
Location: http://www.jguru.com/faq/view.jsp?EID=433111
Created: Jun 3, 2001
Author: Shirish Poddar (http://www.jguru.com/guru/viewbio.jsp?EID=86336)
Question originally posed by Pankaj Jha
(http://www.jguru.com/guru/viewbio.jsp?EID=431702

Yes, you can create CMP Entity Beans without primary keys. But you must be aware
of the implications:

1. Duplicate records may be entered in the table


2. The findByPrimaryKey() method may return varying rows

In essence, CMP was not designed to not have primary keys, although it can work.
The development process is the same as when you create CMP which has primary
keys.

Comments and alternative answers

Entity Beans with no primary keys Is it possible to create an Entity Bean(CMP)


based on table that does not have a primary key.
Author: Allen Fogleson (http://www.jguru.com/guru/viewbio.jsp?EID=344251), Jun
3, 2001
You can create a custom Primary key class that contains all the columns in the table.
(assuming that would be fairly unique) The only hassles there would be in
implementing the hashcode method.

Re: Entity Beans with no primary keys Is it possible to create an Entity


Bean(CMP) based on table that does not have a primary key.
Author: xxxxx yyyyy (http://www.jguru.com/guru/viewbio.jsp?EID=759426), Feb
14, 2002
I have created an entity bean for a table which does not have a primary key and it
does not work. There is nothing stops you creating an entity bean(CMP) for a table
which does not have a primary key but the result return by the finder method is
wrong. Though the table does not have primary key, the CMP bean randomly picks
a column(most likey the first column) out of a table and mkes it a primary key
(which is absolutely wrong). Conclusion: A CMP entity bean for a table which does
not have a primary key is not going to work. You must have a primary key to work
properly.

No Primary Key Class in Entity Beans


Author: Shirish Poddar (http://www.jguru.com/guru/viewbio.jsp?EID=86336), Jun 9,
2001
Generally we create a separate primary key class in a Enity Bean. We can do without
this creation also. What we can do is we have to write in the EJB-Jar.XML the
primary key class name as Java predefined class, such as java.lang.string,any wrapper
classes. <prim-key-class>java.lang.String</prim-key-class> <primkey-
field>accountId</primkey-field> In this case Duplicate recrods will not be allowed.

Re: No Primary Key Class in Entity Beans


Author: Allen Fogleson (http://www.jguru.com/guru/viewbio.jsp?EID=344251),
Jun 14, 2001
But in this case you are saying that the acountID is the primary key... So
effectively you have made the table have a "primary key". I think in general we
have to be aware that although primary keys may not be required, the detriment to
not having at least one unique field is that finders may not operate as expected.

Yes it is possible
Author: prashant jani (http://www.jguru.com/guru/viewbio.jsp?EID=100991), Jan 18,
2002
in the cmp xml file. Do not provide CMp mapping for the primary key.
Thats all
but u will have to create a sequence at the database level for the primary key.
this will avoid duplicate keys problem

Jani

Two primay key??


Author: F M (http://www.jguru.com/guru/viewbio.jsp?EID=737992), Jan 29, 2002
What about two primary key in 1 table (normalization table, many-to-many
example)?? If let say I create a class for this primary key class, how can I retrieve
it or how can I use a finder findByPrimaryKey?? I'm still confuse how to use this
primary key class.

about EJB performance Where can I find articles about EJB performance?
Location: http://www.jguru.com/faq/view.jsp?EID=438168
Created: Jun 12, 2001
Author: Luis F. Canals Samaniego
(http://www.jguru.com/guru/viewbio.jsp?EID=66172) Question originally posed by
slose Lin (http://www.jguru.com/guru/viewbio.jsp?EID=429700

Here are some links:


An official white paper about EJB performance:
http://developer.java.sun.com/developer/technicalArticles/ebeans/ejbperformance/
http://www.jdance.com/ejbperformance.shtm has some links to pages about EJB
performance

If you use IBM WebSphere,


http://advisor.com/wFiles.nsf/wCatID/Miw0009.vonag01.zip/$file/Vonag01.zip can be
useful.
But if you use WebLogic 5.1, in
http://www.weblogic.com/docs51/classdocs/API_ejb/EJB_deploy.html#1032825 you
can see some tips.
Here, you can see how to reduce network traffic

Comments and alternative answers

EJB performance
Author: Shahram Khorsand (http://www.jguru.com/guru/viewbio.jsp?EID=3357), Jun
17, 2001
The EJB performance is very dependent on the products you are using. However,
couple of really good reviews of different products are available on
http://www.theserverside.com.
Cheers,
Shahram

Using the Java Connector Architecture with EJBs Can I map an entity bean
to an EIS for which a JCA resource manager exists? Ideally, I would like to
use container managed persistence for this.
Location: http://www.jguru.com/faq/view.jsp?EID=440204
Created: Jun 16, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
Ara Kassabian (http://www.jguru.com/guru/viewbio.jsp?EID=57884

Is there a COM Bridge that lets Windows developers create native client
applications that access Enterprise JavaBeansTM (EJBTM) components
deployed on a J2EE App server?
Location: http://www.jguru.com/faq/view.jsp?EID=448051
Created: Jun 30, 2001
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)

Yes. Take a look at:

JavaTM 2 Platform, Enterprise Edition Client Access Services (J2EETM CAS) COM
Bridge 1.0 Early Access.

How do I use an EJB to handle simple authentication to an LDAP directory?


Location: http://www.jguru.com/faq/view.jsp?EID=449495
Created: Jul 4, 2001
Author: Nicholas Whitehead (http://www.jguru.com/guru/viewbio.jsp?EID=1260)
Question originally posed by John Doe
(http://www.jguru.com/guru/viewbio.jsp?EID=215716

There are code samples in Sun's JNDI tutorial that explain how to perform LDAP
authentication through JNDI.

My recommendation would be to create a session bean that acquires an LDAP /JNDI


context in the setSession() method. A subsequent call to authenticate would pass in
a user and password. The following code shows how to authenticate the passed
values:

env.put(Context.InitialContextFactory,
"com.sun.jndi.ldap.LdapCtxFactory"); // I added this line myself
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires,
o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");
// Create the initial context
DirContext ctx = new InitialDirContext(env);

A failure in authentication will cause this code to throw a


javax.naming.AuthenticationException

You may want to store the actual LDAP tree that contains the users you are
authenitcating so youi can dynamically set it without recoding, so the actual code
may look like this if you store the LDAP tree name in JNDI as "myUserLDAPTree"
(ou=NewHires, o=JNDITutorial):

env.put(Context.InitialContextFactory,
"com.sun.jndi.ldap.LdapCtxFactory"); // I added this line myself
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=" + passedUserName + "," +
(String)new InitialContext().lookup("myUserLDAPTree"));
env.put(Context.SECURITY_CREDENTIALS, passedPassword);
// Create the initial context
DirContext ctx = new InitialDirContext(env);

The simply return a true, or a false if a javax.naming.AuthenticationException is


thrown.

Comments and alternative answers

How would you find and store the actual LDAP tree?
Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Mar 5,
2003
You have said

"You may want to store the actual LDAP tree that contains the users you are
authenitcating so youi can dynamically set it without recoding, so the actual code may
look like this if you store the LDAP tree name in JNDI as "myUserLDAPTree"
(ou=NewHires, o=JNDITutorial): "

I have to authenticate users at different ou levels...Some are one level deep other are
more than that. How can I write a common login program using the technique you
mentioned?

Stateful Session Beans and Fail Over How are stateful session beans
handled in a failover situation -- is this vendor dependent?
Location: http://www.jguru.com/faq/view.jsp?EID=452355
Created: Jul 9, 2001
Author: Shahram Khorsand (http://www.jguru.com/guru/viewbio.jsp?EID=3357)
Question originally posed by Krishna Dev
(http://www.jguru.com/guru/viewbio.jsp?EID=414725

There is no standard for failovers.Each AppServer implements it differently.

I made a comparison between, Weblogic (WL), Websphere(WAS) and Borland App


server(BAS).
I found that BAS had the best failover. They simply right the state to a database
within 5 seconds intervals. This is of course configurable. BAS had even the best
clustering alternative. My tests showed that this feature didn't have any impact on
the performance.

If you are planning on spending alot of money. There are hardware clusters and
different technologies that provide HA (high availability) services. see SUN clustering
servers.

When it comes to WL and WAS there wasn't a clean failover technology that didn't
impact the performance. Because the problem with statefullness is that it makes
everything so much slower. I found that BAS gave us the best performance.

Comments and alternative answers

Some justification...
Author: Nick Minutello (http://www.jguru.com/guru/viewbio.jsp?EID=222214), Sep
1, 2001
I think we might need a few more details to back up the comments on "who's best".

Firstly, it is guaranteed that you will have to accept some performance hit when you
cluster. You cant get scalability and availability otherwise. There is no such thing as a
free lunch.

Secondly, unless I am mistaken, BAS dont really have a statefull fail-over solution. (I
could be wrong). My understanding is that the only state replication mechanism is via
passivation! This means you might get statefull session failover with BAS if the
Session Bean miraculously gets passivated just before its failover.... I dont know of
any other state replication mechanism that Borland has. I would gladly be corrected
on this if this were wrong.

Weblogic achieves statefull replication using ip-multicast - to broadcast the state to


any number of other servers in the cluster that happen to contain a replica (you can
configure any number of replicas - usually you have just one). Even so, weblogic's
solution isnt transactional - in that you can never be guaranteed that the replica has
received the state before your method returns. If you did make it transactional - ie you
had almost 100% surity that your statefull failover has failed over to one with a valid
state - then performance would be affected dramatically.

I am not sure of Websphere's strategy - so I have no place commenting on it.

So, in conclusion, clustering and fail-over DO have a performance cost. I suspect you
dont see a performance impact with Borlands solution because, in fact, it doesnt have
a statefull fail-over solution.

Re: Some justification...


Author: Janakiraman Nellissery
(http://www.jguru.com/guru/viewbio.jsp?EID=539086), Mar 27, 2002
Hi Nick,

How do we make the fail-over in WLS as Transactional? Do u know what is the


setting reqd in WLS to do that.? Thanx. -Janakiraman

Re[2]: Some justification...


Author: Nick Minutello
(http://www.jguru.com/guru/viewbio.jsp?EID=222214), Mar 27, 2002
You can't make fail-over transactional.

None of the EJB containers support this. In any case, the performance impact
would be quite large - you would be talking about a 2PC commit on every
transaction.

Correcting my earlier post, WLS doesnt use *multi-cast* to replicate - but the
in-memory replication is done over the network.
Weblogic does this after the Stateful bean's transaction commit - which means
there is only a tiny window where failure can occur resulting in state loss.

Borland and Websphere do a periodic passivation to database - leaving


(usually) a 5 second window where a failure can occur resulting in state loss.
<pP

Where can I find a complete J2EE packages/classes diagram?


Location: http://www.jguru.com/faq/view.jsp?EID=452358
Created: Jul 9, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
Habib El-Zoghbi (http://www.jguru.com/guru/viewbio.jsp?EID=38223

This online version from JavaReport is an excellent resource.


Comments and alternative answers
Old
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 10,
2001
Unfortunately, they are from 1999.

Re: Old
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 10,
2001
Oops, 2000 for the J2EE ones. The standard library ones are 1999.

Re[2]: Old
Author: innum onenu (http://www.jguru.com/guru/viewbio.jsp?EID=385539),
Dec 2, 2001
so What's the inference about javareport.com package structure? Is it new and
updated or old? Also, eventhough the main root element is J2EE, guess it
doesn't cover all the J2EE API's(JMS, JNDI etc.) Any other place where the
entire(latest) set could be found? Also any thoughts on how to produce these
sort of documents? Is it possible to attain through javadoc? Lastly, What are all
the API's covered under J2EE and their latest versions(a link would be great).

Can i use SOAP to expose my EJB objects?


Location: http://www.jguru.com/faq/view.jsp?EID=474484
Created: Aug 12, 2001
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)

Yes, of course. There's an article on TheServerSide.com that shows you how to do


this:
Integrating Apache SOAP with an EJB Server.
Comments and alternative answers

That link is dead... try this


Author: Kevin Baker (http://www.jguru.com/guru/viewbio.jsp?EID=882634), May
26, 2002
http://www.theserverside.com/home/thread.jsp?thread_id=2086

Does setting the Home and Object stubs to null from an EJB client improve
performance?
Location: http://www.jguru.com/faq/view.jsp?EID=475266
Created: Aug 13, 2001
Author: Nick Minutello (http://www.jguru.com/guru/viewbio.jsp?EID=222214)
Question originally posed by prakash prabhu
(http://www.jguru.com/guru/viewbio.jsp?EID=91561

No, not really.

If your appserver uses JRMP, then it *might* mean that your serverside objects
(EJB's) get garbage collected sooner. However, it depends on the appserver's lifecycle
management. Since IIOP is mandated in the EJB spec (and IIOP does not support
distributed garbage collection) then most appservers probably rely on a different
strategy for object lifecycle management.

If you ARE using JRMP, then the client-side garbage collection of the stubs (which can
be accelerated by setting references to null) can reduce the network load (as the
stubs sit there pinging the server objects to keep them alive).

However, I dont see that much of an improvement in performance to warrant setting


stubs to null when you are done with them.

In fact, you will get better performance by *caching* your home stubs (these are
always slow to look up). Check out the Home Factory pattern at
http://www.theserverside.com/home/thread.jsp?thread_id=7931

In EJB 2.0 Entity Beans, What is the difference between the local home
interface and the remote home interface?
Location: http://www.jguru.com/faq/view.jsp?EID=477519
Created: Aug 15, 2001
Author: Christopher Pickslay (http://www.jguru.com/guru/viewbio.jsp?EID=468619)
Question originally posed by CustomWare Asia Pacific PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=139414

EJB 2.0 adds the notion of local beans, which are accessible only from within the JVM
your beans are running in.

The idea behind this is that many beans you might create are never meant to be
accessed by remote clients. For example, you may program beans meant for your
public interface like Order and Invoice, and you may have other helper beans which
are never meant to be instantiated by remote clients, like Inventory and
SalesTaxCalculator. Or you might have an entire system that takes advantage of
EJB's transaction management, persistence, etc, but which has no remote (i.e.,
outside the current JVM) clients at all.

With EJB 1.1, you had to implement remote client views for all these beans, even if
you had no remote clients. This means that your home and remote interfaces had to
extend javax.rmi.Remote, which puts several restrictions on them, including:

• Any objects passed as parameters must be serializable


• Parameters are passed by value, not by reference
• Network and serialization overhead related to RMI
• Client must handle RemoteException on all method calls

Local beans also have limitations, the primary one being that you can only access
them from within the same JVM, so they don't make much sense for distributed
applications. Also, if you're converting your old remote interfaces to local ones, you
have to be careful about the pass-by-reference semantics, which may lead to
unintended consequences.

Note that you can implement both remote and local interfaces to your beans. But in
most cases it makes more sense to define your application model first, based on
access, distribution, and deployment needs, and then decide on local vs. remote
based on the tradeoffs.

In EJB 2.0, What is an Entity Bean's local interfaces? How do I define them?
Location: http://www.jguru.com/faq/view.jsp?EID=477524
Created: Aug 15, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
CustomWare Asia Pacific PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=139414

In EJB 2.0, An Entity Bean can have a set of Local interfaces for use by clients within
the same JVM (known as collocated clients). The local interfaces extend the following
interfaces:

• javax.ejb.EJBLocalObject - for the Object interface


• javax.ejb.EJBLocalHome - for the Home interface

Arguments between these interfaces and clients calling them are passed by
reference.

What is the difference between Public Final Draft and Public Final Draft 2 of
EJB 2.0?
Location: http://www.jguru.com/faq/view.jsp?EID=479764
Created: Aug 20, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
CustomWare Asia Pacific PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=139414

Check out section E.12 of Public Final Draft 2 for a complete listing of the changes
between versions.
The major changes were the addition of Local interfaces and Local Home interfaces
for both Entity and Session Beans.

On the Container Managed Persistence (CMP) front, Dependant Objects (which were
a source of controversy) were removed.

What is the J2EE ECperf?


Location: http://www.jguru.com/faq/view.jsp?EID=488276
Created: Aug 31, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
CustomWare Asia Pacific PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=139414

ECperf is used for benchmarking J2EE application servers. It consists of a


Specification and a benchmarking kit which is designed specifically to test and
measure performance and scalability of J2EE application servers.

More information can be found at the ECperf homepage here


Comments and alternative answers

Official ECperf website


Author: Rodney Russ (http://www.jguru.com/guru/viewbio.jsp?EID=407228), Jan 23,
2002
If you would like to see certified ECperf results, you might want to check out
http://ecperf.theserverside.com/ecperf. Currently, there are only results posted for
WebSphere and Borland's appserver.

How do EJB and Web Services relate together? Are Web Services a
replacement for EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=488279
Created: Aug 31, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
CustomWare Asia Pacific PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=139414

Web Services can be thought of as a wrapper that can be used to allow EJB's to
invoke external services and also to allow external services and clients to invoke the
EJB's. A major strength of Web Services is in the integration of the J2EE platform
with the Microsoft .NET platform. Using Web Services allows, for example, Microsoft
Visual Basic clients to access EJB's as clients.

Some products such as IBM WebSphere and BEA WebLogic already support Web
Services inside there Application Servers.

Comments and alternative answers

EJB and Webservices


Author: Uma Maheswari Kandasamy
(http://www.jguru.com/guru/viewbio.jsp?EID=310809), Sep 2, 2001

EJBs are Java Components that can be only accessed directly using another Java
client. The disadvantage here is that these components and its services are remotely
available to only Java application. (Here I am not talking about web clients)

Suppose you want have a service, say, Tax Calculation Service EJB, which you would
want another application to access, no matter what kind/technology that application is
written in, then you will go for this WebServices. All you would do is PUBLISH your
service to a registry called the UDDI and let the other applications know about such a
service. Then, this other application will contact the REGISTRY using SOAP and
know about the methods and parameters that your component needs and will build up
a SOAP REQUEST for your component. Your component will then do the Tax
Calculation and then give back a SOAP RESPONSE which the client application will
use for its purpose.
So EJB is one way to write your WebService. Hope this makes things clear, Uma

Re: EJB and Webservices


Author: ChandraShekhar Rao
(http://www.jguru.com/guru/viewbio.jsp?EID=308678), Dec 5, 2001
Hello, Pls can I have clear details about Webservices. ie. If I want to do
webservices programming what i need. Pls can u gice me clear info

EJB and Webservices


Author: Ranjith CP (http://www.jguru.com/guru/viewbio.jsp?EID=797328),
Mar 14, 2002
Web Services enables businesses to interact each other without human
interaction. If you want to make your business web service enabled,you need to
obey some rules defined by www.w3.org.These protocols are called SOAP.You
create a WSDL file,which have all the operations.It must have the input
payload (the arguments which come in)and output payload(the xml which
contain the output arguments).

Re: EJB and Webservices


Author: Alex Robinson
(http://www.jguru.com/guru/viewbio.jsp?EID=818985), May 2, 2002
Why can't EJBs/App Servers just encapsulate the Webservices
implementation? EJBs are already designed to support different protocols
for communication including Java RMI and IIOP. Why couldn't it also
support SOAP? It would then be the responibility of the app server when
generating the EJB Object implementation for the stub and proxy to
implement the necessary logic to support SOAP. Additionally the App
Server could support UDDI for finding services similar to how Java
programs currently find EJBs using JNDI. Ultimately it seems to me the
implementation of a web service could be completely transparent to the
java developer accept for maybe some additional work in the deployment
descriptor. Then any Session EJB could easily be exposed as a web
services and available to any web service ready technology. Am I wrong or
is this the ideal solution where web services is available automatically to
Java EJB developers and interoperability with other technologies is easier
to acheive without requiring the Java developer to learn a new set of APIs?
Of course still need to address the issue of a Java program accessing a web
service where the EJB Object stub would not be available like a .NET web
service.

In EJB 2.0, What is an ejbSelect() method?


Location: http://www.jguru.com/faq/view.jsp?EID=488299
Created: Aug 31, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
CustomWare Asia Pacific PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=139414

A select method is similar to a finder method for Entity Beans, they both use EJB-QL
to define the semantics of the method.
They differ in that an ejbSelect method(s) are not exposed to the client and the
ejbSelect method(s) can return values that are defined as cmp-types or cmr-types.
For more information on EJB QL, see this FAQ.

How can I update the primary key field in a CMP Entity Bean?
Location: http://www.jguru.com/faq/view.jsp?EID=515864
Created: Oct 9, 2001
Author: Tim Duggan (http://www.jguru.com/guru/viewbio.jsp?EID=506387)
Question originally posed by Shanks75 shanks75
(http://www.jguru.com/guru/viewbio.jsp?EID=506367

You cannot change the primary key field of an Entity bean. Refer to page 130 of the
EJB 2.0 specification, it states "Once the primary key for an entity bean has been
set, the Bean Provider must not attempt to change it by use of set accessor methods
on the primary key cmp-fields. The Bean provider should therefore not expose the
set accessor methods for the primary key cmp-fields in the component interface of
the entity bean."
A work around to update a primary key field, would be to remove and then an re-
create the bean.

When using Websphere 3.5, VisualAge and Oracle to develop CMP EJB's I
receive the following error: "Unable to insert data into a NOT NULL field".
What am I doing wrong?
Location: http://www.jguru.com/faq/view.jsp?EID=515867
Created: Oct 9, 2001
Author: Shai Almog (http://www.jguru.com/guru/viewbio.jsp?EID=501707) Question
originally posed by Theresa Betts
(http://www.jguru.com/guru/viewbio.jsp?EID=506361

You need to modify the create method for the Entity bean to initialize ALL the not null
fields.

VAJ defaults to initializing the primary key but it doesn't initialize the NOT NULL
fields, this won't work because any invocation of create() immediately causes insert.
Take a look (or debug) the deployed code generated by VAJ to see the generated
code that is deployed into the server.

Comments and alternative answers

Attempted to insert null value


Author: rajesh tiwari (http://www.jguru.com/guru/viewbio.jsp?EID=268316), Oct 14,
2001
You have attempted to insert null value to a field which has been stated as not null
===> Solution, always initialize all the fields before invoking the create method, or
provide a costructor which will intialize all the required value, so that even though the
value has not been provided by the client to some of the field, it will go with the
default value provided by the java

Answer
Author: Rocky NAIR (http://www.jguru.com/guru/viewbio.jsp?EID=537969), Nov 3,
2001
well hi there proabably in in the backend that particular field will be not null and u
must be trying to insert a null field .. in visula age there is an option for break points..
and also u can see which field has got what values in the top right corner.. this way u
can check which variable has got a null value and compare it with the database
Regards..

Inserting NOT NULL


Author: Somashekhar Kori Shetty
(http://www.jguru.com/guru/viewbio.jsp?EID=95700), Nov 15, 2001
declare all the class variables of String type to blank as String var = "" ; But incase of
the Date, if it is CMP, then you have to assign the default date. Where as in BMP, you
can just skip the field.

Re: Inserting NOT NULL


Author: C. N. Tsang (http://www.jguru.com/guru/viewbio.jsp?EID=967331), Jul
28, 2002
I considered this as the Oracle's BAD behavior. If you insert an empty string ("")
into a NOT NULL field in Oracle, Oracle will change it to null, and thus cause
exception. I bypass it by change the value of the field to a blank (" "). I have tested
DB2 and Interbase (Firebird) does not have this problem.

Can stateful behave as stateless Is it possible to change a Stateful Session


Bean to behave in a Stateless manner at deploy-time? What issues are
involved?
Location: http://www.jguru.com/faq/view.jsp?EID=547716
Created: Nov 14, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by sachin V
(http://www.jguru.com/guru/viewbio.jsp?EID=507759

Stateful and Stateless Session Beans are for different purposes. Therefore, stateful
session bean cannot act as a Stateless Session Bean since their lifecycles are
different. You can create a Stateful Session Bean to not store any conversational
state and therefore, at least in theory, you can make it stateless, but since the
lifecycles of Stateless and Stateful Session Beans are different, you do not achieve
anything by doing this.
Comments and alternative answers

Stateful to stateless
Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), Nov 15, 2001
I would like to clarify the above answer. It is possible to change stateful beans into
stateless beans declaratively. However, depending how the bean is implemented there
may be some side effects.

Firstly, if the state of the bean is modified by different methods, there may be
inconsistencies in the behavior of the bean.

Secondly, the container will not invoke session synchronization methods and hence
you can not manipulate the state of the bean in the case of a rollback.

As long as your bean does not depend on the above two, you can make a stateful bean
stateless. In your case, you may have to carefully analyze if there is state held in the
bean, and if so, how the state is modified by different methods.

Can an EJB determine its own JNDI name?


Location: http://www.jguru.com/faq/view.jsp?EID=547718
Created: Nov 14, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by stefano traballesi
(http://www.jguru.com/guru/viewbio.jsp?EID=547075

No. A work-around would be to put <env-entry> in the deployment descriptor and


the EJB could then read the environment variable.

What is the meaning of marshalling and unmarshalling?


Location: http://www.jguru.com/faq/view.jsp?EID=560072
Created: Nov 25, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Omar Khan (http://www.jguru.com/guru/viewbio.jsp?EID=232689

Omar,
In few words, "marshalling" refers to the process of converting the data or the
objects inbto a byte-stream, and "unmarshalling" is the reverse process of
converting the byte-stream beack to their original data or object. The conversion is
achieved through "serialization".

The purpose of the "marshalling/unmarshalling" process is to transfer data between


the RMI system.

Is it possible to convert a Java Bean to an Enterprise Java Bean (EJB)?


Location: http://www.jguru.com/faq/view.jsp?EID=560079
Created: Nov 25, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by David Burg
(http://www.jguru.com/guru/viewbio.jsp?EID=537744
I f I have to write EJBs, can I first write JavaBeans and later convert them to EJBs?

Yes, you can convert them later, but keep in mind that Java Beans are client-side
objects and EJBs are server side object, and they have completely different
development, lifecycle, purpose... They have nothing in common other than the fact
that they both have Java Beans in their name.
It is the same as if you ask can you convert any java class into EJB. The answer is
still yes given that the class you want to make an EJB does not violate any of the EJB
restrictions posed in its specifications.

If you need to write EJBs, it is a big waste of time to create java beans and then
convert them to EJBs.
There is absolutely no good reason to do that and many reasons why not to do it.

Comments and alternative answers

but how might this be done?


Author: java rine (http://www.jguru.com/guru/viewbio.jsp?EID=557631), Dec 1,
2001
sorry if this might sound like an ignorant question. I'm a newbie to the EJB
technology and would like to find out how this conversion might be done? Do i just
cut and paste the methods and attributes from the javabean into corresponding
methods in the bean class of the EJB or are there special issues to look out for?

Are there any examples where i can look for such a conversion?

Convert JavaBeans to EJB's?


Author: Kevin Baker (http://www.jguru.com/guru/viewbio.jsp?EID=882634),
May 26, 2002
I am currently working without a J2EE server, so must develop this stage of my
app withouth EJB's. I will definately be moving to J2EE in the future though... So
I will have to convert all of my beans. Its seems to me that it shouldn't be that
difficult, but would love to see an example of this. "...Java Beans are client-side
objects and EJBs are server side object...." Excuse me too for being a bit of a
newbie. This statement above just seems a little off. I can see how javabeans can
be used client side... but I am actively using them in my server-side jsp scripts. So
to me they are not exclusively client-side. Maybe you could explain that statement
a bit more. Thanks

Re: Convert JavaBeans to EJB's?


Author: jay raj (http://www.jguru.com/guru/viewbio.jsp?EID=822224), Oct
28, 2002
Hi! I can tell the difference between JavaBeans and Enterprise Java Beans.For
what purpose they are used for:

(1)JavaBeans are not used for distributed purposes and EJB's are used for
Distributed applications.

(2)Basically JavaBeans are used for intraprocess communications, where as


EJB's are used for interprocess communications.EJB's are widely used to
develop applications in 3-tier architectures.

(3)One way, they are realated to each other, they are component based
models.A component is developed for specific purpose and not for specific
application.It can be reused across the software life cycle.

So dude, clearly understand what EJB is meant for and what javabean is meant
for.The power of EJB can be achieved by utilising it for the right purpose.

Regards,
jay..

In EJB 1.1., how do I ensure that while any client can access EJB A, only EJB
A should be allowed to access EJB B? ie my client cannot access EJB B
directly.
Location: http://www.jguru.com/faq/view.jsp?EID=560080
Created: Nov 25, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
lina chitturi (http://www.jguru.com/guru/viewbio.jsp?EID=388164

(Keeping in mind that 1.1 version does not support run_as_mode)

Hi,
Maybe this it's just a silly idea, but can't you just limit the access to EJB B inside the
deployment descriptor, using the <method-permission> tag?

<method-permission>
<role-name>guest</role-name>
<method>
<ejb-name>EJB_A</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
<method-permission>
<role-name>administrators</role-name>
<method>
<ejb-name>EJB_B</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
This should not allow anyone without the administrator permissions to access to the
EJB_B, and I think that you can set the context inside EJB_A to be in that security
level.
Bypassing login prompt for J2EE1.3 using runclient command
Location: http://www.jguru.com/faq/view.jsp?EID=560676
Created: Nov 26, 2001
Author: Gerard Weatherby (http://www.jguru.com/guru/viewbio.jsp?EID=550879)
Question originally posed by Gauri Tendulkar
(http://www.jguru.com/guru/viewbio.jsp?EID=542648

Additional Information

While connecting to J2EE1.3 server for a standalone java application (in .ear) using
runclient command, there is the need to bypass the login prompt for login name and
password.
As per the documentation, this can be done by the following command:
runclient -client <<appname.ear>> -name
<<app_displayname>>
-Dj2eelogin.username=<<user_name>>
-Dj2eelogin.password=<<password>>
But this does not work. (Ultimately it prompts for login name and password).

Documentation is incorrect (or at least unclear).

Set VMARGS to:


-Dj2eelogin.username=<<user_name>>
-Dj2eelogin.password=<<password>>
before executing runclient.

Comments and alternative answers

Bypassing login prompt for J2EE1.3 using runclient command


Author: Len White (http://www.jguru.com/guru/viewbio.jsp?EID=568486), Nov 30,
2001
Are you sure this should not be j2eelogin.name, not j2eelogin.username?

Recovering State of Statefull SessionBean.


I know how to get the EJBHandle of a Statefull SessionBean and write it to a
file and I get a reference to the EJBObject after I read it back. Now the
question is:
(a) Does the handle in itself store the variable values?
(b) How do I get these values back and construct the bean if my app server
has crashed?
(c) If we cannot do it, then how do I do session fail over management?

Location: http://www.jguru.com/faq/view.jsp?EID=560681
Created: Nov 26, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Janakiraman Nellissery
(http://www.jguru.com/guru/viewbio.jsp?EID=539086

EJB specs section 2.1.3.1 reads:


while a session bean is transactional, it is not recoverable should its container crash.
with that in mind, comments are below.
(a) No. Handle is a simple "pointer" used to locate a bean. So, it does not store the
values of the variables of the beans although specifications do not prohobit this
implementation.

(b) Read the top of my message. so, you cannot automatically. You could try to save
the state of stateful session bean to non-volatile storage after each method
invocation. that wastes lots of resources but could be implemented if you really,
really need to keep client's state when server crashes. Of course, you would need a
mechanism to recover that state from storage yourself.

(c) Well, you do not. The design of stateful session beans is such that it starts out at
default and maintains a state as clients perform operations on the system. Nowhere
in the specifications do you read that session are "crash-safe" or that there is a fail-
over when server crashes. Web containers do not keep http sessions around when
they crash and ejb container is no different. As I wrote in (b) you can implement it
yourself but you have be smart on how you go about doing it.

Comments and alternative answers

Recovering State of Statefull SessionBean.


Author: Adam Young (http://www.jguru.com/guru/viewbio.jsp?EID=584348), Dec
13, 2001
Instead, you would do something like: EJBObject e;
try{
e = handle.getObject()
}catch (Exeception e){
e = localGetObject();
}
Where localGetObject()cretes the instance in the first place. I would suggest making a
client side proxy for Your Session EJB that does this for you.

Session state after a server crash


Author: Tore Green (http://www.jguru.com/guru/viewbio.jsp?EID=457032), Jul 12,
2002
Some application servers share session state between servers in a cluster. E.g. I
believe that Weblogic Server can replicate session state to a secondary server in the
cluster, enabling the client to continue working with that server if the primary server
for that client crashes. I seem to remember that this works both with Stateful Sesion
Beans and with HTTP session state.

Are we allowed to change the transaction isolation property in middle of a


transaction?
Location: http://www.jguru.com/faq/view.jsp?EID=565056
Created: Nov 28, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Ranjith Ayinala
(http://www.jguru.com/guru/viewbio.jsp?EID=562285

No. You cannot change the transaction isolation level in the middle of transaction.
Comments and alternative answers

Isolation-Level with CMP (In the middle of a transaction)


Author: Klaus Dirlewanger (http://www.jguru.com/guru/viewbio.jsp?EID=842393),
May 17, 2002
Hey all, but how with CMP. The isolation levels are defined for single methods. You
say it is only possible to set the isolation level at the beginning of a transaction.

So my conclusion would be: The isolation level only can be set for session bean
methods beginning a new transaction (REQUIRES resp. REQUIRES_NEW), by no
means for entity beans. Is this conclusion correct. Many thanks Klaus

Re: Isolation-Level with CMP (In the middle of a transaction)


Author: Prasun Sarangi (http://www.jguru.com/guru/viewbio.jsp?EID=893319),
May 27, 2002
we can not change the ISOLATION LEVEL in the middle of a transaction. The
best way to know this is to look into the javadoc of
java.sql.Connection.setTransactionIsolation(int level) this is the method we use
while playing aroung Isolation Level in BMP. Incase of CMP we can not explictly
mention the IL. That is the Container who will be deciding on that looking to the
underlying RDBMS.

Re[2]: Isolation-Level with CMP (In the middle of a transaction)


Author: Klaus Dirlewanger
(http://www.jguru.com/guru/viewbio.jsp?EID=893388), May 27, 2002
Thank you.

First: How the isolation level is set I already knew. Second: That it isn´t
possible to be changed in the middle of a transaction was a previous answer.

And anyway: I think the isolation level can be set. Therefore I would like to
ask my question again.

A lot of thanks
Klaus

What is the need of Remote and Home interface. Why cant it be in one?
Location: http://www.jguru.com/faq/view.jsp?EID=567986
Created: Nov 30, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
hari kp (http://www.jguru.com/guru/viewbio.jsp?EID=557981

Hi,
In a few words, I would say that 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.

I would suggest you to take a look at this FAQ: What's the difference between
EJBHome, EJB Home, EJB Object, EJBObject and EJB (not to mention Home Interface
and Remote Interface)? and, maybe, spend some time in reading the EJB
Specifications that are extremely clear and interesting.

Comments and alternative answers

It is all to do with interfaces.


Author: Nick Minutello (http://www.jguru.com/guru/viewbio.jsp?EID=222214), Dec
1, 2001
When you work with objects by interface, you need to have a factory to create the
objects.

If the objects are local, then you can use a factory method or a factory object.
However, if the objects are remote, you can only use a factory object. CORBA had
such a concept as a factory object.

In EJB, the factory object is the Home Object. There is always one and only one of
these home objects, thats why you can have an interface to this object (without the
need for another factory object).

It would be impossible for the server side object to be both object AND factory - so
that is why there are two interfaces.

CMP 2.0 entity bean.


Can I write a method in CMP 2.0 Entity Bean which can retrieve some data
from database (ie. is it possible to have a CMP entity bean mapped to a
particular table and have a business method in it which retrieve some data
from a different table)?
Location: http://www.jguru.com/faq/view.jsp?EID=571808
Created: Dec 4, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Gaurav Sharma PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=66767

You can have CMP Entity Bean map to whichever table you want and you can have
business methods in the bean retrieve values from whichever table you want but not
ejbStore() ejbLoad()... (i.e not the container callbacks).
CMP does stand for Container managed persistence and therefore you have to let the
container do the persistence for you.
But there is nothing to prevent you from declaring a business method in your entity
bean that uses JDBC to connect to the database and retrieve data from some other
table.
The trouble is that if you business method in populating attributes of the bean itself
from a table to which it is not mapped. What can happen in this scenario is app
server can figure out that the value of an attribute in your bean has changed and call
callback that will retrieve values into the bean attributes from the original table to
which CMP attributes are mapped.

I believe that the best solution for you is BMP.

Can I develop an Entity Bean without implementing the create() method in


the home interface?
Location: http://www.jguru.com/faq/view.jsp?EID=575693
Created: Dec 6, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
JIA Java Italian Association PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=414973

I think you can.

As far as I know, there is nothing, in the EJB specifications, that prevents you to
create an Entity Bean without the create() method. In this situation, the only way to
obtain an instance of the bean is using a finder method.

Without the create() method, the only way to create new beans is manually
accessing to the database and using, for example, SQL insert statements.

Comments and alternative answers

No create() method in Entity Bean...


Author: Sandeep Thool (http://www.jguru.com/guru/viewbio.jsp?EID=128141), Jan
15, 2002
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.

Entity bean without create() method


Author: Mahesh Mulchandani
(http://www.jguru.com/guru/viewbio.jsp?EID=756686), Feb 12, 2002
In home interface u only provide the method signature and not implement as
mentioned in the question. in applications where in u want users to only read the data
u go for zero create methods in the entity bean.

No implementation of Create method


Author: Sandeep Thool (http://www.jguru.com/guru/viewbio.jsp?EID=128141), Feb
17, 2002
In Create methods, one usually INSERTS a row in a table. Now, ofcourse you MAY
NOT ALWAYS WANT to INSERT a row. In other words, there is no necessary reason
to implement the CREATE 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.

EJB-JNI-Legacy Integration(C++ API) We have exisitng System in C++.We


want to use Existing in the intranet/internet. We are using JNI to use
existing System. And then we are calling JNI Classes in EJB.Could any one
provide archtecure and sample with steps How to call existing C++ API in
JNI and that JNI API in EJB session beans.If any one can provide help ,i will
be greatful to them.
Location: http://www.jguru.com/faq/view.jsp?EID=577956
Created: Dec 9, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by bhadra reddy
(http://www.jguru.com/guru/viewbio.jsp?EID=425815

EJBs are suppose to be portable between different app server who comply with the
Sun's specifications for compliant EJB containers. Because of this reason, loading of
native libraries is not allowed in EJB. if some app servers allow this as an
enhacement, you need to look at the documentation of that particular app server to
find your answers. but overall, loading native libraries and using JNI from EJB is
prohibited by the spec. you could use JMS or MDBs to accomplish the same with
similar amount of work.
Comments and alternative answers

J2EE Connector
Author: Nick Minutello (http://www.jguru.com/guru/viewbio.jsp?EID=222214), Dec
9, 2001

What sort of functionality is in this C++ library? How fine-grained is the interface to
it? What does it do?

A valid means of using native code is to use the J2EE Connector Architecture.

However, I would strongly recommend that for C++ code, you dont use JNI. The
main reason is that a bug in your C++ code can bring your whole JVM down. It really
compromises the robustness that the appserver environment gives you.
If you really have to - then try use a separate Appserver for the JNI components - and
cluster them separately.

WebSphere and JNI


Author: leo de blaauw (http://www.jguru.com/guru/viewbio.jsp?EID=842771), Apr
17, 2002
Hi, I dont about your appserver. But we are facing a simular issue at our project here.
We are using websphere 4.0 which doesnt support MDB's in its current release. We do
however have to support and old legacy c++ dll with business rules in it which we
cannot go around at this time. Does anyone know if calling a native interface from
EJB's in websphere is allowed and if so if there is any level of protection for crashes
if you decide to do so ? Greetings, Leo de Blaauw

Re: WebSphere and JNI


Author: Anil Datt (http://www.jguru.com/guru/viewbio.jsp?EID=20887), May 2,
2002
We are using weblogic and since we were also in the same situtaion we went
ahead and used the jni code in teh session bean. Weblogic allows to make the JNI
calls from teh EJB , but any error in the C code brings down the whole app server.
Why dont you write a simple EJB and try to load any dll or shared library just to
see whether websphere allows it. I feel it alllows it. Click on this Link

EJB-JNI
Author: Wap Dev (http://www.jguru.com/guru/viewbio.jsp?EID=914149), Jun 13,
2002
I am devloping an application server which is in windows platform,i want to Invoke
Java Beans using JNI,whether it is possible or only normal .class files will be intiated

EJB-JNI-Legacy Integration(C++ API) ...


Author: Raffaele PAPA (http://www.jguru.com/guru/viewbio.jsp?EID=1007318), Oct
9, 2002
Hi there ! You can create an ejb that creates a wrapper class that instantiates the JNI
class which does the rest , e.g. calling the legacy subroutine in JBoss and in
WebSphere it works .... obviuosly remember that every static data got from the C++
procedure should be refreshed with ejbActivate ( ) [here it is a bit of sample code ( i'm
finishing to publish it ) on http://www.e-mplace.com/EJB-JNI.htm ] if you have some
question please email me at rsquek@virgilio.it Raffaele PAPA bye bye

Create a server/appserver running in a separate JVM


Author: geoff maude (http://www.jguru.com/guru/viewbio.jsp?EID=55701), Oct 24,
2002
The safest way to handle JNI integration would be to put it in a separate JVM
instance, though it need not be running an appserver (depends on your
scalability/transaction safety requirement.) If its not an EJB Server, at least have an
RMI interface.
In any case, you'd need a daemon to ping it heartbeat requests and restart it if/when it
crashes, and some expectant try blocks in your EJB in case it goes down.

Re: Create a server/appserver running in a separate JVM


Author: Amit T (http://www.jguru.com/guru/viewbio.jsp?EID=1048812), Jan 21,
2003
Can anyone be a little more specific about this server/appserver running in a
separate JVM. Any other site / article giving more info on this topic ??? Any help
would be most helpful

Re: Create a server/appserver running in a separate JVM


Author: Pedja Radojkovic
(http://www.jguru.com/guru/viewbio.jsp?EID=1083282), May 9, 2003
One possible solution can be to wrap your native C/C++ code in apache module
and let apache take care about executing it. Bad thing is that you have to
communicate with it via http. This solution can be good when your C/C++ library
is not thread safe, and you cannot execute it in one JVM. More about writing
apache modules you can find at www.apache.org.

JMS and message beans are the way to go


Author: Alexander Krapf (http://www.jguru.com/guru/viewbio.jsp?EID=221775), Jul
26, 2003
We have been asked this question many times over the years because we have a tool
that helps in the integration of Java and C++ code (JunC++ion).

In my opinion, in-process integration is not a good option and we always recommend


using MessageBeans in the EJB server and JMS C++ bindings in the external C++
process. Some JMS providers have proprietary C++ bindings, for all the others (or if
you don't want to lock yourself into a specific JMS vendor) you can use JMS Courier.

BTW: This is also possible for .NET applications using Codemesh's JuggerNET tool.

Re: JMS and message beans are the way to go


Author: suhas shahapurkar
(http://www.jguru.com/guru/viewbio.jsp?EID=1198687), Sep 13, 2004
Hi all, I want to access the JMS messages from the C++ code. The JMS messages
are in the Weblogic Server. Thanks in Advance!! Suhas S

Re[2]: JMS and message beans are the way to go


Author: Alexander Krapf
(http://www.jguru.com/guru/viewbio.jsp?EID=221775), Sep 13, 2004
Suhas,
AS I said, you probably don't want the C++ code to be running in the server
process. That means that you have to "JMS-enable" your C++ process. We do
this via our JMS Courier product by providing you with C++ wrapper classes
for the JMS API. The wrapper classes use JNI under the hood. You use the
wrapper classes in your C++ application just like you would use the Java
classes in a Java application.

If you don't want to purchase our product, you have several other choices:

1. write JNI code yourself (and have months of fun :-)


2. use a commercial JMS with some proprietary C++ extensions (and
have vendor lockin)
3. use a commercial JMS with some proprietary XML extensions (and
have vendor lockin)

The first alternative might actually not be too bad if all you need to do can be
wrapped up in one or two method calls. We usually recommend against doing
it by hand if you need advanced features like asynchronous callbacks (for
MessageListeners) or if you have more than 10 integration points.

Good luck,

Alex

What is the difference between Context, InitialContext and Session Context?


How they are used?
Location: http://www.jguru.com/faq/view.jsp?EID=584577
Created: Dec 14, 2001
Author: RATHAKRISHNAN K (http://www.jguru.com/guru/viewbio.jsp?EID=230041)
Question originally posed by Dipendra Jha
(http://www.jguru.com/guru/viewbio.jsp?EID=492227

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.

javax.naming.InitialContext is a Context and provides implementation for methods


available in the Context interface.

Where as SessionContext is an EJBContext object that is provided by the EJB


container to a SessionBean in order for the SessionBean to access the information
and/or services or the container.

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.

Comments and alternative answers

InitialContext
Author: rao ande (http://www.jguru.com/guru/viewbio.jsp?EID=760782), Feb 15,
2002
What can be inferred from implementing the methods in Context. i.e, Is it that if we
set the InitialContext and give a name, we are binding it by that name?

What are all the steps that are required to port EJB 1.1 code to EJB 2.0
compatible?
Location: http://www.jguru.com/faq/view.jsp?EID=585941
Created: Dec 15, 2001