Use Dirty Flags in ejbStore
The ejbStore( )
method is usually called at the end of each transaction in which an
entity bean participates. Given that the container cannot know if a
bean-managed persistence (BMP) entity bean actually changed (and thus
needs to be saved), it will always call the entity’s
ejbStore( ). Because a typical transaction
involves many entity beans, at the end of the transaction the
container will call ejbStore( ) on all these
beans, even though only a few might have actually changed. This is
usually a big performance bottleneck because most entity beans will
communicate with the database.
To solve this problem, a common solution is to use
“dirty flags” in your EJB
implementation. Using them is very simple: have a
boolean flag indicate whether the data in the
entity bean has changed. Whenever one of the business methods
modifies the data, set the flag to true. Then, in
ejbStore( ), check the flag and update the
database if needed. Example 2-6 illustrates this.
public class MyBean implements EntityBean { // Your dirty flag private boolean isModified; // Some data stored in this entity bean private String someString; // You've skipped most of the unrelated methods . . . public void ejbLoad( ) { // Load the data from the database. // So far, your data reflects the database data. isModified = false; } public void ejbStore( ) { // No need to save? if (!isModified) return; // Data has been changed; update the database. ...