In TypeORM, you can set or change the alias of a database column by using the name property of the @Column decorator. This allows you to use a different name in your code compared to the database. The benefit is that it helps maintain code clarity and readability while allowing the database table structure to remain optimized and consistent.
Example
Suppose you have a user entity, and you want to map the username column in the database to the loginName property in the entity.
typescriptimport { Entity, PrimaryGeneratedColumn, Column } from "typeorm"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column({ name: "username" }) loginName: string; // Other properties... }
In the above example, @Column({ name: "username" }) indicates that the field in the database is called username, but in your code, you reference it through the loginName property. After this setup, when you query or update this column, you should use loginName, and TypeORM will automatically handle the mapping to the database column username.
Use Cases
This mapping is particularly useful in the following scenarios:
- When database column names do not conform to your coding style or naming conventions.
- When migrating legacy systems, to gradually transition to new column names.
- To hide or abstract the underlying database column names, making the code cleaner.
This approach makes the code more flexible in decoupling from the database, and maintenance and understanding are easier.