Primary key classes


EJB design: Primary key classes

  1. Primary key classes (2 messages)

    I have seen a number of examples showing how to create a BMP Entity bean. All of them promotes the creating of a primary key class for each bean. For instance:
    My entity bean is named Product. The primary key is a string.
    A primary key class ProductPK is then created. (See code below)
    Why is this convention used, when I could simply use java.lang.String as my primary key class?

    /Mattias Arbin

    public class ProductPK implements {

        public String productId;
        public ProductPK(String s) {
        public ProductPK() {}
        public String toString() {
         return productId;

    Threaded Messages (2)

  2. Primary key classes[ Go to top ]

    I just found an answer to my own question in a WebLogic FAQ (see below)
    If anybody has another opinion, please let me know.

    "Always write a custom primary key class for entity beans
    For container-managed persistence, the EJB 1.0 specification requires you supply an application-defined primary key class. But for bean-managed persistence, the class can be any non-primitive type (such as java.lang.String).
    However, since the signature of findByPrimaryKey() requires you to supply the primary key class as the argument, if you ever change the implementation from bean-managed to container-managed persistence, you will be forced to change the home interface and consequently affect all current users of that bean."

    Moral of the story: always write a custom primary key class unless you are certain that you are never going to change the type of persistence.

  3. Primary key classes[ Go to top ]

    Note that this is not valid anymore in the EJB 1.1 spec, where a String (as well as every other simple type) can be used as primary key, even in CMP.
    In fact, in EJB 1.1, you should only use a custom PK class if the PK is a compound key.