@PrimaryKey
@PrimaryKey registers one or more columns as the entity's primary index. See
Primary Keys for the full guide.
function PrimaryKey(
options?: Omit<IndexMetadata, 'columns' | 'unique' | 'primary'>,
): PropertyDecorator;
function PrimaryKey(
fields: string | string[],
options?: Omit<IndexMetadata, 'columns' | 'unique' | 'primary'>,
): ClassDecorator;
As a property decorator (single-column key)
@PrimaryKey()
@Column({ dataType: DataType.BIGINT, autoGenerated: 'increment' })
declare id?: number;
Placed directly on the key property, alongside @Column. This form implicitly runs
Column({ notNull: true }) on the property before registering it as the primary index — so
the column is notNull: true even if you never call @Column yourself, and if you do stack
@Column below it (decorators apply bottom-up), your own column options are merged on top of
that implicit notNull: true.
As a class decorator (composite key)
@Entity({ tableName: 'customer_tags' })
@PrimaryKey(['customerId', 'tagId'], { name: 'pk_customer_tags' })
class CustomerTag { /* ... */ }
Takes the property name(s) making up the key. This is the only way to declare a composite
primary key, and it does not imply notNull on the referenced columns — declare that yourself
if needed.
Options
Both forms accept an options object typed as Omit<IndexMetadata, 'columns' | 'unique' | 'primary'>
— in practice, just name:
| Option | Type | Description |
|---|---|---|
name | string | Optional name for the underlying index/constraint. |
Internally, @PrimaryKey always creates an index with unique: true and primary: true; only
one index per entity can be primary — the last one registered wins.
Reading primary-key metadata
Entity.getPrimaryIndex(Customer); // IndexMetadata | undefined
Entity.getPrimaryIndexColumns(Customer); // ColumnFieldMetadata[]