gpt4 book ai didi

java - 是什么让事务成为 Spring/Java 中的事务(特定场景)?

转载 作者:行者123 更新时间:2023-12-01 19:09:05 26 4
gpt4 key购买 nike

我已经阅读了本网站上的交易定义以及其他一些外部资源。但在编写代码时,我很难理解事务的具体概念。

我有一个事务性的 BuyService 类。 BuyService 类被声明为事务性的,其唯一方法是 buyWidget(String widgetId)。此方法调用ExampleService 类,该类具有deleteWidgit(String widgetId) 方法。它还调用 InvoiceService 类,该类使用 writeInvoice(String widgitId) 方法。这是代码:

BuyService 类:

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class BuyService implements BuyServiceInterface
{
private ExampleServiceInterface exampleService;
private InvoiceServiceInterface invoiceService;

public void setExampleService(ExampleServiceInterface exampleService)
{
this.exampleService = exampleService;
}

public void setInvoiceService(InvoiceServiceInterface invoiceService)
{
this.invoiceService = invoiceService;
}

@Override
@Transactional(propagation=Propagation.REQUIRED)
public void buyWidget(Widget widgetId)
{
try
{
Widget purchasedWidget = this.exampleService.getWidgetById(String widgetId);
this.exampleService.deleteWidget(purchasedWidget);
this.invoiceService.writeInvoice(purchasedWidget);
}
catch (WidgetNotFoundException e)
{
System.out.println("Widget with widgetId " + widgetId + " not found.");
}
}
}

我非常确定 buyWidget 方法构成了一笔交易。它需要删除数据库(在 exampleService 中)中的小部件,并在购买数据库(在 invoiceService 中)中插入数据。但此后我对术语感到困惑。 deleteWidget 和 writeInvoice 方法本身也是事务吗?

示例服务类:

public class ExampleService implements ExampleServiceInterface
{
private ExampleServiceDaoInterface dao;

public void setExampleServiceDao(ExampleServiceDaoInterface dao)
{
this.dao = dao;
}

@Override
public void deleteWidget(Widget oldWidget)
throws WidgetNotFoundException
{
this.dao.delete(oldWidget);
}

@Override
public Widget getWidgetById(String widgetId)
{
return this.dao.getById(widgetId);
}
}

发票服务类:

public class InvoiceService implements InvoiceServiceInterface
{
private InvoiceServiceDaoInterface InvoiceServiceDao;

public void setInvoiceServiceDao(InvoiceServiceDaoInterface InvoiceServiceDao)
{
this.InvoiceServiceDao = InvoiceServiceDao;
}

@Override
public void writeInvoice(Widget purchasedWidget)
{
Date purchaseDate = new Date(new java.util.Date().getTime());
String isbn = purchasedWidget.getIsbn();
Purchases newPurchase = new Purchases(purchaseDate, isbn);
this.InvoiceServiceDao.savePurchase(newPurchase);
}
}

buyWidget 交易也会调用这两个方法吗?也就是说,即使这些方法都没有声明为事务。不将两个子方法声明为事务有哪些潜在的陷阱? (因为它们显然已经成为其中的一部分)。

最佳答案

Are the methods deleteWidget and writeInvoice themselves transactions as well?

他们将参与 buyWidget 交易,但他们本身并不具有交易性

Are the two methods called on by buyWidget transactions as well?

事务在进入buyWidget方法之前启动,并在该方法完成之前停止或回滚。这两个方法将参与 buyWidget 交易,但它们本身并不是交易。

关于java - 是什么让事务成为 Spring/Java 中的事务(特定场景)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com