The real power of entity beans is synchronization

The bean and the underlying row in the database must stay in sync! Remember, the bean is not the entity—the bean is a representation of the real entity. The bean is an OO way of working with the data, but the entity in the database is the only true entity. If the entity in the database dies (i.e. is deleted), the bean for that specific entity dies too (although the bean instance still lives, as you saw in the last chapter).

The Container’s job is make sure that the entity and the bean stay in sync, so that nobody’s looking at a stale bean or a stale row in the database. Keep in mind that the entity bean may not be the only way to get into the database! In fact, in most cases the Bean Provider (you) will have no way to know for certain, during development, if your bean is the only way anyone will ever be able to get to the entity data.

For example, your Customer database might be used by a bunch of apps in your company, including some that work directly with the database and some that go through the Customer bean in an EJB application.

If a client has a reference to a bean, the client might change the bean’s state by, say, calling a setter method. If that setter method corresponds to one of the bean’s persistent fields (in other words, a column in the table like address), the bean and the database will be temporarily out of sync. The database won’t have the current address until the bean updates the database!

Now think what a disaster ...

Get Head First EJB now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.