nestjs/TypeOrm数据库事务 [英] nestjs / TypeOrm database transaction

查看:863
本文介绍了nestjs/TypeOrm数据库事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有2个服务,即A和B. 服务A具有执行以下功能的功能:

  1. 验证数据
  2. 调用服务B函数,该函数对数据库进行更改
  3. 多做点事
  4. 对数据库进行更改

现在,让我们假设以下第3步或第4步之一失败了. 由于服务B在数据库中进行了更改,因此这些更改仍然存在.

在这种情况下,有什么方法可以回滚数据库吗?我虽然是关于数据库事务的,但我在嵌套js中找不到任何方法可以做到这一点,尽管TypeOrm支持它,但嵌套似乎并不自然. 如果没有,那么我现在就被服务B所发生的更改卡住"了,但是如果服务B却没有发生更改,我就被卡住了."

非常感谢.

解决方案

有许多可用的解决方案,它们都应基于SQL事务管理.

我个人认为,实现该目标的最简单方法是在数据库上执行代码时使用相同的EntityManager实例.然后,您可以使用类似的内容:

getConnection().transaction(entityManager -> {
    service1.doStuff1(entityManager);
    service2.doStuff2(entityManager);
});

您可以从EntityManager实例中生成一个QueryRunner,该实例将包装在同一事务中,以防您在ORM操作之外执行原始SQL.您还需要从EntityManager生成Repository实例,否则它们将在主事务之外执行代码.

Assuming we have 2 services, A and B. Service A has a function doing the following:

  1. Validate the data
  2. Call a service B function, that makes changes to the database
  3. Do some more stuff
  4. Do changes to the database

Now, let's assume that one of the following, steps 3 or 4 failed. Since service B made changes in the database, those changes are still there.

Is there any way of rolling the database back in this case? I though about database transactions, but I couldn't find any way to do that in nest js, although it is supported by TypeOrm, it doesn't look natural to nest. If not, I am now "stuck" with the changes occured by service B, but without the changes should have happen by A.

Thanks a lot.

解决方案

Many solutions are available, they should all be based on SQL transaction management.

Personally I feel that the simplest way to achieve that is to use the same EntityManager instance when you execute code on your database. Then you can use something like:

getConnection().transaction(entityManager -> {
    service1.doStuff1(entityManager);
    service2.doStuff2(entityManager);
});

You can spawn a QueryRunner from an EntityManager instance that will be wrapped in the same transaction in case you execute raw SQL outside ORM operations. You need also to spawn Repository instances from EntityManager as well or they will execute code outside the main transaction.

这篇关于nestjs/TypeOrm数据库事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆