Re: Simple retrieval of an object by PK

From: Andrus Adamchik (andru..bjectstyle.org)
Date: Thu Jul 15 2004 - 16:53:23 EDT

  • Next message: Gentry, Michael: "RE: Simple retrieval of an object by PK"

    On Jul 15, 2004, at 4:17 PM, Jonathan Carlson wrote:

    > I gravitate towards powerful tools that make simple things simple and
    > hard things possible. I know that Cayenne is in this category of
    > tools, but I don't see any way to simply and quickly retrieve an
    > instance by it's primary key -- something that should be very easy and
    > concise.
    >
    > For example, when doing web apps this seems like a common use case: ...

    In JSP and Struts it is, but not in Tapestry and WebObjects. I
    personally can't remember if I ever used bare PK values in URLs, as I
    rarely needed to build a URL manually, and also I consider it a
    security risk. So I guess none of the developers cared to make this a
    one liner.

    Still lots of people use it (and actually asked about it on this list,
    but no one ever opened a feature request). And we should probably add
    such utility method, as there is lots of popular demand, but you can
    easily create one yourself (write 6 lines of code once and use it
    everywhere ;-)).

    The archives should contain various implementations that others have
    come up with. Here is yet another one. It is generic and works for any
    DataObject type, so there is a little more work inside the method...
    Also you can easily create a similar but simpler static method inside a
    custom class generation template, so that it is included in each
    _MyPersistentClass.java:

    public DataObject objectForId(DataContext context, Class objectClass,
    int id) {
        DbEntity entity =
    context.getEntityResolver().lookupDbEntity(objectClass);
        DbAttribute pk = (DbAttribute) entity.getPrimaryKey().get(0);
        SelectQuery q = QueryUtils.selectObjectForId(new
    ObjectId(objectClass, pk.getName(), id));

        List objects = context.performQuery(q);
        if(objects.size() == 1) {
            return (DataObject) object.get(0);
        }

        throw RuntimeException("Something terrible has happened.");
    }

    Cheers,
    Andrus



    This archive was generated by hypermail 2.0.0 : Thu Jul 15 2004 - 16:53:28 EDT