小编Dzm*_*nka的帖子

如何使用JAX-RS和Spring编写正确/可靠的事务代码

基本上,我正在尝试了解如何在使用Jax-RS和Spring开发REST服务时编写正确的(或"正确编写"?)事务代码.此外,我们正在使用JOOQ进行数据访问.但这不应该是非常相关的...
考虑简单的模型,我们有一些组织,有这些领域:"id", "name", "code".所有这一切都必须是独特的.还有一个status领域.
可能会在某个时候删除组织.但我们不想完全删除数据,因为我们希望将其保存以用于分析/维护目的.所以我们只需将组织"状态"字段设置为'REMOVED'.
因为我们不从表中删除组织行,所以我们不能简单地将唯一约束放在"名称"列上,因为我们可能会删除组织,然后创建一个具有相同名称的新组织.但是我们假设代码必须是全局唯一的,所以我们对code列有一个独特的约束.

因此,让我们看看这个简单的例子,创建组织,沿途执行一些检查.

资源:

@Component
@Path("/api/organizations/{organizationId: [0-9]+}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaTypeEx.APPLICATION_JSON_UTF_8)
public class OrganizationResource {
    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private DtoConverter dtoConverter;

    @POST
    public OrganizationResponse createOrganization(@Auth Person person, CreateOrganizationRequest request) {

        if (organizationService.checkOrganizationWithNameExists(request.name())) {
            // this throws special Exception which is intercepted and translated to response with 409 status code
            throw Responses.abortConflict("organization.nameExist", ImmutableMap.of("name", request.name()));
        }

        if (organizationService.checkOrganizationWithCodeExists(request.code())) {
            throw Responses.abortConflict("organization.codeExists", ImmutableMap.of("code", request.code()));
        }

        long organizationId = organizationService.create(person.user().id(), request.name(), request.code()); …
Run Code Online (Sandbox Code Playgroud)

java rest spring transactions jax-rs

8
推荐指数
1
解决办法
576
查看次数

标签 统计

java ×1

jax-rs ×1

rest ×1

spring ×1

transactions ×1