When does the container call my bean's ejbCreate / ejbPostCreate /ejbStore / ejbPassivate / ejbActivate / ejbLoad / ejbPassivate method? And what should I do inside it?
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").
- 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.
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 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:
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