Aristedes Maniatis wrote:
>
> Objects will only be given their primary key after they are committed
> to the database. However 9 times out of 10, users new to Cayenne who
> want to use the pk for something find that there is a better way which
> doesn't involve using the primary key. What do you want to do with the
> pk?
>
I'd agree with that. In all the apps we've written over the past few
years, we've had only one case where we needed to get the next pk before
committing. (For historical reasons, the pk value had significance to
the users. But even that case we don't use any more... we just let the
user specify the pk value there.)
Anyway, if you need to do it, this code works:
public Integer getNewOid()
{
DataContext dc = getDataContext();
// Get the DataMap; we have only one in our model.
Collection dataMaps = dc.getEntityResolver().getDataMaps();
Iterator it = dataMaps.iterator();
DataMap dataMap = (DataMap) it.next();
DataNode dataNode =
dc.getParentDataDomain().lookupDataNode(dataMap);
EntityResolver resolver = dataNode.getEntityResolver();
DbEntity dbEntity = resolver.lookupDbEntity(this);
PkGenerator pkGenerator = dataNode.getAdapter().getPkGenerator();
Integer oid = null;
try {
Object pk = pkGenerator.generatePkForDbEntity(dataNode,
dbEntity);
// For us the pk is always an Integer.
oid = (Integer) pk;
}
catch (Exception ex) {
ex.printStackTrace();
}
return oid;
}
This archive was generated by hypermail 2.0.0 : Tue Mar 27 2007 - 08:17:48 EDT