Primary Keys
Stormify supports simple primary keys, composite keys, and auto-generated keys. You can mark primary-key fields explicitly with annotations, or register a resolver that identifies them by naming convention.
Custom Primary Key Resolvers
Primary keys in databases commonly follow a naming convention. If this is the case, instead of using annotations, you can register custom primary key resolvers to help Stormify identify primary keys based on their name.
How It Works
To set up a primary key resolver, use the registerPrimaryKeyResolver method. You provide:
- Priority: A numeric value that determines execution order when multiple resolvers are registered. Higher values are checked earlier. The default priority is 0; use values like 10, 20, etc. to run before the default.
- Resolver Function: A function that receives the table name and field name, and returns
trueif the field should be treated as a primary key.
Example
In this example:
- The resolver checks if the field name is
id, a common but not universal pattern. - The priority
10means this resolver runs earlier than any default (priority 0) resolvers.
By setting up custom primary key resolvers, Stormify can accurately identify primary keys without relying on annotations for every class.
Handling Auto-Increment Fields
Stormify can manage auto-increment fields automatically by leveraging database sequences or letting the database handle the generation of primary key values. You can specify this behavior using the @DbField annotation's primaryKey and primarySequence attributes.
Using Sequences
If your database uses sequences for generating primary keys, you can specify the sequence name using the primarySequence attribute in the @DbField annotation.
Example
In this example, the id field uses the sequence named id_seq to generate its values.
Working with Composite Keys
Stormify supports tables with composite primary keys, allowing you to define multiple fields as part of the primary key.
Defining Composite Keys
To define a composite key, mark all fields involved in the key as primary keys using annotations or a resolver function.
Example
In this example, both part1 and part2 fields form the composite primary key.