Discussions

EJB programming & troubleshooting: how to protect setId in value-objects

  1. how to protect setId in value-objects (4 messages)

    We want to use value objects with our CMP EJB's. It seems wrong to expose the setId method for in the value object to our client code since that is a container managed field and the primary key field of the database. Yet the EJB needs the setId to be able to hand back a value object doesnt it. So what is the correct/best way protect the setId method in our ejb or vo? (note we are using ant/xdoclet to generate our interfaces etc if that is any help in answering)
    thanks - rich
  2. Hi,
    You could make the constructors of your value objects to use an 'id' argument.
    Best regards, Mircea
  3. Mircea's suggestion is the best one, since it allows you to make the instance variable for your id final.

    If this won't work (because you are using your setters with reflection), another useful trick is a "write-once" setter that rejects updates after the id has already been set:

    public void setId(Long id) {
        if (this.id != null) {
            this.id = id;
        }
    }
  4. Id dont see quite how the mechanisms suggested completely protect my EJB.

    Consider a client that requests a new value object corresponding to my ejb (by any method). They then call setId() to change the id to some other value and submit the value object for it for update. Presumably the update will succeed on the persisted item with the bogus id if it happens to exist in my database.

    Im looking for a way to allow clients to create new value objects or update existing ones, yet they can only update if they have first retrieved it. I dont want to let them modify the id via setId() then update and have the update occur to fields on an item they never actually retrieved.

    Thanks - Rich
  5. Hi,
    Yes you are right in this case So I have another proposition :-)
    1. make all your value objects implemment an Identifiable interface with set/get id. The clients work as usuall with your value objects, but the server knows is working with Idetifiable objects.
    2. this a varioation of the first solution, but with inheritance. The value objects that the client works with have no 'id' property. Extend the value objects with classes having the 'id' property. The server works with the extended value object.
    This might be ok for your case, except the case of a malicios client that makes a downcast or using reflection.
    Best regards, Mircea