or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mddata-operations.mddatabase-adapters.mdentity-modeling.mdindex.mdsql-conditions.md

entity-modeling.mddocs/

0

# Entity Modeling

1

2

Database table and column mapping using TypeScript decorators. HibernateTS provides a comprehensive decorator system that allows you to define your data models with annotations that automatically generate the database schema and handle relationships.

3

4

## Capabilities

5

6

### Table Decorator

7

8

Marks a class as a database table and configures table-level options.

9

10

```typescript { .api }

11

/**

12

* Marks a class as a database table

13

* @param opts - Table configuration options

14

* @returns Class decorator

15

*/

16

function table(opts?: TableOptions): ClassDecorator;

17

18

interface TableOptions {

19

/** Table name (defaults to lowercase class name) */

20

name?: string;

21

/** Database collation (defaults to "utf8mb4_general_ci") */

22

collation?: string;

23

/** Use prototype assignment for instance creation */

24

usePrototypeAssignInsteadOf0ArgsConstructor?: boolean;

25

/** Array of table constraints */

26

constraints?: Constraint<any>[];

27

}

28

29

interface Constraint<TableClass> {

30

/** Constraint type */

31

type: "unique";

32

/** Array of column names */

33

columns: Array<keyof TableClass & string>;

34

}

35

```

36

37

**Usage Examples:**

38

39

```typescript

40

import { table } from "hibernatets";

41

42

// Basic table mapping

43

@table()

44

export class User {

45

// class properties...

46

}

47

48

// Custom table name and options

49

@table({

50

name: "user_accounts",

51

collation: "utf8mb4_unicode_ci",

52

constraints: [{

53

type: "unique",

54

columns: ["email", "username"]

55

}]

56

})

57

export class UserAccount {

58

// class properties...

59

}

60

```

61

62

### Column Decorator

63

64

Marks a property as a database column with customizable options for data types and constraints.

65

66

```typescript { .api }

67

/**

68

* Marks a property as a database column

69

* @param opts - Column configuration options

70

* @returns Property decorator

71

*/

72

function column(opts?: ColumnOptions): PropertyDecorator;

73

74

interface DBColumn {

75

/** Column data type (binding uses primary Key type or BigInt as default) */

76

type?: "text" | "number" | "boolean" | "date" | "binding";

77

/** Column size specification */

78

size?: "small" | "medium" | "large";

79

/** Allow null values */

80

nullable?: boolean;

81

/** Default column value */

82

default?: string;

83

}

84

85

interface ColumnOptions extends DBColumn {

86

/** Custom data transformations */

87

transformations?: Transformations<any, any>;

88

}

89

90

interface Transformations<T, U> {

91

/** Transform data when loading from database to property */

92

loadFromDbToProperty(dbData: U): Promise<T> | T;

93

/** Transform data when saving from property to database */

94

saveFromPropertyToDb(obj: T): Promise<U> | U;

95

}

96

```

97

98

**Usage Examples:**

99

100

```typescript

101

import { table, column } from "hibernatets";

102

103

@table()

104

export class Product {

105

@column()

106

name: string;

107

108

@column({ type: "number", nullable: false })

109

price: number;

110

111

@column({ type: "text", size: "large" })

112

description: string;

113

114

@column({ type: "boolean", default: true })

115

active: boolean;

116

117

@column({ type: "date" })

118

createdAt: Date;

119

120

// Custom transformation example

121

@column({

122

type: "text",

123

transformations: {

124

loadFromDbToProperty(dbData: string): string[] {

125

return JSON.parse(dbData || "[]");

126

},

127

saveFromPropertyToDb(tags: string[]): string {

128

return JSON.stringify(tags);

129

}

130

}

131

})

132

tags: string[];

133

}

134

```

135

136

### Primary Key Decorator

137

138

Marks a property as the primary key with configurable generation strategies.

139

140

```typescript { .api }

141

/**

142

* Marks a property as the primary key

143

* @param options - Primary key configuration options

144

* @returns Property decorator

145

*/

146

function primary(options?: primaryOptions): PropertyDecorator;

147

148

interface primaryOptions extends ColumnOptions {

149

/** Primary key generation strategy */

150

strategy?: "auto-increment" | "custom";

151

}

152

```

153

154

**Usage Examples:**

155

156

```typescript

157

import { table, column, primary } from "hibernatets";

158

159

@table()

160

export class User {

161

// Auto-increment primary key (default)

162

@primary()

163

id: number;

164

165

@column()

166

name: string;

167

}

168

169

@table()

170

export class Document {

171

// Custom primary key strategy

172

@primary({ strategy: "custom" })

173

uuid: string;

174

175

@column()

176

title: string;

177

}

178

```

179

180

### Mapping Decorator

181

182

Defines relationships between entities with support for OneToOne and OneToMany mappings.

183

184

```typescript { .api }

185

/**

186

* Defines relationships between entities

187

* @param type - Mapping type (OneToOne or OneToMany)

188

* @param model - Target entity class or Promise of class

189

* @param key - Foreign key field name or function

190

* @param options - Mapping configuration options

191

* @returns Property decorator

192

*/

193

function mapping(

194

type: Mappings,

195

model: any | Promise<any>,

196

key?: string | ((obj: any) => any),

197

options?: MappingOptions

198

): PropertyDecorator;

199

200

enum Mappings {

201

/** One-to-many relationship (key on target object) */

202

OneToMany = 0,

203

/** One-to-one relationship (key on referencing object) */

204

OneToOne = 1

205

}

206

207

interface MappingOptions extends DBColumn {

208

/** Enable lazy loading for the relationship */

209

lazyLoad?: boolean;

210

}

211

212

interface OneToManyMappingOptions extends MappingOptions {

213

/** Load type configuration (defaults to "list") */

214

loadType?: "list" | "map";

215

}

216

```

217

218

**Usage Examples:**

219

220

```typescript

221

import { table, column, primary, mapping, Mappings } from "hibernatets";

222

223

@table()

224

export class User {

225

@primary()

226

id: number;

227

228

@column()

229

name: string;

230

231

// One-to-many: User has many Posts

232

@mapping(Mappings.OneToMany, Post, "userId")

233

posts: Post[];

234

235

// One-to-one: User has one Profile

236

@mapping(Mappings.OneToOne, Profile, "userId")

237

profile: Profile;

238

}

239

240

@table()

241

export class Post {

242

@primary()

243

id: number;

244

245

@column()

246

title: string;

247

248

@column()

249

userId: number;

250

251

// One-to-one: Post belongs to User

252

@mapping(Mappings.OneToOne, User, "id")

253

user: User;

254

}

255

256

@table()

257

export class Profile {

258

@primary()

259

id: number;

260

261

@column()

262

bio: string;

263

264

@column()

265

userId: number;

266

267

// Lazy loading example

268

@mapping(Mappings.OneToOne, User, "id", { lazyLoad: true })

269

user: User;

270

}

271

```

272

273

### Reference Decorator

274

275

Marks a property as a reference key for relationship mapping.

276

277

```typescript { .api }

278

/**

279

* Marks a property as a reference key

280

* @returns Property decorator

281

*/

282

function reference(): PropertyDecorator;

283

```

284

285

**Usage Examples:**

286

287

```typescript

288

import { table, column, primary, reference, mapping, Mappings } from "hibernatets";

289

290

@table()

291

export class Order {

292

@primary()

293

id: number;

294

295

@column()

296

total: number;

297

298

@reference()

299

customerId: number;

300

301

@mapping(Mappings.OneToOne, Customer, "id")

302

customer: Customer;

303

}

304

305

@table()

306

export class Customer {

307

@primary()

308

id: number;

309

310

@column()

311

name: string;

312

313

@mapping(Mappings.OneToMany, Order, "customerId")

314

orders: Order[];

315

}

316

```

317

318

### Advanced Relationship Examples

319

320

Complex relationship scenarios and advanced mapping patterns.

321

322

```typescript

323

import { table, column, primary, mapping, Mappings } from "hibernatets";

324

325

// Self-referencing relationship

326

@table()

327

export class Category {

328

@primary()

329

id: number;

330

331

@column()

332

name: string;

333

334

@column({ nullable: true })

335

parentId: number;

336

337

// Self-reference: Category has subcategories

338

@mapping(Mappings.OneToMany, Category, "parentId")

339

subcategories: Category[];

340

341

// Parent category

342

@mapping(Mappings.OneToOne, Category, "id")

343

parent: Category;

344

}

345

346

// Many-to-many through junction table

347

@table()

348

export class UserRole {

349

@primary()

350

id: number;

351

352

@column()

353

userId: number;

354

355

@column()

356

roleId: number;

357

358

@mapping(Mappings.OneToOne, User, "id")

359

user: User;

360

361

@mapping(Mappings.OneToOne, Role, "id")

362

role: Role;

363

}

364

365

@table()

366

export class User {

367

@primary()

368

id: number;

369

370

@column()

371

name: string;

372

373

@mapping(Mappings.OneToMany, UserRole, "userId")

374

userRoles: UserRole[];

375

}

376

377

@table()

378

export class Role {

379

@primary()

380

id: number;

381

382

@column()

383

name: string;

384

385

@mapping(Mappings.OneToMany, UserRole, "roleId")

386

userRoles: UserRole[];

387

}

388

```

389

390

### Database Configuration Access

391

392

Accessing the generated database configuration for entities.

393

394

```typescript { .api }

395

/**

396

* Configuration class for entity database mapping

397

*/

398

interface DataBaseConfig<T> {

399

/** Primary key field name */

400

modelPrimary: string;

401

/** Database table name */

402

table: string;

403

/** Column definitions */

404

columns: { [key: string]: ColumnDefinition<any> };

405

/** Table options */

406

options: TableOptions;

407

/** Reference key field name */

408

referenceKey: string;

409

/** Creates new instance of entity */

410

createInstance(): T;

411

}

412

413

interface ColumnDefinition<K> {

414

/** Property name in model */

415

modelName: string;

416

/** Column name in database */

417

dbTableName: string;

418

/** Relationship mapping configuration */

419

mapping?: any;

420

/** Inverse relationship definitions */

421

inverseMappingDef?: any;

422

/** Primary key strategy */

423

primaryType?: "auto-increment" | "custom";

424

/** Column options */

425

opts?: ColumnOptions;

426

}

427

```

428

429

**Usage Examples:**

430

431

```typescript

432

import { getDBConfig } from "hibernatets";

433

434

@table({ name: "users" })

435

export class User {

436

@primary()

437

id: number;

438

439

@column()

440

name: string;

441

}

442

443

// Access database configuration

444

const config = getDBConfig(User);

445

console.log(config.table); // "users"

446

console.log(config.modelPrimary); // "id"

447

console.log(config.columns); // Column definitions

448

```