Apache Cayenne > Index > Cayenne FAQ > Mapping Primary Keys
Added by Michael Gentry, last edited by Michael Gentry on Mar 08, 2005  (view change)

By default, Cayenne Modeler will not create a getter or setter for primary keys in the Java classes it generates. This is because primary keys are best viewed as a database artifact and generally aren't needed by the application.

Sometimes, however, a pre-existing schema will have meaningful primary keys (such as a Social Security Number) which must be visible or must be set directly. (It should be noted that Cayenne will not attempt to generate a primary key on INSERT unless the field is empty, therefore you can explicitly set a primary key value and bypass the generator.) To make a primary key available in a Java class, it must be mapped from the DbEntity to the ObjEntity, which is simple to do.

In Cayenne Modeler, do the following:

  1. Select the ObjEntity (the one with the icon beside it) in which you want the primary key to appear.
  2. Select the "Attributes" tab in the right-hand panel.
  3. Click on the "Create Attribute" icon ().
  4. Enter the Java name you want in the newly added attribute row under the "ObjAttribute" heading.
  5. Select the Java data type you want in the "Java Type" pulldown.
  6. Select the primary key (database name) in the "DbAttribute" pulldown.
  7. Click on the "Used for Locking" checkbox if you want to use the primary key for optimistic locking (you should have optimistic locking set on your ObjEntity, too).

That's it. When you next generate your Java classes, a getter and setter will be created.

Be Careful

If you alter a record's primary key value and other records reference that value, you need to ensure those other records pick up the change to the key, too.