错误提示:ERROR [QueryFailedError: Specified key was too long; max key length is 767 bytes] Error during TypeORM initialization
这个错误通常在使用 MySQL/MariaDB 数据库时出现,原因是索引键长度超过了 InnoDB 引擎的 767 字节限制。
MySQL 的 InnoDB 引擎对索引键长度有限制,使用
1 | utf8mb4 |
字符集时,每个字符占用 4 字节,对于 VARCHAR(255) 字段,索引键长度 = 255 × 4 = 1020 字节 > 767 字节限制
解决方法:
方法 1:减少字段长度(推荐)
修改实体类中的字段长度:
@Column({ length: 191 }) // 191 × 4 = 764 < 767
name: string;
方法 2:修改数据库配置
修改 MySQL 配置(需要服务器权限):
[mysqld]
innodb_large_prefix=1
innodb_file_format=Barracuda
innodb_file_per_table=1
然后重启 MySQL 服务
方法 3:使用前缀索引
@Index({ length: 191 })
@Column()
name: string;
方法 4:更改表存储格式
@Entity()
@TableInheritance({ column: { type: "varchar", name: "type", length: 191 } })
export abstract class Content {
// ...
}
方法 5:全局配置 TypeORM
{
type: "mysql",
// ...
entitySkipConstructor: true,
namingStrategy: new DefaultNamingStrategy(),
maxAliasLength: 191 // 设置最大别名长度
}
总结下只需要把MySQL 5.6升级MySQL 5.7.7 或更高版本, 是最简单且兼容性最好的解决方案
升级参考:https://www.ttbobo.com/4972.html
评论(0)