How can I configure foreign keys through column tag attributes foreignKeyName
and references
? The only example I've found demonstrates how to add foreign keys after the fact.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It acts as a cross-reference between tables because it references the primary key of another table, thereby establishing a link between them.
Foreign key is a field in the database table that is a primary key in other tables. The naming conventions for a foreign key constraint should have an "FK_" prefix, followed by the target table name, followed by the source table name. The syntax should be "FK_<TargetTable>_<SourceTable>".
Use a nested <constraints>
tag in your column tag.
Example:
<changeSet id="SAMPLE_1" author="alice"> <createTable tableName="employee"> <column name="id" type="int" autoIncrement="true"> <constraints primaryKey="true"/> </column> <column name="first_name" type="varchar(255)"/> <column name="last_name" type="varchar(255)"> <constraints nullable="false"/> </column> </createTable> </changeSet> <changeSet id="create address table" author="bob"> <createTable tableName="address"> <column name="id" type="int" autoIncrement="true"> <constraints primaryKey="true"/> </column> <column name="line1" type="varchar(255)"> <constraints nullable="false"/> </column> <column name="line2" type="varchar(255)"/> <column name="city" type="varchar(100)"> <constraints nullable="false"/> </column> <column name="employee_id" type="int"> <constraints nullable="false" foreignKeyName="fk_address_employee" references="employee(id)"/> </column> </createTable> </changeSet>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With