[英]How to do transaction using aws s3 in Spring Boot
I wrote image upload method using spring boot of java as below.我使用 java 的 spring 引导编写了图像上传方法,如下所示。
It saves title and image path etc before upload image called Todo class.它在上传名为 Todo class 的图像之前保存标题和图像路径等。
@Override
public Todo saveTodo(String title, String description, MultipartFile file) {
// check if the file is empty
if (file.isEmpty()) {
throw new IllegalStateException("Cannot upload empty file");
}
// Check if the file is an image
if (!Arrays.asList(IMAGE_PNG.getMimeType(), IMAGE_BMP.getMimeType(), IMAGE_GIF.getMimeType(),
IMAGE_JPEG.getMimeType()).contains(file.getContentType())) {
throw new IllegalStateException("FIle uploaded is not an image");
}
// get file metadata
Map<String, String> metadata = new HashMap<>();
metadata.put("Content-Type", file.getContentType());
metadata.put("Content-Length", String.valueOf(file.getSize()));
// Save Image in S3 and then save Todo in the database
String path = String.format("%s/%s", amazonConfig.getBucketName(), UUID.randomUUID());
String fileName = String.format("%s", file.getOriginalFilename());
Todo todo = Todo.builder().description(description).title(title).imagePath(path).imageFileName(fileName)
.build();
repository.save(todo);
try {
fileStore.upload(path, fileName, Optional.of(metadata), file.getInputStream());
} catch (IOException e) {
throw new IllegalStateException("Failed to upload file", e);
}
return repository.findByTitle(todo.getTitle());
}
But when the error occurs doing upload, I want to delete the inserted todo totally.但是当上传发生错误时,我想完全删除插入的待办事项。
I can delete using repository delete method in catch manually.我可以在 catch 中使用存储库删除方法手动删除。
But Can I do this action without delete method writing only @transacion or something?但是我可以在没有删除方法的情况下只写@transacion 或其他东西来执行此操作吗?
Thank you for reading my question.感谢您阅读我的问题。
Just annotate the saveTodo
method with @Transactional
.只需使用
@Transactional
注释saveTodo
方法。
Itt will look like something this:它看起来像这样:
import org.springframework.transaction.annotation.Transactional;
// other imports
// other code
@Override
@Transactional
public Todo saveTodo(....
Then it will rollback if a RuntimeException occurs.如果发生 RuntimeException,它将回滚。 (IllegalStateException is a RuntimeException, so it will work fine)
(IllegalStateException 是一个 RuntimeException,所以它会正常工作)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.