Leonardo,
> Hi everybody,
>
> how can we select an object by its pk value?
Based on advice and code snippets from others on the list, here is what
I have to select an object by its PK value. I've also included the
reverse method that obtains the PK value from an object.
/**
* Given a class and a primary key value, returns the proper object
* or <code>null</code> if none exists.
* <p>
* The object's primary key column must be named "id" (if not, change
* this method to accept the column name, too).
*
*..aram klass the Java class of the model object
*..aram pk the primary key value
*..aram context a database context
*..eturn the object
*/
public static Object objectFromPrimaryKey(Class klass, int pk,
DataContext context)
{
ObjectId oid = new ObjectId(klass, "id", pk);
SelectQuery query = QueryUtils.selectObjectForId(oid);
List list = context.performQuery(query);
if (list.size() == 1)
return list.get(0);
else
return null;
// Or this, but if there was no such object in the database then it
would
// fail.
// ObjectId oid = new ObjectId(klass, "id", pk);
// return context.registeredObject(oid);
}
/**
* Utility methods for dealing directly with primary keys, which should
* be a rare occurrence.
*
*..uthor Jim Menard, <a href="mailto:jimm@io.com">jimm@io.com</a>
*/
public class PrimaryKey {
/**
* We need to return the primary key of a few data objects as numbers.
* Here's how to get them.
*/
public static Number primaryKeyOf(DataObject dataObj) {
String pkStr = null;
Map pkAttributes = dataObj.getObjectId().getIdSnapshot();
// FIX what to do? This should not happen.
// if (pkAttributes.size() != 1)
// throw new Exception("multi-field primary key found");
Iterator iter = pkAttributes.keySet().iterator();
String pkName = (String)iter.next();
return (Number)pkAttributes.get(pkName);
}
Jim
-- Jim Menard, jim..o.com, http://www.io.com/~jimm/ "Any sufficiently advanced technology is indistinguishable from a rigged demo." -- Unknown
This archive was generated by hypermail 2.0.0 : Wed Jan 07 2004 - 07:17:15 EST