我们一直在尝试在Loopback中实现ACID事务,但没有成功。文档中唯一的示例使用“create”方法。我们尝试完全覆盖事件以及多种操作钩子的变化。我们只能使create示例正常工作。
核心要求:我们需要能够在特定模型的create和update方法中启动事务,然后使用Loopback的ORM函数或直接使用SQL更新多个表,并根据业务规则进行提交或回滚。例如,我们需要终端能够接受带有头和详细交易的发票,验证它,更新各种表(如库存和客户),然后将所有更改保存(或回滚)在一个单独的ACID事务中。
使用数据库事务: https://docs.strongloop.com/display/public/LB/Using+database+transactions 这是文档中的示例:
在操作钩子中实现保存、更新等也无法正常工作:
核心要求:我们需要能够在特定模型的create和update方法中启动事务,然后使用Loopback的ORM函数或直接使用SQL更新多个表,并根据业务规则进行提交或回滚。例如,我们需要终端能够接受带有头和详细交易的发票,验证它,更新各种表(如库存和客户),然后将所有更改保存(或回滚)在一个单独的ACID事务中。
使用数据库事务: https://docs.strongloop.com/display/public/LB/Using+database+transactions 这是文档中的示例:
Post.create({title: 't1', content: 'c1'}, {transaction: tx}, function(err, post) {
post.updateAttributes({content: 'c2', {transaction: tx}, function(err, newPost) {
//
newPost.reviews.create({content: 'r1'}, {transaction: tx}, function(err, newPost) {
});
}
});
操作钩子:https://docs.strongloop.com/display/public/LB/Operation+hooks
我们只能成功地覆盖了一些核心方法:
Item.create = function(id, cb){
console.log('create'); // Success!
}
//
Item.find = function(id, cb){
console.log('find'); // Success!
}
Item.findById = function(id, cb){
console.log('findById'); // Success!
}
Item.getById = function(id, cb){
console.log('updateAttributes'); // Did not work!
}
Item.all = function(id, cb){
console.log('all'); // Did not work!
};
Item.findOrCreate = function(id, test, cb){
console.log('findOrCreate'); // Did not work!
}
Item.replicate = function(id, test, cb){
console.log('replicate'); // Did not work!
}
Item.save = function(id, test, cb){
console.log('save'); // Did not work!
}
Item.updateAll = function(id, test, cb){
console.log('updateAll'); // Did not work!
}
Item.upsert = function(id, test, cb){
console.log('upsert'); // Did not work!
}
Item.updateAttribute = function(id, cb){
console.log('updateAttribute'); // Did not work!
};
Item.updateById = function(id, test, cb){
console.log('updateById'); // Did not work!
}
在操作钩子中实现保存、更新等也无法正常工作:
Item.observe('before save', function(ctx, next) {
console.log('before save');
ctx.Model.beginTransaction({isolationLevel: ctx.Model.Transaction.READ_COMMITTED}, function(err, tx) {
// Now we have a transaction (tx)
console.log('begin transaction', err);
//tx.commit(function(err) {
// console.log('commit', err);
//})
//tx.rollback(function(err) {
// console.log('rollback', err);
//})
next();
});
})