我需要在服务层实现事务管理。Nodejs、sequelize和mysql是我正在使用的技术。所有crud操作都从db层调用到服务层。在这里,我需要通过从两个独立的db层调用来执行服务层中的两个insert操作。我已经在我的项目中实现了sequelize事务管理。我的问题是,我不能管理单事务下的2插入操作。因为,我需要收集第一次成功插入的数据。这样我就可以叫“那么”行动了。当我调用然后操作时,事务被提交了。所以应该如何让它成为可能。
common_database_Handler_file
this.insertData = function(collectionObject, collectionName) {
var collection = MODELS[collectionName];
return collection
.create(collectionObject);
};table1_database_Handler_file
this.create = function (data1) {
return commonHandler.insertData(data1,"table1")
}table2_database_Handler_file
this.create = function (data2) {
return commonHandler.insertData(data2,"table2")
}service_layer_file
sequelize.transaction(function (t1) {
//saving data to table1
this.createUser = function (data1) {
table1Handler.create(data1)
.then(function (response) {
if (response) {
var data2 = {};
data2.id = response.id;
//saving data to table2
table2Handler.create(data2)
.then(function (data2) {
console.log("success);
}
}
}
.catch(error => {
new Error();
console.log("Failed");
}
}
});发布于 2018-04-04 17:26:02
事务必须传递到您正在数据库处理程序中执行的操作中。
this.insertData = function(collectionObject, collectionName, t1) {
var collection = MODELS[collectionName];
return collection
.create(collectionObject, { transaction: t1 });
};要实现上述目标,您可以将事务从服务层传递到数据库层,作为参数传递给函数。
在上面的实现中,事务不是调用函数,而是分配一个函数。下面是一个示例,说明它的实际外观
this.createUser = function(data1) {
return sequelize.transaction(function (t1) {
return firstDBfunction(data1, t1)
.then(function(response){
return secondDBFunction(data2 , t1);
});
}).then(function(response){
//transaction successful
}).catch(function(error){
//transaction failed, so auto ROLLBACK
});
}https://stackoverflow.com/questions/49654053
复制相似问题