A TypeScript ORM library inspired by Hibernate for working with MySQL, MariaDB, and PostgreSQL databases using decorators and async/await patterns
npx @tessl/cli install tessl/npm-hibernatets@2.0.0HibernateTS is a comprehensive TypeScript ORM library for MySQL, MariaDB, and PostgreSQL databases. It provides a decorator-based approach to entity mapping, automatic change tracking, and powerful querying capabilities. The library offers seamless database operations with full type safety and relationship management.
npm install hibernatetsimport {
table, column, primary, mapping, reference,
load, save, remove,
SqlCondition, Mappings,
updateDatabase, intercept
} from "hibernatets";For CommonJS:
const {
table, column, primary, mapping, reference,
load, save, remove,
SqlCondition, Mappings,
updateDatabase, intercept
} = require("hibernatets");import { table, column, primary, mapping, Mappings, load, save } from "hibernatets";
// Define entities with decorators
@table()
export class User {
@primary()
id: number;
@column()
name: string;
@column({ type: "boolean" })
active: boolean;
@mapping(Mappings.OneToMany, Post, "userId")
posts: Post[];
}
@table()
export class Post {
@primary()
id: number;
@column()
title: string;
@column()
userId: number;
@mapping(Mappings.OneToOne, User, "id")
user: User;
}
// Basic operations
async function example() {
// Create and save new user
const user = new User();
user.name = "Alice";
user.active = true;
await save(user);
// Load user with related posts
const userWithPosts = await load(User, 1, [], { deep: true });
// Query with SQL conditions
const activeUsers = await load(User,
new SqlCondition().column("active").equals(true)
);
// Update and save changes
user.name = "Alice Smith";
await save(user); // Automatically detects changes
}HibernateTS is built around several key architectural components:
@table, @column, @primary, @mapping) define database schema mappingSqlCondition API for building complex SQL queries with type safetyDatabase table and column mapping using TypeScript decorators. Define your data models with annotations that automatically generate the database schema.
// Class decorators
function table(opts?: TableOptions): ClassDecorator;
// Property decorators
function column(opts?: ColumnOptions): PropertyDecorator;
function primary(options?: PrimaryOptions): PropertyDecorator;
function mapping(type: Mappings, model: any, key?: string, options?: MappingOptions): PropertyDecorator;
function reference(): PropertyDecorator;
interface TableOptions {
name?: string;
collation?: string;
usePrototypeAssignInsteadOf0ArgsConstructor?: boolean;
constraints?: Constraint<any>[];
}Core CRUD operations for loading, saving, and deleting entities with support for relationships and bulk operations.
function load<T>(findClass: ConstructorClass<T>, primaryKeyOrFilter: any, parameters?: any[], options?: LoadOptions<T>): Promise<T | Array<T>>;
function save<T>(saveObjects: T | T[], options?: SaveOptions<T>): Promise<Array<number>>;
function remove<T>(object: any, opts?: DeleteOptions): Promise<number>;
function remove<T>(descriptor: ConstructorClass<T>, primaryId: number | Array<number>, opts?: DeleteOptions): Promise<number>;
interface LoadOptions<T> {
deep?: boolean | string[] | { [key: string]: SqlCondition };
skipFields?: string[];
first?: boolean;
idOnNonDeepOneToOne?: boolean;
withShallowReferences?: boolean;
db?: any;
dontInterceptSetters?: boolean;
}Fluent SQL condition builder for complex queries and filtering with type-safe parameter binding.
class SqlCondition {
static ALL: SqlCondition;
column(columnName: string): SqlCondition;
smaller(): SqlCondition;
greater(): SqlCondition;
equals(value: SqlParameter): SqlCondition;
and(cb: (condition: SqlCondition) => SqlCondition): SqlCondition;
param(value: SqlParameter | Date): SqlCondition;
now(): SqlCondition;
build(params: Array<SqlParameter> | null): string;
checkColumns(classRef: any): void;
}
type SqlParameter = string | number;Database connectivity and adapter implementations for MySQL, MariaDB, and PostgreSQL with connection pooling.
interface DataBaseBase {
sqlquery<T>(cfg: any, queryString: string, params?: any[]): Promise<DatabaseResult>;
selectQuery<T>(queryString: string, params?: any[]): Promise<Array<T>>;
end(): Promise<void>;
}
interface DatabaseResult {
insertId: BigInt;
affectedRows: number;
warningStatus: number;
}
// Database-specific adapters
class MariaDbBase extends DataBaseBase;
class MysqlBase extends DataBaseBase;
class PsqlBase extends DataBaseBase;Database configuration, schema updates, and utility functions for entity management and persistence.
function updateDatabase(modelRootPath: string, opts?: UpdateOpts): Promise<void>;
function intercept<T>(object: T, opts?: InterceptParams): void;
function getId(object: any): number;
function setId(object: any, id: number): void;
function isPersisted(object: any): boolean;
function getDBConfig<T>(obj: any): DataBaseConfig<T>;
interface UpdateOpts {
dbPoolGenerator?: () => DataBaseBase;
modelDb?: DataBaseBase;
}
interface InterceptParams {
interceptArrayFunctions?: boolean;
db?: DataBaseBase;
}Type-safe extended map implementations for managing key-value pairs with automatic JSON serialization and database persistence.
class ExtendedMap<T extends ExtendedMapItem<string, any>, ValueMap> extends Map<T["key"], ExtendedMapItem<T["key"], ValueMap[T["key"]]>> {
getValue<K extends T["key"]>(key: K, fallback?: ValueMap[K]): ValueMap[K];
setValue<K extends T["key"]>(key: K, val: ValueMap[K]): void;
}
@table()
class ExtendedMapItem<K extends string = string, T = any> {
@primary() id: number;
@column() value: string;
@column() key: K;
parsed(): T;
setStringified(value: T): void;
}