Re: Recall object by it's PK? (e.g. w/Lucene)

From: Mike Kienenberger (mkienen..laska.net)
Date: Mon Apr 19 2004 - 14:54:59 EDT

  • Next message: Eric Schneider: "Re: Recall object by it's PK? (e.g. w/Lucene)"

    Craig Jones <crai..ankardsaweigh.com> wrote:
    > I need help figuring out how to recall a data object given the PK.
    >
    > Expression qual = ExpressionFactory.inExp("getId", idList); //
    > Tried with and w/o the "get"
    > SelectQuery cayenneQuery = new SelectQuery(MyObject.class,
    > qual);
    > return ctxt.performQuery(cayenneQuery);
    >
    > But Cayenne can't resolve the expression (presumably because the PK
    > property is not part of the mappings in the XML file?)
    >
    >
    > How do I tell Cayenne that the getId property is available for searching
    > without mucking up the auto-PK generation?

    You have to match a db expression instead obj expression. Check for
    inDbExp() or create it based on inExp.

    Here's a generic method I use (all my DataObjects inherit from
    GenericEntity).
    Alternatively, you can hardcode the name of the primary key attribute.

    -Mike

        public static GenericEntity objectMatchingPrimaryKey(DataContext
    aDataContext, Class aClass, Object aPrimaryKeyValue)
        {
            if (log.isTraceEnabled()) log.trace("in
    GenericRecord.objectMatchingPrimaryKey(DataContext, Class, Object)");

            EntityResolver anEntityResolver = aDataContext.getEntityResolver();
            DbEntity aDbEntity = anEntityResolver.lookupDbEntity(aClass);
            List pkDbAttributes = aDbEntity.getPrimaryKey();
            
            if (0 == pkDbAttributes.size()) throw new
    CayenneRuntimeException("no primary key found for class=" + aClass + ".");
            if (1 != pkDbAttributes.size()) throw new
    CayenneRuntimeException("multi-field primary key found for class=" + aClass
    + ".");
            
            DbAttribute primaryKeyDbAttribute =
    (DbAttribute)pkDbAttributes.get(0);
            String primaryKeyName = primaryKeyDbAttribute.getName();

            Expression qualifier = ExpressionFactory.matchDbExp(primaryKeyName,
    aPrimaryKeyValue);
                
            SelectQuery query = new SelectQuery(aClass, qualifier);
            List aList = aDataContext.performQuery(query);
            
            if (1 == aList.size()) return (GenericEntity)aList.get(0);
            
            if (0 == aList.size()) return null;
            
            throw new MoreThanOneException("Found " +
    String.valueOf(aList.size()) + " results for primary key=" +
    aPrimaryKeyValue);
        }
        



    This archive was generated by hypermail 2.0.0 : Mon Apr 19 2004 - 14:53:45 EDT