I wanted to do a bulk insert/update with TypeORM
The Test is described as below:
export class Test {
@PrimaryColumn('integer')
id: number;
@Column('varchar', { length: 255 })
testName: string;
}
I wanted to do a batch insert for:
const test1 = new Test();
script.id = 1;
script.testName = 't1';
const test2 = new Test();
test2.id = 2;
test2.testName = 't2';
const test3 = new Test();
test3.id = 3;
test3.testName = 't3';
const tests = [test1, test2, test3];
When I try:
const testRepository = dataSource.getRepository(Test);
await testRepository.save(tests);
It does not work, however, testRepository.save(test1); works.
Could you please let me know how to do a batch insert? Especially if there are 1000s of rows.
You can use the
insertmethod to do bulk inserts with TypeORM.The basic syntax would be:
The key things to note:
inserttakes an array of entity objectsSo for your example:
This will insert all 3 tests in a single query.
Some other tips: