Primary keys in `ObjEntity`

51 Views Asked by At

Primary keys get special treatments in the default ObjEntitys generated in the GUI. They are removed from the properties, and it seems the best way to get them would be via the .getObjectId().getIdSnapshot(), as a Map<String, Object>, and to set them with one of the ObjectId.of() variants to create one.

I feel I'm missing something here -- why are the primary key column(s) not exposed like other columns? Is there a better way to get / set PKs? The Map<String, Object>-way is much less convenient and less type-safe, than the cgened getters and setters.

I'm talking about the default behavior of creating a ObjEntity from a DbEntity in the GUI. I found I could add the property mappings manually in the ObjEntity editing window. But I feel it's me fighting the tool instead of letting it help me.

1

There are 1 best solutions below

0
On

why are the primary key column(s) not exposed like other columns

To have a universal interface to the ID no matter what the actual ID structure is (single column, multiple columns, etc.) Also the fact that in many cases the ID parts are managed by the framework (generated keys, keys propagated from relationships).

the best way to get them would be via the .getObjectId().getIdSnapshot()

Possible. Also check Cayenne.longPkForObject(..) / Cayenne.intPkForObject(..)

I could add the property mappings manually in the ObjEntity editing window.

Correct. That's an approach mostly recommended for "meaningful" keys that are provided by the user. For DB-generated keys, instead of mapping the ID as an ObjAttribute, I'd recommend creating a cover method to read the one encoded in ObjectId:

class MyClass extends _MyClass {

   public long getId() {
      return Cayenne.longPkForObject(this);
   }

}