问题
How to support transaction in Loopback4? Is there a decorator for the same, something like @Transaction?
I looked into the documentation here https://loopback.io/doc/en/lb4/Repositories.html but nothing is mentioned about the transaction.
回答1:
LoopBack 4 does not support transactions out of the box. Please open a new GitHub issue to discuss how to implement this feature:
- https://github.com/strongloop/loopback-next/issues/new
回答2:
LoopBack 4 now supports database transactions for quite a while:
import {
Transaction,
DefaultTransactionalRepository,
IsolationLevel,
} from '@loopback/repository';
// assuming there is a Note model extending Entity class, and
// ds datasource which is backed by a transaction enabled
// connector
const repo = new DefaultTransactionalRepository(Note, ds);
// Now we have a transaction (tx)
const tx = await repo.beginTransaction(IsolationLevel.READ_COMMITTED);
const created = await repo.create({title: 'Groceries'}, {transaction: tx});
const updated = await repo.update(
{title: 'Errands', id: created.id},
{transaction: tx},
);
// commit the transaction to persist the changes
await tx.commit();
Further reading:
- https://loopback.io/doc/en/lb4/Using-database-transactions.html
来源:https://stackoverflow.com/questions/54604916/transaction-support-in-loopback4