|
Using compound primary keys for entities |
|
|
Typically, primary key values are more complex than a single column. Compound primary keys are an excellent way to drill
down to specific data. Using a compound primary key is more complex for both CMP and BMP entity beans. For both types
of beans, you must create a primary key class that follows specific rules, and also configure your entity bean to properly
use an instance of the class.
To provide a compound primary key for an entity bean, you must create a primary key class. In this example, we define a complex
key for a person table. This key consists of a first and last names of a person :
A primary key class:
public class PersonKey implements java.io.Serializable {
public String firstName;
public String lastName;
// a default constructor is required:
public PersonKey() { }
// optional constructor fo clients:
public PersonKey(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String toString() { return firstName + " " + lastName; }
// these methods are required overloaded:
public boolean equals(Object o) { ... }
public int hashCode() { ... }
}
|
A bean using compound key:
public abstract class PersonBean implements EntityBean {
// defines a create method to accept primary-key fields:
public PersonKey ejbCreate(String firstName, String lastName)
throws CreateException {
setFirstName(firstName);
setLastName(lastName);
// always returns null;
return null;
}
abstract public String getFirstName();
abstract public void setFirstName(String firstName);
abstract public String getLastName();
abstract public void setLastName(String lastName);
}
|
Deployment descriptor definitions:
<ejb-jar>
<enterprise-beans>
<!-- main bean definitions -->
<entity>
...
<ejb-class>test.PersonBean</ejb-class>
<!-- declaration of a primary key class -->
<prim-key-class>PersonKey</prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>firstName</field-name>
</cmp-field>
<cmp-field>
<field-name>lastName</field-name>
</cmp-field>
</entity>
</enterprise-beans>
</ejb-jar>
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.