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

How to saving a list of Entity using TypeORM

1个答案

1

In TypeORM, bulk saving data is typically performed using the save() method. This method accepts an array of entity objects and efficiently inserts or updates them into the database. Here is a specific example demonstrating how to use TypeORM for bulk saving data: Suppose we have an entity named User, and we need to bulk insert multiple user objects into the database. First, ensure that the User entity is defined and the required TypeORM modules are imported: ```typescript import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity() export class User { @PrimaryGeneratedColumn() id: number;

@Column() name: string;

@Column() email: string; } Next, 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' } ];

// Bulk 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 is synchronized with the database. Then, we create an array containing multiple users. By calling userRepository.save(users), these user records are bulk inserted into the database. It's important to note that the save() method determines whether to perform an update or an insert based on the primary key when handling existing records. This makes the save() method highly flexible and suitable for various batch processing scenarios. Additionally, if you're dealing with a very large dataset, 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 回复

你的答案