CHAPTER 9 Working with objects However, there are (Managed web hosting)

CHAPTER 9 Working with objects However, there are again two problems with this approach. First, instances from different Sessions are no longer equal if one is modified (for example, if the user changes the password). Second, instances with different database identity (instances that represent different rows of the database table) can be considered equal unless some combination of properties is guaranteed to be unique (the database columns have a unique constraint). In the case of user, there is a unique property: username. This leads us to the preferred (and semantically correct) implementation of an equality check. You need a business key. Implementing equality with a business key To get to the solution that we recommend, you need to understand the notion of a business key. A business key is a property, or some combination of properties, that is unique for each instance with the same database identity. Essentially, it s the natural key that you would use if you weren t using a surrogate primary key instead. Unlike a natural primary key, it isn t an absolute requirement that the business key never changes as long as it changes rarely, that s enough. We argue that essentially every entity class should have some business key, even if it includes all properties of the class (this would be appropriate for some immutable classes). The business key is what the user thinks of as uniquely identifying a particular record, whereas the surrogate key is what the application and database use. Business key equality means that the equals() method compares only the properties that form the business key. This is a perfect solution that avoids all the problems described earlier. The only downside is that it requires extra thought to identify the correct business key in the first place. This effort is required anyway; it s important to identify any unique keys if your database must ensure data integrity via constraint checking. For the User class, username is a great candidate business key. It s never null, it s unique with a database constraint, and it changes rarely, if ever: public class User { … public boolean equals(Object other) { if (this==other) return true; if ( !(other instanceof User) ) return false; final User that = (User) other; return this.username.equals( that.getUsername() ); } public int hashCode() {
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.