0
# Entity Definition
1
2
Comprehensive entity definition system using TypeScript decorators for defining database schemas, relationships, and constraints with compile-time type safety. TypeORM's decorator-based approach provides a clean and intuitive way to map TypeScript classes to database tables.
3
4
## Capabilities
5
6
### Core Entity Decorators
7
8
Basic decorators for defining entities and their core properties.
9
10
```typescript { .api }
11
/**
12
* Marks a class as a database entity (table)
13
* @param options - Entity configuration options
14
*/
15
function Entity(options?: EntityOptions): ClassDecorator;
16
17
/**
18
* Marks a class as a child entity in table inheritance
19
* @param discriminatorValue - Value used to identify this child type
20
*/
21
function ChildEntity(discriminatorValue?: any): ClassDecorator;
22
23
/**
24
* Configures table inheritance strategy for an entity
25
* @param options - Inheritance configuration
26
*/
27
function TableInheritance(options: TableInheritanceOptions): ClassDecorator;
28
29
/**
30
* Marks a class as a database view entity
31
* @param options - View entity configuration
32
*/
33
function ViewEntity(options: ViewEntityOptions): ClassDecorator;
34
35
interface EntityOptions {
36
/** Custom table name (defaults to class name) */
37
name?: string;
38
/** Database name (for multi-database setups) */
39
database?: string;
40
/** Schema name (for databases supporting schemas) */
41
schema?: string;
42
/** Storage engine (MySQL specific) */
43
engine?: string;
44
/** Whether to synchronize this entity */
45
synchronize?: boolean;
46
/** Default ordering for queries */
47
orderBy?: Record<string, "ASC" | "DESC">;
48
/** Entity comment */
49
comment?: string;
50
}
51
52
interface TableInheritanceOptions {
53
/** Inheritance pattern: single-table or joined-table */
54
pattern: "STI" | "CTI";
55
/** Column name for discriminator (STI only) */
56
column?: string;
57
}
58
```
59
60
**Usage Examples:**
61
62
```typescript
63
import { Entity, ChildEntity, TableInheritance } from "typeorm";
64
65
// Basic entity
66
@Entity("users")
67
export class User {
68
// ... properties
69
}
70
71
// Entity with custom options
72
@Entity({
73
name: "user_profiles",
74
schema: "public",
75
orderBy: {
76
createdAt: "DESC"
77
},
78
comment: "User profile information"
79
})
80
export class UserProfile {
81
// ... properties
82
}
83
84
// Table inheritance - parent class
85
@Entity()
86
@TableInheritance({ column: "type", pattern: "STI" })
87
export class Content {
88
@Column({ type: "varchar" })
89
type: string;
90
// ... common properties
91
}
92
93
// Child entities
94
@ChildEntity("article")
95
export class Article extends Content {
96
// ... article-specific properties
97
}
98
99
@ChildEntity("video")
100
export class Video extends Content {
101
// ... video-specific properties
102
}
103
```
104
105
### Column Decorators
106
107
Decorators for defining table columns with various data types and constraints.
108
109
```typescript { .api }
110
/**
111
* Marks a property as a database column
112
* @param options - Column configuration options
113
*/
114
function Column(options?: ColumnOptions): PropertyDecorator;
115
116
/**
117
* Marks a property as a primary key column
118
* @param options - Primary column options
119
*/
120
function PrimaryColumn(options?: ColumnOptions): PropertyDecorator;
121
122
/**
123
* Marks a property as an auto-generated primary key column
124
* @param strategy - Generation strategy: "increment", "identity", "uuid", "rowid"
125
* @param options - Column options
126
*/
127
function PrimaryGeneratedColumn(
128
strategy?: "increment" | "identity" | "uuid" | "rowid",
129
options?: ColumnOptions
130
): PropertyDecorator;
131
132
/**
133
* Automatically sets creation timestamp
134
* @param options - Column options
135
*/
136
function CreateDateColumn(options?: ColumnOptions): PropertyDecorator;
137
138
/**
139
* Automatically sets update timestamp
140
* @param options - Column options
141
*/
142
function UpdateDateColumn(options?: ColumnOptions): PropertyDecorator;
143
144
/**
145
* Timestamp column for soft deletes
146
* @param options - Column options
147
*/
148
function DeleteDateColumn(options?: ColumnOptions): PropertyDecorator;
149
150
/**
151
* Version column for optimistic locking
152
* @param options - Column options
153
*/
154
function VersionColumn(options?: ColumnOptions): PropertyDecorator;
155
156
/**
157
* Virtual/computed column that doesn't exist in database
158
* @param options - Virtual column options
159
*/
160
function VirtualColumn(options?: VirtualColumnOptions): PropertyDecorator;
161
162
/**
163
* Column specifically for database views
164
* @param options - View column options
165
*/
166
function ViewColumn(options?: ColumnOptions): PropertyDecorator;
167
168
/**
169
* MongoDB ObjectId column
170
* @param options - Column options
171
*/
172
function ObjectIdColumn(options?: ColumnOptions): PropertyDecorator;
173
174
interface ColumnOptions {
175
/** Column data type */
176
type?: ColumnType;
177
/** Column name in database */
178
name?: string;
179
/** Column length (for string types) */
180
length?: number;
181
/** Column precision (for decimal types) */
182
precision?: number;
183
/** Column scale (for decimal types) */
184
scale?: number;
185
/** Whether column allows NULL values */
186
nullable?: boolean;
187
/** Default column value */
188
default?: any;
189
/** Column comment */
190
comment?: string;
191
/** Whether column is primary key */
192
primary?: boolean;
193
/** Whether column is unique */
194
unique?: boolean;
195
/** Column charset (MySQL specific) */
196
charset?: string;
197
/** Column collation */
198
collation?: string;
199
/** Value transformer for serialization/deserialization */
200
transformer?: ValueTransformer | ValueTransformer[];
201
/** Whether to select this column by default */
202
select?: boolean;
203
/** Whether to insert this column */
204
insert?: boolean;
205
/** Whether to update this column */
206
update?: boolean;
207
/** Array type (PostgreSQL specific) */
208
array?: boolean;
209
/** Enum values (for enum columns) */
210
enum?: Object | (string | number)[];
211
/** PostgreSQL-specific options */
212
hstoreType?: "object" | "string";
213
}
214
```
215
216
**Usage Examples:**
217
218
```typescript
219
import {
220
Entity,
221
Column,
222
PrimaryGeneratedColumn,
223
CreateDateColumn,
224
UpdateDateColumn,
225
DeleteDateColumn,
226
VersionColumn
227
} from "typeorm";
228
229
@Entity()
230
export class User {
231
@PrimaryGeneratedColumn("uuid")
232
id: string;
233
234
@Column({
235
type: "varchar",
236
length: 100,
237
nullable: false,
238
comment: "User's full name"
239
})
240
name: string;
241
242
@Column({
243
type: "varchar",
244
length: 255,
245
unique: true,
246
transformer: {
247
to: (value: string) => value.toLowerCase(),
248
from: (value: string) => value
249
}
250
})
251
email: string;
252
253
@Column({
254
type: "int",
255
default: 0,
256
unsigned: true
257
})
258
loginCount: number;
259
260
@Column({
261
type: "enum",
262
enum: ["active", "inactive", "pending"],
263
default: "pending"
264
})
265
status: "active" | "inactive" | "pending";
266
267
@Column({
268
type: "text",
269
nullable: true
270
})
271
bio?: string;
272
273
@Column({
274
type: "decimal",
275
precision: 10,
276
scale: 2,
277
default: 0
278
})
279
balance: number;
280
281
// PostgreSQL array column
282
@Column({
283
type: "text",
284
array: true,
285
default: () => "ARRAY[]::text[]"
286
})
287
tags: string[];
288
289
// JSON column
290
@Column({
291
type: "jsonb",
292
nullable: true
293
})
294
metadata?: Record<string, any>;
295
296
@CreateDateColumn()
297
createdAt: Date;
298
299
@UpdateDateColumn()
300
updatedAt: Date;
301
302
@DeleteDateColumn()
303
deletedAt?: Date;
304
305
@VersionColumn()
306
version: number;
307
}
308
```
309
310
### Constraint and Index Decorators
311
312
Decorators for defining database constraints and indexes for data integrity and performance.
313
314
```typescript { .api }
315
/**
316
* Creates a database index on the decorated property
317
* @param options - Index configuration options
318
*/
319
function Index(options?: IndexOptions): PropertyDecorator;
320
321
/**
322
* Creates a database index with custom name and configuration
323
* @param name - Index name
324
* @param options - Index configuration options
325
*/
326
function Index(name: string, options?: IndexOptions): PropertyDecorator;
327
328
/**
329
* Creates a unique constraint on the decorated property
330
* @param options - Unique constraint options
331
*/
332
function Unique(options?: UniqueOptions): PropertyDecorator;
333
334
/**
335
* Creates a unique constraint with custom name
336
* @param name - Constraint name
337
* @param columns - Column names for composite unique constraint
338
*/
339
function Unique(name: string, columns: string[]): ClassDecorator;
340
341
/**
342
* Creates a check constraint on the entity
343
* @param name - Constraint name
344
* @param expression - SQL expression for the check
345
*/
346
function Check(name: string, expression: string): ClassDecorator;
347
348
/**
349
* Creates an exclusion constraint (PostgreSQL specific)
350
* @param name - Constraint name
351
* @param expression - Exclusion expression
352
*/
353
function Exclusion(name: string, expression: string): ClassDecorator;
354
355
/**
356
* Marks a column value as generated by the database
357
* @param strategy - Generation strategy: "increment", "uuid", "rowid"
358
*/
359
function Generated(strategy?: "increment" | "uuid" | "rowid"): PropertyDecorator;
360
361
interface IndexOptions {
362
/** Index name */
363
name?: string;
364
/** Whether index is unique */
365
unique?: boolean;
366
/** Spatial index (MySQL specific) */
367
spatial?: boolean;
368
/** Full-text index (MySQL specific) */
369
fulltext?: boolean;
370
/** Index method (PostgreSQL specific) */
371
using?: string;
372
/** Partial index condition (PostgreSQL specific) */
373
where?: string;
374
/** Index columns for composite index */
375
columns?: string[];
376
/** Whether to synchronize this index */
377
synchronize?: boolean;
378
}
379
```
380
381
**Usage Examples:**
382
383
```typescript
384
import { Entity, Column, Index, Unique, Check, Generated } from "typeorm";
385
386
@Entity()
387
@Index(["email", "status"]) // Composite index on class
388
@Unique("UQ_USER_EMAIL_DOMAIN", ["email", "domain"])
389
@Check("CHK_USER_AGE", "age >= 0 AND age <= 150")
390
export class User {
391
@PrimaryGeneratedColumn()
392
id: number;
393
394
@Column()
395
@Index() // Simple index
396
email: string;
397
398
@Column()
399
@Index("IDX_USER_STATUS") // Named index
400
status: string;
401
402
@Column()
403
@Unique() // Unique constraint
404
username: string;
405
406
@Column()
407
@Index({ unique: true, name: "IDX_USER_SSN" }) // Unique index
408
ssn: string;
409
410
@Column()
411
age: number;
412
413
@Column()
414
domain: string;
415
416
// PostgreSQL specific examples
417
@Column({ type: "tsvector" })
418
@Index({ using: "gin" }) // GIN index for full-text search
419
searchVector: string;
420
421
@Column()
422
@Generated("uuid")
423
uuid: string;
424
425
// Partial index (PostgreSQL)
426
@Column()
427
@Index({
428
where: "active = true",
429
name: "IDX_ACTIVE_USERS_EMAIL"
430
})
431
active: boolean;
432
}
433
```
434
435
### Embedded and Composite Types
436
437
Support for embedded objects and composite types for better data organization.
438
439
```typescript { .api }
440
/**
441
* Embeds properties of another class into this entity
442
* @param type - Class to embed
443
* @param options - Embedded options
444
*/
445
function Embedded(
446
type: () => Function,
447
options?: EmbeddedOptions
448
): PropertyDecorator;
449
450
/**
451
* Marks a class as embeddable
452
*/
453
function Embeddable(): ClassDecorator;
454
455
interface EmbeddedOptions {
456
/** Prefix for embedded columns */
457
prefix?: string | boolean;
458
/** Array of embedded objects */
459
array?: boolean;
460
}
461
```
462
463
**Usage Examples:**
464
465
```typescript
466
import { Entity, Column, Embedded, Embeddable } from "typeorm";
467
468
// Embeddable class
469
@Embeddable()
470
export class Address {
471
@Column()
472
street: string;
473
474
@Column()
475
city: string;
476
477
@Column()
478
state: string;
479
480
@Column()
481
zipCode: string;
482
483
@Column()
484
country: string;
485
}
486
487
@Embeddable()
488
export class Name {
489
@Column()
490
first: string;
491
492
@Column()
493
last: string;
494
}
495
496
// Entity using embedded types
497
@Entity()
498
export class User {
499
@PrimaryGeneratedColumn()
500
id: number;
501
502
@Embedded(() => Name)
503
name: Name;
504
505
@Embedded(() => Address, { prefix: "home_" })
506
homeAddress: Address;
507
508
@Embedded(() => Address, { prefix: "work_" })
509
workAddress: Address;
510
}
511
512
// Results in columns: id, nameFirst, nameLast, home_street, home_city, etc.
513
```
514
515
## Column Types
516
517
TypeORM supports a wide range of column types across different databases:
518
519
### Common Types
520
521
- `int`, `integer`, `tinyint`, `smallint`, `mediumint`, `bigint`
522
- `float`, `double`, `decimal`, `numeric`
523
- `char`, `varchar`, `text`, `tinytext`, `mediumtext`, `longtext`
524
- `boolean`, `bool`
525
- `date`, `time`, `datetime`, `timestamp`
526
- `json`, `jsonb` (PostgreSQL)
527
- `enum`
528
- `uuid`
529
- `blob`, `longblob`, `bytea`
530
531
### Database-Specific Types
532
533
- **PostgreSQL**: `array`, `hstore`, `ltree`, `point`, `line`, `polygon`, `geometry`, `geography`
534
- **MySQL**: `year`, `bit`, `geometry`, `point`, `linestring`, `polygon`
535
- **MongoDB**: `objectid`
536
- **SQL Server**: `nchar`, `nvarchar`, `ntext`, `xml`, `uniqueidentifier`
537
538
Each column type has specific options and validation rules depending on the target database system.