Batch Saving Entities
Optimizing performance is crucial when dealing with large data sets. Onyx Database provides batch operations to efficiently save multiple entities in one call. This tutorial demonstrates how to batch save entities using Onyx's ORM.
Steps to Batch Save Entities (Onyx Cloud Database)
1
Create a Collection of Entities
Instantiate multiple entities and add them to a collection.
1const people = [];
2
3for (let i = 0; i < 1000; i++) {
4 people.push({
5 firstName: `TestName_${i}`,
6 lastName: `TestName_${i}`,
7 dateCreated: new Date()
8 });
9}
- Use a loop to create instances of your entity and populate their fields.
- Ensure that all required fields (non-nullable attributes) are set for each entity.
2
Batch Save the Entities
Use the Persistence Manager's
save
method to save the collection.1await db.save('People', people);
- The
save
method accepts a collection of entities and persists them in a single operation. - If an entity with the same primary key exists, it will be updated instead of inserted.
3
Verify the Batch Save Operation
Execute a query to confirm that all entities have been saved.
1const savedPeople = await db.from('People').list();
2console.log(`${savedPeople.length} people saved`);
- Use a
Query
to retrieve the saved entities. - Verify the number of entities returned matches the number saved.
Important Notes
- Onyx does not differentiate between insert and update operations. If an entity with the same primary key exists, it will be updated.
- All entities in the batch must be of the same type when using
save
. - Batch operations can significantly improve performance by reducing the number of database calls.
Troubleshooting
- Entities Not Persisting: Ensure that all entities are properly instantiated and that all required fields are set before saving.
- Invalid Identifier: Verify that each entity's primary key is correctly configured and unique if necessary.
- Type Mismatch: Make sure all entities in the collection are of the same type.
- Performance Issues: Batch operations are designed to improve performance. If you're experiencing issues, check for network latency or large payload sizes.
Next Steps
Now that you know how to batch save entities, you can explore further topics: