乐闻世界logo
搜索文章和话题

How to saving a list of Entity using TypeORM

1个答案

1

In TypeORM, batch saving data is typically performed using the save() method. This method can accept an array of entity objects and effectively insert or update them into the database. Below is a specific example demonstrating how to use TypeORM for batch saving data:

Suppose we have an entity named User, and we need to batch save multiple user objects into the database.

First, you need to ensure that the User entity has been defined and the required TypeORM modules have been imported:

typescript
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() email: string; }

Next, you can create an array of user objects and save them to the database using the save() method:

typescript
import { createConnection, getRepository } from 'typeorm'; import { User } from './User'; async function saveUsers() { // Create database connection const connection = await createConnection({ type: "postgres", // Database type host: "localhost", port: 5432, username: "your_username", password: "your_password", database: "your_database", entities: [ User ], synchronize: true, }); const userRepository = connection.getRepository(User); // Create user data const users = [ { name: 'Alice', email: 'alice@example.com' }, { name: 'Bob', email: 'bob@example.com' }, { name: 'Charlie', email: 'charlie@example.com' } ]; // Batch save users await userRepository.save(users); console.log('Users have been saved'); } saveUsers().catch(error => console.log(error));

In this example, we first establish a connection to the database and ensure that the User entity has been synchronized to the database. Then, we create an array containing multiple users. By calling userRepository.save(users), these user data will be batch saved into the database.

Note that the save() method determines whether to perform an update or an insert operation based on the primary key when handling existing records. This makes the save() method very flexible and suitable for various batch processing scenarios.

Additionally, if you are handling a very large amount of data, TypeORM supports batch processing to optimize performance and memory usage. This typically involves manually splitting the data array and calling the save() method in batches.

2024年6月29日 12:07 回复

你的答案