Cayenne User Documentation
Generated Columns

## What Is a "Generated" Column

Many databases allow users to define special columns with values that are automatically created by the the database to be unique for each inserted row. Main use if this feature is to generate a primary key. Such columns are often called "autoincrement" or "identity" columns. JDBC3 specification provides Java API to read values of such columns right after an insert is performed. JDBC calls such columns "generated keys", and Cayenne follows JDBC in that. Namely DbAttribute has a `"generated"` boolean property to indicate that a given column value is provided by the database on insert.

## Generated Columns in Cayenne

Primary key generation is the only use of generated columns in Cayenne.

If a primary key column is marked as "generated" in CayenneModeler (see below), Cayenne will bypass its default PK generation mechanism and rely on the database to provide a key value. But only if the runtime DbAdapter is configured to allow that (see "Hints and Limitations" section for explanation). Currently only Derby, MySQL and SQLServer adapters allow generated columns by default. For the rest of the adapters, Cayenne will fall back to its default PK generation mechanism.

If you know that your driver supports generated keys API, but Cayenne assumes it does not, you can change this setting manually:

    DataNode node = ...
    JdbcAdapter adapter = (JdbcAdapter) node.getAdapter();
    adapter.setSupportsGeneratedKeys(true);

Use of generated keys for PK is configured for each DbEntity individually in CayenneModeler:

- Navigate to a DbEntity in question and select `"PK Generation Strategy"` to be `"Database-Generated"`:

- Select a PK column that will be auto-incremented by the database from the list of existing primary keys:

## Hints and Limitations

- Only a single DbAttribute can be marked as "generated" in a DbEntity. Most databases only allow a single generated column per table, and Cayenne consistently adheres to the same policy.
- Generated attribute must also be a primary key.
- Database must support this feature.
- JDBC driver must support this feature. Even if database supports identity columns, the driver may not. By default Cayenne assumes that the following drivers support it: Derby, MySQL and SQLServer jTDS (but not the MS) driver.

| MS SQLServer Note MS drivers prior to 2005 version do not support generated columns, while newer drivers and jTDS support it just fine. Cayenne can automatically detect the driver type and configure SQLServerAdapter, but only when AutoAdapter is used. To make sure auto-detection works, clear the "Custom Adapter" field for the corresponding DataNode in the Modeler.

.
Copyright ©2001-2008 Apache Software Foundation