Finding data using an access bean

You will be using access beans in your business logic when you want to find data in the WebSphere Commerce database. Within an access bean, you must select the appropriate database record by using the primary key, or a finder method.

Finding data by primary key

The following code snippet demonstrates how to select using a primary key.

The first line in the following code snippet instantiates a new UserProfileAccessBean that is called "abUserProfile". The second line sets the primary key in the access bean. The setInitKey_ xxx (where xxx is the primary key field name) naming convention is used by WebSphere Commerce Developer to name the set methods for primary keys.

//create a new access bean
UserProfileAccessBean abUserProfile = new UserProfileAccessBean();

// set the primary key
abUserProfile.setInitKey_UserId(getUserId().toString());

//call getter to get the DisplayName.  This will also fully populate the access bean with data.
String myDisplayName = abUserProfile.getDisplayName();

When to use refreshCopyHelper()

Use the refreshCopyHelper method to retrieve information from the database and populate the access bean. You do not need to use the refreshCopyHelper() if you are using a getter method to retrieve specific data from the access bean. You only need to use it to explicitly tell the access bean to populate itself, for example, to check if the data you are looking for exists, or to populate an object before passing it to another method.

For example:
//Create a new access bean
UserProfileAccessBean abUserProfile = new UserProfileAccessBean();

//Set the primary key
abUserProfile.setInitKey_UserId(getUserId().toString());

//Call refreshCopyHelper to populate it with data
abUserProfile.refreshCopyHelper();
Note: When instantiating an access bean, you must ensure that all fields set by a setInitKey_xxx method are initialized before retrieving any data from the access bean. This includes using any getter methods or calling the refreshCopyHelper() method. The order in which the setInitKey_xxx methods are called is not important.

Finding data using a finder method

Access beans may also provide specific finder methods for commonly needed "find" operations. These methods will return you an Enumeration of access beans that match the find criteria. If records are found, there will be one or more fully populated access beans in the Enumeration. If the result of the finder is empty, the finder method will throw javax.ejb.ObjectNotFoundException.

For example, in the following code sample, if no users are found with the specified nick name, ObjectNotFoundException is caught and logged.

AddressAccessBean abAddress = new AddressAccessBean().findByNickname("nickname", new Long("10001")); 
Where nickname is the search term used for the nick name.
Note: The returned value can be single objects in a finder, or an enumeration.