从 0.3 升级到 1.0
这是从 0.3.x 版本升级到 1.0 的升级指南。
自动化升级
@typeorm/codemod 包可以自动处理本指南中描述的大部分破坏性变更:
npx @typeorm/codemod v1 src/它会就地更新你的代码——使用 --dry 可以预览改动而不写入文件。该 codemod 会处理导入重命名、API 替换、查找选项语法、依赖升级等。无法自动化的改动会留作 TODO 注释,供人工审阅。
完整的用法和选项请参阅 codemod README。
平台要求
Node.js 20+
最低 JavaScript 目标现在是 ES2023,这要求 Node.js 20 或更高版本。如果你使用的是更旧的 Node.js 版本,请先升级再更新 TypeORM。
非 Node 平台上 Buffer 被替换为 Uint8Array
浏览器端的 Buffer polyfill 已被移除。在非 Node 平台(浏览器、Deno、Bun)上,二进制数据现在表示为 Uint8Array。Node.js 用户不受影响——Node 的 Buffer 继承自 Uint8Array,继续照常工作。
驱动变更
MySQL / MariaDB
移除 connectorPackage 选项
connectorPackage 选项已随对旧版 mysql 客户端的支持一起被移除。现在唯一受支持的数据库客户端是 mysql2,TypeORM 会默认尝试加载它。如果你的项目中用的是 mysql,只需把它换成 mysql2。
legacySpatialSupport 默认值改为 false
legacySpatialSupport 选项现在默认为 false,这意味着 TypeORM 会使用 MySQL 5.7 引入、MySQL 8.0+ 要求的标准兼容 ST_GeomFromText 和 ST_AsText 空间函数。旧版的 GeomFromText 和 AsText 函数已在 MySQL 8.0 中被移除。
如果你运行的是 MySQL 5.6 或更早版本并且依赖空间类型,请显式设置 legacySpatialSupport: true:
new DataSource({
type: "mysql",
legacySpatialSupport: true,
// ...
})移除 width 和 zerofill 列选项
MySQL 8.0.17 弃用了整数类型的显示宽度和 ZEROFILL 属性,MySQL 8.4 则彻底移除了它们。TypeORM 不再支持 width 和 zerofill 列选项。如果你用过这些选项,请把它们从列定义中移除:
// 之前
@Column({ type: "int", width: 9, zerofill: true })
postCode: number
// 之后
@Column({ type: "int" })
postCode: number如果你需要补零的显示格式,请在应用层用 String.prototype.padStart() 处理,或在原生查询中使用 MySQL 的 LPAD() 函数。整数类型的 unsigned 选项 不 受此变更影响。
QueryBuilder.useIndex 签名变更
指定 USE INDEX 查询提示时,QueryBuilder.useIndex() 方法不再接受原生 SQL,而是接受一个索引名或索引名数组。
// 之前
qb.useIndex("index1, `index#2`")
// 之后
qb.useIndex(["index1", "index#2"])SQLite
sqlite3 包已被弃用。请改用 better-sqlite3:
// 之前
new DataSource({
type: "sqlite",
database: "db.sqlite",
})
// 之后
new DataSource({
type: "better-sqlite3",
database: "db.sqlite",
})移除 flags 选项
sqlite3 包接受 C 层的打开标志(OPEN_URI、OPEN_SHAREDCACHE 等)。better-sqlite3 不支持这个——请改用专门的选项:
- 只读模式用
readonly - WAL 日志模式用
enableWAL
busyTimeout 选项更名为 timeout
sqlite3 包用 busyTimeout 配置 SQLite 的忙等待超时。better-sqlite3 改用 timeout(默认:5000ms):
// 之前
new DataSource({
type: "sqlite",
database: "db.sqlite",
busyTimeout: 2000,
})
// 之后
new DataSource({
type: "better-sqlite3",
database: "db.sqlite",
timeout: 2000,
})MongoDB
TypeORM 现在要求 mongodb Node.js 驱动 v7 或更高版本(^7.0.0)。对 mongodb 驱动 v5/v6 的支持已被移除。
移除已弃用的连接选项
以下 MongoDB 连接选项已被移除:
| 被移除的选项 | 处理方式 |
|---|---|
appname |
改用 appName(驼峰命名) |
fsync |
改用 writeConcern: { journal: true } |
j |
改用 writeConcern: { journal: true } |
keepAlive |
移除——自 MongoDB 驱动 v6.0 起始终启用 |
keepAliveInitialDelay |
移除——自 MongoDB 驱动 v6.0 起不可配置 |
ssl |
改用 tls |
sslCA |
改用 tlsCAFile |
sslCRL |
移除——现代驱动中没有替代品 |
sslCert |
改用 tlsCertificateKeyFile |
sslKey |
改用 tlsCertificateKeyFile |
sslPass |
改用 tlsCertificateKeyFilePassword |
sslValidate |
改用 tlsAllowInvalidCertificates(取反) |
useNewUrlParser |
移除——自 MongoDB 驱动 v4.0 起是空操作 |
useUnifiedTopology |
移除——自 MongoDB 驱动 v4.0 起是空操作 |
w |
改用 writeConcern: { w: 1 } |
wtimeout |
改用 writeConcern: { wtimeoutMS: 2500 } |
wtimeoutMS |
改用 writeConcern: { wtimeoutMS: 2500 } |
移除 stats() 方法
stats() 方法已从 MongoQueryRunner、MongoEntityManager 和 MongoRepository 中移除。底层的 collStats 命令在 MongoDB 服务器 6.2 中被弃用,Collection.stats() 方法在 MongoDB 驱动 v7 中被移除。
请改用 $collStats 聚合阶段。注意响应结构不同——count、size、storageSize 这类属性嵌套在 storageStats 下,而不是在顶层。
// 之前
const stats = await mongoRepository.stats()
console.log(stats.count)
console.log(stats.size)
console.log(stats.totalIndexSize)
// 之后——使用 $collStats 聚合阶段
const [stats] = await dataSource.mongoManager
.aggregate(MyEntity, [{ $collStats: { storageStats: {} } }])
.toArray()
console.log(stats.storageStats.count)
console.log(stats.storageStats.size)
console.log(stats.storageStats.totalIndexSize)移除 getMongoRepository 和 getMongoManager 全局函数
已弃用的全局函数 getMongoRepository() 和 getMongoManager() 已被移除。请改用 DataSource 或 EntityManager 上对应的实例方法:
// 之前
import { getMongoManager, getMongoRepository } from "typeorm"
const manager = getMongoManager()
const repository = getMongoRepository(User)
// 之后
const manager = dataSource.mongoManager
const repository = dataSource.getMongoRepository(User)类型
内部的 MongoDB 类型(ObjectId 等)不再从 typeorm 重新导出。请直接从 mongodb 导入它们:
// 之前
import { ObjectId } from "typeorm"
// 之后
import { ObjectId } from "mongodb"MS SQL Server
移除 domain 连接选项
SqlServerConnectionCredentialsOptions 上已弃用的 domain 选项已被移除。请改用 NTLM 类型的 authentication 选项:
// 之前
new DataSource({
type: "mssql",
domain: "MYDOMAIN",
username: "user",
password: "pass",
// ...
})
// 之后
new DataSource({
type: "mssql",
authentication: {
type: "ntlm",
options: {
domain: "MYDOMAIN",
userName: "user",
password: "pass",
},
},
// ...
})options.isolation 和 options.connectionIsolationLevel
SqlServerDataSourceOptions 上的 options.isolation 选项已更名为 options.isolationLevel,因为它本来就不是正确的选项。另外请注意,值格式已从 READ_COMMITTED 改为 READ COMMITTED(下划线换成空格),以匹配 TypeORM 整个代码库中所使用的预期格式。请相应地更新你的 DataSource 选项:
// 之前
new DataSource({
type: "mssql",
options: {
isolation: "READ_COMMITTED",
connectionIsolationLevel: "READ_COMMITTED",
// ...
},
// ...
})
// 之后
new DataSource({
type: "mssql",
options: {
isolationLevel: "READ COMMITTED",
connectionIsolationLevel: "READ COMMITTED",
// ...
},
// ...
})Oracle
LegacyOracleNamingStrategy 不再从 TypeORM 主包中导出。如果你仍然需要它,可以从 @typeorm/legacy-naming-strategies 导入。
// 之前
import { LegacyOracleNamingStrategy } from "typeorm"
// 之后
import { LegacyOracleNamingStrategy } from "@typeorm/legacy-naming-strategies"SAP HANA
若干已弃用的 SAP HANA 连接别名已被移除。
hanaClientDriver已移除。请使用driver。pool.max已移除。请使用pool.maxConnectedOrPooled。pool.requestTimeout已移除。请使用pool.maxWaitTimeoutIfPoolExhausted。pool.idleTimeout已移除。请使用pool.maxPooledIdleTime(秒)。pool.min、pool.maxWaitingRequests和pool.checkInterval已移除,没有替代品。
另外请注意连接池配置的默认行为变化:
pool.maxPooledIdleTime现在默认为30秒,不再回退到pool.idleTimeout。pool.maxWaitTimeoutIfPoolExhausted现在默认为0,不再回退到pool.requestTimeout。
Expo
最低受支持的 Expo SDK 版本是 52,它带来了现代的异步 SQLite API。TypeORM 现在会自动加载 expo-sqlite,因此 driver 选项不再是必需的:
// 之前
new DataSource({
type: "expo",
driver: require("expo-sqlite"),
database: "db.sqlite",
})
// 之后
new DataSource({
type: "expo",
database: "db.sqlite",
})Redis(缓存)
RedisQueryResultCache 中对旧版(v3)Redis 客户端的支持已移除。请升级到 Redis 客户端 v4 或更高版本(redis、ioredis):
// 之前——redis v3
import { createClient } from "redis"
const client = createClient()
// 之后——redis v4+
import { createClient } from "redis"
const client = createClient()
await client.connect()数据源
Connection → DataSource
DataSource 在 v0.3 中取代了 Connection。向后兼容的别名现在已被移除:
// 之前
import { Connection, ConnectionOptions } from "typeorm"
const connection = await createConnection(options)
await connection.close()
// 之后
import { DataSource, DataSourceOptions } from "typeorm"
const dataSource = new DataSource(options)
await dataSource.initialize()
await dataSource.destroy()以下重命名全局适用:
| 之前 | 之后 |
|---|---|
Connection |
DataSource |
ConnectionOptions |
DataSourceOptions |
BaseConnectionOptions |
BaseDataSourceOptions |
MysqlConnectionOptions |
MysqlDataSourceOptions |
| (所有驱动都遵循同样的模式) | |
connection.connect() |
dataSource.initialize() |
connection.close() |
dataSource.destroy() |
connection.isConnected |
dataSource.isInitialized |
移除 name 属性
DataSource 和 BaseDataSourceOptions 上已弃用的 name 属性已被移除。命名连接在 v0.3 移除 ConnectionManager 时就已被弃用。如果你曾用 name 来标识连接,请改为直接管理你的 DataSource 实例。
注意:读取 dataSource.name 的代码现在会得到 undefined 而不是 "default"。如果你在日志或多租户逻辑中使用了这个值,请相应更新。
各类中的 .connection 属性现在是 .dataSource
Driver、QueryRunner、EntityManager、QueryBuilder、EntityMetadata 和 *Event 类中的 connection 属性已更名为 dataSource。对 EntityManager 而言,这一变更在 0.3 中就已公布,但当时并未真正实现。为便于过渡,这里加了一个已弃用的 getter,它返回与 dataSource 相同的值。
杂项
ConnectionManager 类已被移除。如果你曾用它管理多个连接,请改为直接创建并管理你的 DataSource 实例。
ConnectionOptionsReader 也被简化了:all() 更名为 get()(以数组形式返回所有配置),旧的 get(name) 和 has(name) 方法已被移除。它现在会在 process.cwd() 而不是应用路径中搜索 ormconfig 文件。你可以用 root 选项改变搜索位置。
const reader = new ConnectionOptionsReader({ root: "/path/to/config/" })
// 当你的 ormconfig 只有一个数据源时
const [options] = await reader.get()
// 当你需要从多个数据源中取某个特定配置时
const allOptions = await reader.get()
const postgresOptions = allOptions.find((o) => o.type === "postgres")移除全局便捷函数
以下已弃用的全局函数已被移除:
createConnection/createConnectionsgetConnectiongetConnectionManagergetConnectionOptionsgetManagergetSqljsManagergetRepositorygetTreeRepositorycreateQueryBuilder
请使用你的 DataSource 实例上的等价方法:
// 之前
const repo = getRepository(User)
const qb = createQueryBuilder("user")
// 之后
const repo = dataSource.getRepository(User)
const qb = dataSource.createQueryBuilder("user")移除通过环境变量配置的方式
已弃用的 ConnectionOptionsEnvReader 类,以及通过 TYPEORM_CONNECTION、TYPEORM_URL 和其他 TYPEORM_* 环境变量配置连接的能力已被移除。ormconfig.env 文件格式也不再受支持。TypeORM 不再自动加载 .env 文件,也不再依赖 dotenv。
请改用 TypeScript 或 JavaScript 配置文件:
// ormconfig.ts
export default {
type: process.env.DB_TYPE,
url: process.env.DB_URL,
// ...
}行为变更
invalidWhereValuesBehavior 默认值改为 throw
这是一项重大的行为变更,可能在运行时破坏现有应用。
where 条件中 null 与 undefined 值的默认行为发生了变化。此前,null 和 undefined 值会被静默忽略(该属性被跳过)。现在,两者默认都会抛出错误。
这一变更避免了那些隐蔽的 bug——比如 findBy({ id: undefined }) 会静默返回所有行而不是失败。
// v0.3:静默返回所有帖子(null 被忽略)
// v1.0:抛出 TypeORMError
await repository.find({ where: { text: null } })
// v0.3:静默返回所有帖子(undefined 被忽略)
// v1.0:抛出 TypeORMError
await repository.find({ where: { text: undefined } })要匹配 null 值,请使用 IsNull() 运算符:
import { IsNull } from "typeorm"
await repository.find({ where: { text: IsNull() } })要恢复之前的行为,请在数据源选项中设置 invalidWhereValuesBehavior:
new DataSource({
// ...
invalidWhereValuesBehavior: {
null: "ignore",
undefined: "ignore",
},
})该设置守护所有高层 API——查找操作、repository/manager 的变更方法,以及 queryBuilder.setFindOptions()(唯一受影响的 QueryBuilder 方法)。QueryBuilder 的其余方法(.where()、.andWhere()、.orWhere())不受影响——null 和 undefined 值会原样透传。完整细节参见 null 与 undefined 的处理。
哈希
在 TypeORM v1 中,用于哈希的 SHA1 算法会直接作用于输入。在之前的版本(v0.3)中,输入会先用 encodeURIComponent 编码。
如果你使用 TypeORM 的查询结果缓存,升级后已有的缓存条目会失效,因为哈希函数产生的输出不同。缓存会自动重建——你可能会看到缓存未命中短暂增加。
如果你的表名和列名包含特殊字符,可以使用 @typeorm/legacy-naming-strategies 来避免数据库发生变化:
import { NamingStrategyV03 } from "@typeorm/legacy-naming-strategies"
const dataSource = new DataSource({
...
namingStrategy: new NamingStrategyV03(),
...
})Glob 模式
Glob 模式(用于实体/迁移文件的发现)现在由 tinyglobby 而不是 glob 处理。对大多数项目来说这是无缝替换。
带非空外键的 orphanedRowAction: "nullify"
当 orphanedRowAction 为 "nullify"(默认值)且外键列不可空时,孤儿子对象现在会被删除,而不是抛出数据库约束冲突。此前,TypeORM 会尝试把外键设为 null,这在非空列上会失败。
这仅在关系已加载到实体实例上时适用。TypeORM 不会自动加载关系——它只遍历对象上已经填充的关系值。为确保孤儿子对象被处理,请在调用 remove 或 save 之前先加载该关系:
const parent = await manager.findOne(Parent, {
where: { id: 1 },
relations: { children: true },
})
await manager.remove(parent)如果关系未被加载(即该属性为 undefined),TypeORM 不会检测或删除孤儿子对象,这可能导致外键约束冲突。
如果你依赖那个错误来防止意外删除子对象,请在关系上设置 orphanedRowAction: "disable" 以保留旧行为。
级联删除现在对一对多关系生效
在一对多关系上使用 cascade: true 或 cascade: ["remove"] 时调用 manager.remove(entity),现在会正确地在删除父对象之前先删除子实体。此前子实体不会被级联删除,导致 DELETE 因外键约束冲突而失败。此外,级联操作现在限定在匹配的操作类型范围内——例如 save() 只遵循 insert/update 级联,不再遍历仅 remove 的关系。
多对多中间表行与软删除实体
对带多对多关系的软删除实体调用 recover() 不再抛出重复键冲突。softRemove 不会触碰中间表行,但 TypeORM 此前在为恢复而加载实体时看不到它们,导致它尝试重复插入。
副作用是,save() 期间的多对多中间表比较现在会包含软删除的关联实体。如果你显式设置了一个排除某软删除实体的关系数组,它的中间表行会被移除:
// photo2 被独立软删除了,但它的中间表行仍然存在
user.manyToManyPhotos = [photo1] // photo2 被排除
await manager.save(user) // photo2 的中间表行现在被移除了这仅在关系属性被显式设置时适用。如果它是 undefined,则不会执行比较,中间表行保持原样。
日志记录器
FileLogger 让底层平台(例如 NodeJS)处理路径,而不是相对于应用根目录来确定路径。如果应用不是从其根文件夹启动的,你可以提供一个绝对路径(或相对于 process.cwd() 的路径):
const dataSource = new DataSource({
logger: new FileLogger("all", { logPath: "/path/to/file.log" }),
})列
移除 readonly 选项
已弃用的 readonly 列选项已被移除。请改用 update 选项——注意它取的是 相反 的值:
// 之前
@Column({ readonly: true })
authorName: string
// 之后
@Column({ update: false })
authorName: string移除 ColumnNumericOptions 上的 unsigned
ColumnNumericOptions 上已弃用的 unsigned 属性(用于 decimal/float 列类型重载,如 @Column("decimal", { unsigned: true }))已被移除,因为 MySQL 已弃用非整数数值类型的 UNSIGNED。整数类型的 ColumnOptions 上的 unsigned 选项 不 受影响。
关系
nullable: false 现在使用 INNER JOIN
标记为 nullable: false 的关系,在通过 relations、急加载或查找选项加载时,现在使用 INNER JOIN 而不是 LEFT JOIN。这仅适用于持有连接列的关系类型(ManyToOne 和拥有方 OneToOne)。
这在语义上是正确的,因为非空外键保证了关联实体必然存在,并让数据库优化器能产生更高效的查询计划。
潜在破坏性: 如果你的数据库中包含违反 NOT NULL 约束的行(例如孤儿外键,或设置了 nullable: false 但该列在数据库中实际可空),这些行会被排除在查询结果之外。请验证你的数据完整性,或在需要时把关系改为 nullable: true。
// INNER JOIN——关联实体必然存在
@ManyToOne(() => User, { nullable: false })
author: User
// LEFT JOIN——关联实体可能不存在(默认)
@ManyToOne(() => User)
optionalEditor: UserOneToMany、ManyToMany 和反向 OneToOne 关系无论 nullable 设置如何都始终使用 LEFT JOIN,因为这些关系类型在当前表上没有连接列。
软删除例外: 如果关联实体有 @DeleteDateColumn,即使是 nullable: false 的关系也会使用 LEFT JOIN(除非设置了 withDeleted: true)。这能防止软删除的关联实体把它们的父行过滤掉。
Repository
findOneById
已弃用的 findOneById 方法已从 EntityManager、Repository、BaseEntity、MongoEntityManager 和 MongoRepository 中移除。请改用 findOneBy:
// 之前
const user = await manager.findOneById(User, 1)
const user = await repository.findOneById(1)
const user = await User.findOneById(1)
// 之后
const user = await manager.findOneBy(User, { id: 1 })
const user = await repository.findOneBy({ id: 1 })
const user = await User.findOneBy({ id: 1 })对带 @ObjectIdColumn() 的 MongoDB 实体,findOneBy 的用法相同——TypeORM 会自动把属性名转换为 _id。
移除 findByIds
已弃用的 findByIds 方法已从 EntityManager、Repository 和 BaseEntity 中移除。请改用带 In 运算符的 findBy:
// 之前
const users = await repository.findByIds([1, 2, 3])
// 之后
import { In } from "typeorm"
const users = await repository.findBy({ id: In([1, 2, 3]) })exist 更名为 exists
已弃用的 Repository.exist() 方法已被移除。请改用 exists()——行为完全一致:
// 之前
const hasUsers = await userRepository.exist({ where: { isActive: true } })
// 之后
const hasUsers = await userRepository.exists({ where: { isActive: true } })移除 AbstractRepository、@EntityRepository 和 getCustomRepository
AbstractRepository 类、@EntityRepository 装饰器和 getCustomRepository() 方法已被移除。它们在 v0.3 中就已弃用,推荐使用 Repository.extend():
// 之前
@EntityRepository(User)
class UserRepository extends AbstractRepository<User> {
findByName(name: string) {
return this.repository.findOneBy({ name })
}
}
const userRepo = dataSource.getCustomRepository(UserRepository)
// 之后
const UserRepository = dataSource.getRepository(User).extend({
findByName(name: string) {
return this.findOneBy({ name })
},
})以下错误类也已被移除:CustomRepositoryDoesNotHaveEntityError、CustomRepositoryCannotInheritRepositoryError、CustomRepositoryNotFoundError。
移除 @RelationCount 装饰器和 loadRelationCountAndMap
@RelationCount 装饰器和 SelectQueryBuilder.loadRelationCountAndMap() 方法已被移除。请改用 @VirtualColumn 或在 query builder 中使用子查询:
// 之前
@RelationCount((post: Post) => post.categories)
categoryCount: number
// 之后——使用带子查询的 @VirtualColumn
// 把中间表名和列名替换为与你的结构匹配的名字
@VirtualColumn({
query: (alias) =>
`SELECT COUNT(*) FROM post_categories_category WHERE postId = ${alias}.id`,
})
categoryCount: number查找选项
移除 join 选项
FindOneOptions 和 FindManyOptions 上已弃用的 join 属性已被移除,JoinOptions 接口也一并移除。
leftJoinAndSelect → relations
如果你曾使用 leftJoinAndSelect,请把它替换为 relations 对象语法——relations 总是执行带选取的 LEFT JOIN,两者等价:
// 之前
const posts = await repository.find({
join: {
alias: "post",
leftJoinAndSelect: {
categories: "post.categories",
author: "post.author",
},
},
})
// 之后
const posts = await repository.find({
relations: { categories: true, author: true },
})所有其他连接类型 → QueryBuilder
relations 选项只支持带选取的 LEFT JOIN。如果你曾使用 innerJoinAndSelect、innerJoin 或 leftJoin(不选取),请改用 QueryBuilder API:
// 之前——innerJoinAndSelect
const posts = await repository.find({
join: {
alias: "post",
innerJoinAndSelect: {
categories: "post.categories",
},
},
})
// 之后——QueryBuilder 配合 innerJoinAndSelect
const posts = await repository
.createQueryBuilder("post")
.innerJoinAndSelect("post.categories", "categories")
.getMany()
// 之前——leftJoin(不选取)
const posts = await repository.find({
join: {
alias: "post",
leftJoin: {
categories: "post.categories",
},
},
where: { categories: { isRemoved: false } },
})
// 之后——QueryBuilder 配合 leftJoin
const posts = await repository
.createQueryBuilder("post")
.leftJoin("post.categories", "categories")
.where("categories.isRemoved = :isRemoved", { isRemoved: false })
.getMany()这一区别在实践中很重要。例如,PostgreSQL 和 CockroachDB 不允许在外连接的可空一侧使用 FOR UPDATE,因此把锁与连接关系结合的查询可能需要 INNER JOIN:
// 之前——innerJoinAndSelect + lock
const post = await repository.findOne({
join: {
alias: "post",
innerJoinAndSelect: {
categories: "post.categories",
},
},
lock: { mode: "pessimistic_write", tables: ["category"] },
})
// 之后——QueryBuilder 配合 innerJoinAndSelect + lock
const post = await repository
.createQueryBuilder("post")
.innerJoinAndSelect("post.categories", "categories")
.setLock("pessimistic_write", undefined, ["categories"])
.getOne()带嵌套关系的锁 → QueryBuilder
relations 选项无法与针对被连接表的悲观锁一起使用,因为 relations 总是使用 LEFT JOIN,而 PostgreSQL/CockroachDB 拒绝在外连接的可空一侧使用 FOR UPDATE。请改用 QueryBuilder 配合 innerJoinAndSelect:
// 之前——通过查找选项使用嵌套关系 + lock
const post = await repository.findOne({
where: { id: 1 },
join: {
alias: "post",
innerJoinAndSelect: {
categories: "post.categories",
images: "categories.images",
},
},
lock: { mode: "pessimistic_write", tables: ["images"] },
})
// 之后——QueryBuilder 配合 innerJoinAndSelect + lock
const post = await repository
.createQueryBuilder("post")
.innerJoinAndSelect("post.categories", "categories")
.innerJoinAndSelect("categories.images", "images")
.where("post.id = :id", { id: 1 })
.setLock("pessimistic_write", undefined, ["images"])
.getOne()注意,锁定主表仍然可以与 relations 一起使用——只有锁定被连接的表才需要 QueryBuilder 配合内连接。
移除基于字符串的 select
select 查找选项中已弃用的字符串数组语法已被移除。请改用对象语法:
// 之前
const users = await repository.find({
select: ["id", "name"],
})
// 之后
const users = await repository.find({
select: { id: true, name: true },
})被移除的类型是 FindOptionsSelectByString。
移除基于字符串的 relations
relations 查找选项中已弃用的字符串数组语法已被移除。请改用对象语法:
// 之前
const users = await repository.find({
relations: ["profile", "posts"],
})
// 之后
const users = await repository.find({
relations: { profile: true, posts: true },
})被移除的类型是 FindOptionsRelationByString。
QueryBuilder
移除 printSql
query builder 上的 printSql() 方法已被移除。它是多余的,因为启用查询日志后,所有已执行的查询都已经通过所配置的日志记录器自动记录。请改用 getSql() 或 getQueryAndParameters() 来查看生成的 SQL:
// 之前
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.printSql()
.getMany()
// 之后——执行前查看 SQL
const qb = dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
console.log(qb.getSql())
// 或者:const [sql, params] = qb.getQueryAndParameters()
const users = await qb.getMany()要自动记录所有已执行的查询,请在你的 DataSource 中启用查询日志:
new DataSource({
// ...
logging: ["query"],
})移除 onConflict
InsertQueryBuilder 上的 onConflict() 方法已被移除。它接受原生 SQL 字符串,而那些字符串是驱动专属且容易出错的。请改用 orIgnore() 或 orUpdate():
// 之前
await dataSource
.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.onConflict(`("id") DO NOTHING`)
.execute()
// 之后
await dataSource
.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.orIgnore()
.execute()
// 之前
await dataSource
.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.onConflict(`("id") DO UPDATE SET "title" = :title`)
.setParameter("title", post.title)
.execute()
// 之后
await dataSource
.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.orUpdate(["title"], ["id"])
.execute()移除 orUpdate 的对象重载
接受 { columns?, overwrite?, conflict_target? } 的对象式 orUpdate() 重载已被移除。请改用基于数组的签名:
// 之前
.orUpdate({ conflict_target: ["date"], overwrite: ["title"] })
// 之后
.orUpdate(["title"], ["date"])移除 setNativeParameters
// 之前
qb.setNativeParameters({ key: "value" })
// 之后
qb.setParameters({ key: "value" })移除 WhereExpression 类型别名
// 之前
import { WhereExpression } from "typeorm"
// 之后
import { WhereExpressionBuilder } from "typeorm"移除 replacePropertyNames
QueryBuilder 上已弃用的受保护方法 replacePropertyNames() 已被移除。如果你在自定义子类中重写了它,该重写不会再被调用。
移除已弃用的锁模式
// 之前
.setLock("pessimistic_partial_write")
// 之后
.setLock("pessimistic_write")
.setOnLocked("skip_locked")
// 之前
.setLock("pessimistic_write_or_fail")
// 之后
.setLock("pessimistic_write")
.setOnLocked("nowait")查找选项同理:
// 之前
{ lock: { mode: "pessimistic_partial_write" } }
// 之后
{ lock: { mode: "pessimistic_write", onLocked: "skip_locked" } }
// 之前
{ lock: { mode: "pessimistic_write_or_fail" } }
// 之后
{ lock: { mode: "pessimistic_write", onLocked: "nowait" } }迁移
移除 getAllMigrations
已弃用的 getAllMigrations() 方法已从 MigrationExecutor 中移除。请改用 getPendingMigrations() 或 getExecutedMigrations(),或直接访问 dataSource.migrations 来获取已注册的迁移类列表:
// 之前
const migrations = await migrationExecutor.getAllMigrations()
// 之后——取决于你需要什么
const pending = await migrationExecutor.getPendingMigrations()
const executed = await migrationExecutor.getExecutedMigrations()
const registered = dataSource.migrations移除 QueryRunner.loadedTables 和 loadedViews
// 之前
const tables = queryRunner.loadedTables
const views = queryRunner.loadedViews
// 之后
const tables = await queryRunner.getTables()
const views = await queryRunner.getViews()注意:替代品是异步方法,不是同步属性。
容器系统
已弃用的 IoC 容器集成已被移除:useContainer()、getFromContainer()、ContainerInterface、ContainedType 和 UseContainerOptions。
TypeORM 不再有内置的 IoC 容器支持。typeorm-typedi-extensions 和 typeorm-routing-controllers-extensions 包也不再兼容。下面几节介绍如何根据你的配置进行迁移。
带依赖的订阅者与迁移
TypeORM 始终在内部使用无参构造函数实例化订阅者和迁移,因此你无法传入预先构建好的实例。如果你的迁移需要访问服务,请在迁移内部使用 DataSource(可通过 queryRunner.dataSource 获取):
// 之前
import { useContainer } from "typeorm"
import { Container } from "typedi"
useContainer(Container)
// 之后——在迁移内部通过 DataSource 访问依赖
export class MyMigration1234 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
const repo = queryRunner.dataSource.getRepository(User)
// ...
}
}访问 repository 与 entity manager
如果你之前用 typeorm-typedi-extensions 把 EntityManager 或 repository 注入到服务中,请改为直接使用 DataSource:
// 之前(配合 typeorm-typedi-extensions)
import { InjectManager, InjectRepository } from "typeorm-typedi-extensions"
class UserService {
@InjectManager()
private manager: EntityManager
@InjectRepository(User)
private userRepository: Repository<User>
}
// 之后——从 DataSource 实例获取
class UserService {
private manager: EntityManager
private userRepository: Repository<User>
constructor(dataSource: DataSource) {
this.manager = dataSource.manager
this.userRepository = dataSource.getRepository(User)
}
}与 DI 框架一起使用
如果你使用 DI 框架,请把 DataSource(或它的 repository)注册为容器中的提供者:
// typedi 示例
import { DataSource } from "typeorm"
import { Container } from "typedi"
const dataSource = new DataSource({/* ... */})
await dataSource.initialize()
Container.set(DataSource, dataSource)
Container.set("UserRepository", dataSource.getRepository(User))NestJS
NestJS 用户不受影响——@nestjs/typeorm 包有自己的集成,并不依赖 TypeORM 已被移除的容器系统。不过,@nestjs/typeorm v10 和 v11.0.0 会尝试注册已被移除的 Connection 类,并在启动时崩溃。要兼容 TypeORM v1,请升级到 @nestjs/typeorm v11.0.1 或更高版本。@typeorm/codemod 工具会自动为你提升版本。
其他内部移除
以下内部 API 已被移除。只有当你在构建自定义驱动、扩展 QueryBuilder 或使用底层元数据 API 时才会受影响:
| 被移除的 | 替代品 |
|---|---|
EntityMetadata.createPropertyPath()(静态) |
已移除,没有公开替代品 |
EntityMetadata.getValueMap() 的 options 参数 |
移除第三个参数——它从未生效 |
DriverUtils.buildColumnAlias() |
使用 DriverUtils.buildAlias() |
Broadcaster.broadcastLoadEventsForAll() |
没有替代品——请使用各个事件订阅者 |
QueryExpressionMap.nativeParameters |
使用 QueryExpressionMap.parameters |
RdbmsSchemaBuilder.renameTables() |
已移除 |
This is the upgrading guide from version 0.3.x to 1.0.
Automated upgrade
The @typeorm/codemod package can automate most of the breaking changes described in this guide:
npx @typeorm/codemod v1 src/This will update your code in place — use --dry to preview changes without writing. The codemod handles import renames, API replacements, find option syntax, dependency upgrades, and more. Changes that cannot be automated are left as TODO comments for manual review.
See the codemod README for full usage and options.
Platform requirements
Node.js 20+
The minimum JavaScript target is now ES2023, which requires Node.js 20 or later. If you are using an older Node.js version, upgrade before updating TypeORM.
Buffer replaced with Uint8Array on non-Node platforms
The browser Buffer polyfill has been removed. On non-Node platforms (browser, Deno, Bun), binary data is now represented as Uint8Array. Node.js users are not affected — Node's Buffer extends Uint8Array and continues to work as before.
Driver changes
MySQL / MariaDB
connectorPackage option removed
The connectorPackage option was removed, together with the support for the old mysql client. The only database client supported is now mysql2, which TypeORM will try to load by default. If you were using mysql in your project, simply replace it with mysql2.
legacySpatialSupport default changed to false
The legacySpatialSupport option now defaults to false, meaning TypeORM uses the standard-compliant ST_GeomFromText and ST_AsText spatial functions introduced in MySQL 5.7 and required by MySQL 8.0+. The legacy GeomFromText and AsText functions were removed in MySQL 8.0.
If you are running MySQL 5.6 or earlier and rely on spatial types, set legacySpatialSupport: true explicitly:
new DataSource({
type: "mysql",
legacySpatialSupport: true,
// ...
})width and zerofill column options removed
MySQL 8.0.17 deprecated display width for integer types and the ZEROFILL attribute, and MySQL 8.4 removed them entirely. TypeORM no longer supports the width and zerofill column options. If you were using these options, remove them from your column definitions:
// Before
@Column({ type: "int", width: 9, zerofill: true })
postCode: number
// After
@Column({ type: "int" })
postCode: numberIf you need zero-padded display formatting, handle it in your application layer using String.prototype.padStart() or the MySQL LPAD() function in a raw query. The unsigned option for integer types is not affected by this change.
QueryBuilder.useIndex signature changed
When specifying the USE INDEX query hint, the QueryBuilder.useIndex() method no longer accepts raw SQL, but either an index name or an array of index names.
// Before
qb.useIndex("index1, `index#2`")
// After
qb.useIndex(["index1", "index#2"])SQLite
The sqlite3 package has been dropped. Use better-sqlite3 instead:
// Before
new DataSource({
type: "sqlite",
database: "db.sqlite",
})
// After
new DataSource({
type: "better-sqlite3",
database: "db.sqlite",
})flags option removed
The sqlite3 package accepted C-level open flags (OPEN_URI, OPEN_SHAREDCACHE, etc.). better-sqlite3 does not support this — use the dedicated options instead:
readonlyfor read-only modeenableWALfor WAL journal mode
busyTimeout option renamed to timeout
The sqlite3 package used busyTimeout to configure SQLite's busy timeout. better-sqlite3 uses timeout instead (default: 5000ms):
// Before
new DataSource({
type: "sqlite",
database: "db.sqlite",
busyTimeout: 2000,
})
// After
new DataSource({
type: "better-sqlite3",
database: "db.sqlite",
timeout: 2000,
})MongoDB
TypeORM now requires the mongodb Node.js driver v7 or later (^7.0.0). Support for the mongodb driver v5/v6 has been dropped.
Deprecated connection options removed
The following MongoDB connection options have been removed:
| Removed option | Action |
|---|---|
appname |
Use appName (camelCase) instead |
fsync |
Use writeConcern: { journal: true } instead |
j |
Use writeConcern: { journal: true } instead |
keepAlive |
Remove — always enabled since MongoDB Driver v6.0 |
keepAliveInitialDelay |
Remove — not configurable since MongoDB Driver v6.0 |
ssl |
Use tls instead |
sslCA |
Use tlsCAFile instead |
sslCRL |
Remove — no replacement in modern driver |
sslCert |
Use tlsCertificateKeyFile instead |
sslKey |
Use tlsCertificateKeyFile instead |
sslPass |
Use tlsCertificateKeyFilePassword instead |
sslValidate |
Use tlsAllowInvalidCertificates (inverted) instead |
useNewUrlParser |
Remove — no-op since MongoDB Driver v4.0 |
useUnifiedTopology |
Remove — no-op since MongoDB Driver v4.0 |
w |
Use writeConcern: { w: 1 } instead |
wtimeout |
Use writeConcern: { wtimeoutMS: 2500 } instead |
wtimeoutMS |
Use writeConcern: { wtimeoutMS: 2500 } instead |
stats() method removed
The stats() method has been removed from MongoQueryRunner, MongoEntityManager, and MongoRepository. The underlying collStats command was deprecated in MongoDB server 6.2 and the Collection.stats() method was removed in MongoDB Driver v7.
Use the $collStats aggregation stage instead. Note that the response shape is different — properties like count, size, and storageSize are nested under storageStats rather than at the top level.
// Before
const stats = await mongoRepository.stats()
console.log(stats.count)
console.log(stats.size)
console.log(stats.totalIndexSize)
// After — use $collStats aggregation stage
const [stats] = await dataSource.mongoManager
.aggregate(MyEntity, [{ $collStats: { storageStats: {} } }])
.toArray()
console.log(stats.storageStats.count)
console.log(stats.storageStats.size)
console.log(stats.storageStats.totalIndexSize)getMongoRepository and getMongoManager globals removed
The deprecated global functions getMongoRepository() and getMongoManager() have been removed. Use the corresponding instance methods on DataSource or EntityManager instead:
// Before
import { getMongoManager, getMongoRepository } from "typeorm"
const manager = getMongoManager()
const repository = getMongoRepository(User)
// After
const manager = dataSource.mongoManager
const repository = dataSource.getMongoRepository(User)Types
The internal MongoDB types (ObjectId, etc.) are no longer re-exported from typeorm. Import them directly from mongodb:
// Before
import { ObjectId } from "typeorm"
// After
import { ObjectId } from "mongodb"MS SQL Server
domain connection option removed
The deprecated domain option on SqlServerConnectionCredentialsOptions has been removed. Use the authentication option with NTLM type instead:
// Before
new DataSource({
type: "mssql",
domain: "MYDOMAIN",
username: "user",
password: "pass",
// ...
})
// After
new DataSource({
type: "mssql",
authentication: {
type: "ntlm",
options: {
domain: "MYDOMAIN",
userName: "user",
password: "pass",
},
},
// ...
})options.isolation and options.connectionIsolationLevel
The options.isolation option on SqlServerDataSourceOptions was renamed to options.isolationLevel as was not the correct option in the first place. Also note that the value format has changed from READ_COMMITTED to READ COMMITTED (underscore replaced with space) to match the expected format used by the TypeORM throughout the codebase. Update your DataSource options accordingly:
// Before
new DataSource({
type: "mssql",
options: {
isolation: "READ_COMMITTED",
connectionIsolationLevel: "READ_COMMITTED",
// ...
},
// ...
})
// After
new DataSource({
type: "mssql",
options: {
isolationLevel: "READ COMMITTED",
connectionIsolationLevel: "READ COMMITTED",
// ...
},
// ...
})Oracle
The LegacyOracleNamingStrategy is no longer exported in the main TypeORM package. You can import it from @typeorm/legacy-naming-strategies if you still need it.
// Before
import { LegacyOracleNamingStrategy } from "typeorm"
// After
import { LegacyOracleNamingStrategy } from "@typeorm/legacy-naming-strategies"SAP HANA
Several deprecated SAP HANA connection aliases were removed.
hanaClientDriverwas removed. Usedriver.pool.maxwas removed. Usepool.maxConnectedOrPooled.pool.requestTimeoutwas removed. Usepool.maxWaitTimeoutIfPoolExhausted.pool.idleTimeoutwas removed. Usepool.maxPooledIdleTime(seconds).pool.min,pool.maxWaitingRequests, andpool.checkIntervalwere removed with no replacement.
Also note the default behavior changes in pool configuration:
pool.maxPooledIdleTimenow defaults to30seconds and no longer falls back topool.idleTimeout.pool.maxWaitTimeoutIfPoolExhaustednow defaults to0and no longer falls back topool.requestTimeout.
Expo
The minimum supported Expo SDK version is 52, which comes with a modern async SQLite API. TypeORM now loads expo-sqlite automatically, so the driver option is no longer required:
// Before
new DataSource({
type: "expo",
driver: require("expo-sqlite"),
database: "db.sqlite",
})
// After
new DataSource({
type: "expo",
database: "db.sqlite",
})Redis (cache)
Removed support for legacy (v3) Redis clients in RedisQueryResultCache. Upgrade to Redis client v4 or later (redis, ioredis):
// Before — redis v3
import { createClient } from "redis"
const client = createClient()
// After — redis v4+
import { createClient } from "redis"
const client = createClient()
await client.connect()Data Source
Connection → DataSource
DataSource replaced Connection in v0.3. The backward-compatible alias has now been removed:
// Before
import { Connection, ConnectionOptions } from "typeorm"
const connection = await createConnection(options)
await connection.close()
// After
import { DataSource, DataSourceOptions } from "typeorm"
const dataSource = new DataSource(options)
await dataSource.initialize()
await dataSource.destroy()The following renames apply throughout:
| Before | After |
|---|---|
Connection |
DataSource |
ConnectionOptions |
DataSourceOptions |
BaseConnectionOptions |
BaseDataSourceOptions |
MysqlConnectionOptions |
MysqlDataSourceOptions |
| (same pattern for all drivers) | |
connection.connect() |
dataSource.initialize() |
connection.close() |
dataSource.destroy() |
connection.isConnected |
dataSource.isInitialized |
name property removed
The deprecated name property on DataSource and BaseDataSourceOptions has been removed. Named connections were deprecated in v0.3 when ConnectionManager was removed. If you were using name to identify connections, manage your DataSource instances directly instead.
Note: code that reads dataSource.name will now receive undefined instead of "default". If you use this value in logging or multi-tenancy logic, update accordingly.
.connection property in various classes is now .dataSource
The connection property in the Driver, QueryRunner, EntityManager, QueryBuilder, EntityMetadata and *Event classes was renamed to dataSource. For EntityManager, this change was announced in 0.3, but it was not actually implemented. To ease the transition, a deprecated getter was added that returns the same value as dataSource.
Miscellaneous
The ConnectionManager class has been removed. If you were using it to manage multiple connections, create and manage your DataSource instances directly instead.
ConnectionOptionsReader has also been simplified: all() was renamed to get() (returning all configs as an array), and the old get(name) and has(name) methods were removed. It will now search for the ormconfig file in process.cwd() instead of the application path. You can use the root option to change the search location.
const reader = new ConnectionOptionsReader({ root: "/path/to/config/" })
// when your ormconfig has a single data source
const [options] = await reader.get()
// when you need a specific config from multiple data sources
const allOptions = await reader.get()
const postgresOptions = allOptions.find((o) => o.type === "postgres")Global convenience functions removed
The following deprecated global functions have been removed:
createConnection/createConnectionsgetConnectiongetConnectionManagergetConnectionOptionsgetManagergetSqljsManagergetRepositorygetTreeRepositorycreateQueryBuilder
Use the equivalent methods on your DataSource instance:
// Before
const repo = getRepository(User)
const qb = createQueryBuilder("user")
// After
const repo = dataSource.getRepository(User)
const qb = dataSource.createQueryBuilder("user")Configuration via environment variables removed
The deprecated ConnectionOptionsEnvReader class and the ability to configure connections via TYPEORM_CONNECTION, TYPEORM_URL, and other TYPEORM_* environment variables has been removed. The ormconfig.env file format is also no longer supported. TypeORM no longer auto-loads .env files or depends on dotenv.
Use a TypeScript or JavaScript configuration file instead:
// ormconfig.ts
export default {
type: process.env.DB_TYPE,
url: process.env.DB_URL,
// ...
}Behavioral changes
invalidWhereValuesBehavior default changed to throw
This is a significant behavioral change that may break existing applications at runtime.
The default behavior for null and undefined values in where conditions has changed. Previously, null and undefined values were silently ignored (the property was skipped). Now, both throw an error by default.
This change prevents subtle bugs where queries like findBy({ id: undefined }) would silently return all rows instead of failing.
// v0.3: silently returns all posts (null is ignored)
// v1.0: throws TypeORMError
await repository.find({ where: { text: null } })
// v0.3: silently returns all posts (undefined is ignored)
// v1.0: throws TypeORMError
await repository.find({ where: { text: undefined } })To match null values, use the IsNull() operator:
import { IsNull } from "typeorm"
await repository.find({ where: { text: IsNull() } })To restore the previous behavior, set invalidWhereValuesBehavior in your data source options:
new DataSource({
// ...
invalidWhereValuesBehavior: {
null: "ignore",
undefined: "ignore",
},
})This setting guards all high-level APIs — find operations, repository/manager mutation methods, and queryBuilder.setFindOptions() (the only QueryBuilder method that is affected). The rest of the QueryBuilder methods (.where(), .andWhere(), .orWhere()) are not affected — null and undefined values pass through as-is. See Null and undefined handling for full details.
Hashing
In TypeORM v1, the SHA1 hashing algorithm used for hashing is applied directly to the input. In the previous versions (v0.3), the input was first encoded using encodeURIComponent.
If you use TypeORM's query result cache, existing cached entries will be invalidated after upgrading because the hash function produces different output. Caches will be rebuilt automatically — you may see a brief increase in cache misses.
If you have table and columns names containing special characters, you can use @typeorm/legacy-naming-strategies to avoid changes in the database:
import { NamingStrategyV03 } from "@typeorm/legacy-naming-strategies"
const dataSource = new DataSource({
...
namingStrategy: new NamingStrategyV03(),
...
})Glob patterns
Glob patterns (used in entity/migration file discovery) are now handled by tinyglobby instead of glob. This is a drop-in replacement for most projects.
orphanedRowAction: "nullify" with non-nullable foreign keys
When orphanedRowAction is "nullify" (the default) and the foreign key column is non-nullable, orphaned children are now deleted instead of throwing a database constraint violation. Previously, TypeORM would attempt to set the FK to null, which failed on non-nullable columns.
This only applies when the relation is loaded on the entity instance. TypeORM does not automatically load relations — it only traverses relation values that are already populated on the object. To ensure orphaned children are handled, load the relation before calling remove or save:
const parent = await manager.findOne(Parent, {
where: { id: 1 },
relations: { children: true },
})
await manager.remove(parent)If the relation is not loaded (i.e. the property is undefined), TypeORM will not detect or delete orphaned children, which may result in foreign key constraint violations.
If you were relying on the error to prevent accidental child deletion, set orphanedRowAction: "disable" on the relation to preserve the old behavior.
Cascade remove now works for one-to-many relations
Calling manager.remove(entity) with cascade: true or cascade: ["remove"] on a one-to-many relation now correctly deletes child entities before the parent. Previously, the child entities were not cascade-removed, causing the DELETE to fail with a foreign key constraint violation. Additionally, cascade operations are now scoped to the matching operation type — for example, save() only follows insert/update cascades and no longer traverses remove-only relations.
Many-to-many junction rows and soft-deleted entities
Calling recover() on a soft-deleted entity with many-to-many relations no longer throws a duplicate key violation. Junction table rows are not touched by softRemove, but TypeORM previously couldn't see them when loading the entity for recovery, causing it to attempt duplicate inserts.
As a side effect, many-to-many junction comparisons during save() now include soft-deleted related entities. If you explicitly set a relation array that excludes a soft-deleted entity, its junction row will be removed:
// photo2 was independently soft-deleted but its junction row exists
user.manyToManyPhotos = [photo1] // photo2 excluded
await manager.save(user) // junction row for photo2 is now removedThis only applies when the relation property is explicitly set. If it is undefined, no comparison is performed and junction rows are left intact.
Logger
FileLogger lets the underlying platform (e.g. NodeJS) handle the paths instead of determining the path relative to the app root. You can provide an absolute path (or a path relative to process.cwd()) if the app is not started from its root folder:
const dataSource = new DataSource({
logger: new FileLogger("all", { logPath: "/path/to/file.log" }),
})Columns
readonly option removed
The deprecated readonly column option has been removed. Use the update option instead — note that it takes the opposite value:
// Before
@Column({ readonly: true })
authorName: string
// After
@Column({ update: false })
authorName: stringunsigned on ColumnNumericOptions removed
The deprecated unsigned property on ColumnNumericOptions (used with decimal/float column type overloads like @Column("decimal", { unsigned: true })) has been removed, as MySQL deprecated UNSIGNED for non-integer numeric types. The unsigned option on ColumnOptions for integer types is not affected.
Relations
nullable: false now uses INNER JOIN
Relations marked with nullable: false now use INNER JOIN instead of LEFT JOIN when loaded via relations, eager loading, or find options. This applies only to relation types that own the join column (ManyToOne and owning-side OneToOne).
This is semantically correct since a non-nullable foreign key guarantees the related entity exists, and allows the database optimizer to produce more efficient query plans.
Potentially breaking: If your database contains rows that violate the NOT NULL constraint (e.g. orphaned foreign keys, or nullable: false was set but the column is actually nullable in the DB), those rows will be excluded from query results. Verify your data integrity or change the relation to nullable: true if needed.
// INNER JOIN — related entity is guaranteed to exist
@ManyToOne(() => User, { nullable: false })
author: User
// LEFT JOIN — related entity may not exist (default)
@ManyToOne(() => User)
optionalEditor: UserOneToMany, ManyToMany, and inverse OneToOne relations always use LEFT JOIN regardless of the nullable setting, since these relation types do not have a join column on the current table.
Soft-delete exception: If the related entity has a @DeleteDateColumn, LEFT JOIN is used even for nullable: false relations (unless withDeleted: true is set). This prevents soft-deleted related entities from filtering out their parent rows.
Repository
findOneById
The deprecated findOneById method has been removed from EntityManager, Repository, BaseEntity, MongoEntityManager, and MongoRepository. Use findOneBy instead:
// Before
const user = await manager.findOneById(User, 1)
const user = await repository.findOneById(1)
const user = await User.findOneById(1)
// After
const user = await manager.findOneBy(User, { id: 1 })
const user = await repository.findOneBy({ id: 1 })
const user = await User.findOneBy({ id: 1 })For MongoDB entities with @ObjectIdColumn(), findOneBy works the same way — TypeORM automatically translates the property name to _id.
findByIds removed
The deprecated findByIds method has been removed from EntityManager, Repository, and BaseEntity. Use findBy with the In operator instead:
// Before
const users = await repository.findByIds([1, 2, 3])
// After
import { In } from "typeorm"
const users = await repository.findBy({ id: In([1, 2, 3]) })exist renamed to exists
The deprecated Repository.exist() method has been removed. Use exists() instead — the behavior is identical:
// Before
const hasUsers = await userRepository.exist({ where: { isActive: true } })
// After
const hasUsers = await userRepository.exists({ where: { isActive: true } })AbstractRepository, @EntityRepository, and getCustomRepository removed
The AbstractRepository class, @EntityRepository decorator, and getCustomRepository() method have been removed. These were deprecated in v0.3 in favor of Repository.extend():
// Before
@EntityRepository(User)
class UserRepository extends AbstractRepository<User> {
findByName(name: string) {
return this.repository.findOneBy({ name })
}
}
const userRepo = dataSource.getCustomRepository(UserRepository)
// After
const UserRepository = dataSource.getRepository(User).extend({
findByName(name: string) {
return this.findOneBy({ name })
},
})The following error classes were also removed: CustomRepositoryDoesNotHaveEntityError, CustomRepositoryCannotInheritRepositoryError, CustomRepositoryNotFoundError.
@RelationCount decorator and loadRelationCountAndMap removed
The @RelationCount decorator and SelectQueryBuilder.loadRelationCountAndMap() method have been removed. Use @VirtualColumn or a sub-query in your query builder instead:
// Before
@RelationCount((post: Post) => post.categories)
categoryCount: number
// After — use @VirtualColumn with a sub-query
// Replace the junction table name and column names to match your schema
@VirtualColumn({
query: (alias) =>
`SELECT COUNT(*) FROM post_categories_category WHERE postId = ${alias}.id`,
})
categoryCount: numberFind Options
join option removed
The deprecated join property on FindOneOptions and FindManyOptions has been removed, along with the JoinOptions interface.
leftJoinAndSelect → relations
If you were using leftJoinAndSelect, replace it with the relations object syntax — relations always performs LEFT JOINs with selection, which is equivalent:
// Before
const posts = await repository.find({
join: {
alias: "post",
leftJoinAndSelect: {
categories: "post.categories",
author: "post.author",
},
},
})
// After
const posts = await repository.find({
relations: { categories: true, author: true },
})All other join types → QueryBuilder
The relations option only supports LEFT JOINs with selection. If you were using innerJoinAndSelect, innerJoin, or leftJoin (without select), switch to the QueryBuilder API:
// Before — innerJoinAndSelect
const posts = await repository.find({
join: {
alias: "post",
innerJoinAndSelect: {
categories: "post.categories",
},
},
})
// After — QueryBuilder with innerJoinAndSelect
const posts = await repository
.createQueryBuilder("post")
.innerJoinAndSelect("post.categories", "categories")
.getMany()
// Before — leftJoin (without select)
const posts = await repository.find({
join: {
alias: "post",
leftJoin: {
categories: "post.categories",
},
},
where: { categories: { isRemoved: false } },
})
// After — QueryBuilder with leftJoin
const posts = await repository
.createQueryBuilder("post")
.leftJoin("post.categories", "categories")
.where("categories.isRemoved = :isRemoved", { isRemoved: false })
.getMany()This distinction matters in practice. For example, PostgreSQL and CockroachDB do not allow FOR UPDATE on the nullable side of an outer join, so queries that combine locking with joined relations may need INNER JOINs:
// Before — innerJoinAndSelect + lock
const post = await repository.findOne({
join: {
alias: "post",
innerJoinAndSelect: {
categories: "post.categories",
},
},
lock: { mode: "pessimistic_write", tables: ["category"] },
})
// After — QueryBuilder with innerJoinAndSelect + lock
const post = await repository
.createQueryBuilder("post")
.innerJoinAndSelect("post.categories", "categories")
.setLock("pessimistic_write", undefined, ["categories"])
.getOne()Locking with nested relations → QueryBuilder
The relations option cannot be used with pessimistic locking on joined tables because relations always uses LEFT JOINs, and PostgreSQL/CockroachDB reject FOR UPDATE on the nullable side of outer joins. Use QueryBuilder with innerJoinAndSelect instead:
// Before — nested relations + lock via find options
const post = await repository.findOne({
where: { id: 1 },
join: {
alias: "post",
innerJoinAndSelect: {
categories: "post.categories",
images: "categories.images",
},
},
lock: { mode: "pessimistic_write", tables: ["images"] },
})
// After — QueryBuilder with innerJoinAndSelect + lock
const post = await repository
.createQueryBuilder("post")
.innerJoinAndSelect("post.categories", "categories")
.innerJoinAndSelect("categories.images", "images")
.where("post.id = :id", { id: 1 })
.setLock("pessimistic_write", undefined, ["images"])
.getOne()Note that locking the main table still works with relations — only locking joined tables requires QueryBuilder with inner joins.
String-based select removed
The deprecated string-array syntax for select find options has been removed. Use the object syntax instead:
// Before
const users = await repository.find({
select: ["id", "name"],
})
// After
const users = await repository.find({
select: { id: true, name: true },
})The removed type is FindOptionsSelectByString.
String-based relations removed
The deprecated string-array syntax for relations find options has been removed. Use the object syntax instead:
// Before
const users = await repository.find({
relations: ["profile", "posts"],
})
// After
const users = await repository.find({
relations: { profile: true, posts: true },
})The removed type is FindOptionsRelationByString.
QueryBuilder
printSql removed
The printSql() method on query builders has been removed. It was redundant because all executed queries are already automatically logged through the configured logger when query logging is enabled. Use getSql() or getQueryAndParameters() to inspect the generated SQL instead:
// Before
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.printSql()
.getMany()
// After — inspect SQL before executing
const qb = dataSource
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
console.log(qb.getSql())
// or: const [sql, params] = qb.getQueryAndParameters()
const users = await qb.getMany()To log all executed queries automatically, enable query logging in your DataSource:
new DataSource({
// ...
logging: ["query"],
})onConflict removed
The onConflict() method on InsertQueryBuilder has been removed. It accepted raw SQL strings which were driver-specific and error-prone. Use orIgnore() or orUpdate() instead:
// Before
await dataSource
.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.onConflict(`("id") DO NOTHING`)
.execute()
// After
await dataSource
.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.orIgnore()
.execute()
// Before
await dataSource
.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.onConflict(`("id") DO UPDATE SET "title" = :title`)
.setParameter("title", post.title)
.execute()
// After
await dataSource
.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.orUpdate(["title"], ["id"])
.execute()orUpdate object overload removed
The object-based orUpdate() overload accepting { columns?, overwrite?, conflict_target? } has been removed. Use the array-based signature instead:
// Before
.orUpdate({ conflict_target: ["date"], overwrite: ["title"] })
// After
.orUpdate(["title"], ["date"])setNativeParameters removed
// Before
qb.setNativeParameters({ key: "value" })
// After
qb.setParameters({ key: "value" })WhereExpression type alias removed
// Before
import { WhereExpression } from "typeorm"
// After
import { WhereExpressionBuilder } from "typeorm"replacePropertyNames removed
The deprecated replacePropertyNames() protected method on QueryBuilder has been removed. If you were overriding it in a custom subclass, the override is no longer called.
Deprecated lock modes removed
// Before
.setLock("pessimistic_partial_write")
// After
.setLock("pessimistic_write")
.setOnLocked("skip_locked")
// Before
.setLock("pessimistic_write_or_fail")
// After
.setLock("pessimistic_write")
.setOnLocked("nowait")The same applies to find options:
// Before
{ lock: { mode: "pessimistic_partial_write" } }
// After
{ lock: { mode: "pessimistic_write", onLocked: "skip_locked" } }
// Before
{ lock: { mode: "pessimistic_write_or_fail" } }
// After
{ lock: { mode: "pessimistic_write", onLocked: "nowait" } }Migrations
getAllMigrations removed
The deprecated getAllMigrations() method has been removed from MigrationExecutor. Use getPendingMigrations() or getExecutedMigrations() instead, or access dataSource.migrations directly for the list of registered migration classes:
// Before
const migrations = await migrationExecutor.getAllMigrations()
// After — depending on what you need
const pending = await migrationExecutor.getPendingMigrations()
const executed = await migrationExecutor.getExecutedMigrations()
const registered = dataSource.migrationsQueryRunner.loadedTables and loadedViews removed
// Before
const tables = queryRunner.loadedTables
const views = queryRunner.loadedViews
// After
const tables = await queryRunner.getTables()
const views = await queryRunner.getViews()Note: the replacements are async methods, not synchronous properties.
Container system
The deprecated IoC container integration has been removed: useContainer(), getFromContainer(), ContainerInterface, ContainedType, and UseContainerOptions.
TypeORM no longer has built-in IoC container support. The typeorm-typedi-extensions and typeorm-routing-controllers-extensions packages are also no longer compatible. The sections below cover how to migrate depending on your setup.
Subscribers and migrations with dependencies
TypeORM always instantiates subscribers and migrations internally using a zero-argument constructor, so you cannot pass pre-built instances. If your migrations need access to services, use the DataSource (available via queryRunner.dataSource) inside the migration itself:
// Before
import { useContainer } from "typeorm"
import { Container } from "typedi"
useContainer(Container)
// After — access dependencies via the DataSource inside the migration
export class MyMigration1234 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
const repo = queryRunner.dataSource.getRepository(User)
// ...
}
}Accessing repositories and entity manager
If you previously used typeorm-typedi-extensions to inject EntityManager or repositories into your services, use the DataSource directly instead:
// Before (with typeorm-typedi-extensions)
import { InjectManager, InjectRepository } from "typeorm-typedi-extensions"
class UserService {
@InjectManager()
private manager: EntityManager
@InjectRepository(User)
private userRepository: Repository<User>
}
// After — access from the DataSource instance
class UserService {
private manager: EntityManager
private userRepository: Repository<User>
constructor(dataSource: DataSource) {
this.manager = dataSource.manager
this.userRepository = dataSource.getRepository(User)
}
}Using with a DI framework
If you use a DI framework, register the DataSource (or its repositories) as providers in your container:
// typedi example
import { DataSource } from "typeorm"
import { Container } from "typedi"
const dataSource = new DataSource({/* ... */})
await dataSource.initialize()
Container.set(DataSource, dataSource)
Container.set("UserRepository", dataSource.getRepository(User))NestJS
NestJS users are not affected — the @nestjs/typeorm package has its own integration that does not depend on TypeORM's removed container system. However, @nestjs/typeorm v10 and v11.0.0 attempt to register the removed Connection class and will crash at startup. Upgrade to @nestjs/typeorm v11.0.1 or later for TypeORM v1 compatibility. The @typeorm/codemod tool will bump it for you automatically.
Other internal removals
The following internal APIs have been removed. These only affect you if you were building custom drivers, extending QueryBuilder, or using low-level metadata APIs:
| Removed | Replacement |
|---|---|
EntityMetadata.createPropertyPath() (static) |
Removed with no public replacement |
EntityMetadata.getValueMap() options param |
Remove the third argument — it was never functional |
DriverUtils.buildColumnAlias() |
Use DriverUtils.buildAlias() |
Broadcaster.broadcastLoadEventsForAll() |
No replacement — use individual event subscribers |
QueryExpressionMap.nativeParameters |
Use QueryExpressionMap.parameters |
RdbmsSchemaBuilder.renameTables() |
Removed |