spring 如何在dynamodb中使用主键删除记录

wribegjk  于 2023-03-16  发布在  Spring
关注(0)|答案(1)|浏览(103)

我使用java在amazon dynamodb中使用主键id获取记录。

帐户控制器.java

package com.dynamodb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.account.json.AccountJson;
import com.account.service.AccountService;

@Controller
public class AccountController extends AbstractServiceController {

@Autowired
private AccountService accountService;

@RequestMapping(value = "/deleteAccountByAccountId", method = RequestMethod.POST)
public @ResponseBody String deleteAccountByAccountId(@RequestBody AccountJson accountJson) {
    try {
        Boolean bool = accountService.deleteAccountByAccountId(accountJson.getAccountId());
        if (bool) {
            return "Record deleted Successfully";
        } else {
            return "Record not deleted";
        }
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}
}

帐户服务.java

package com.account.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.account.dao.AccountRepository;

@Service
public class AccountService {

@Autowired
private AccountRepository accountRepository;

public Boolean deleteAccountByAccountId(String accountId) {
    return accountRepository.deleteAccountByAccountId(accountId);
}

}

帐户存储库.java

package com.account.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.account.datastore.Account;

@Repository
public class AccountRepository extends BaseRepository {

public Account getAccountByAccountId(String accountId) {
    Account account = null;
    try {
        DynamoDBMapper mapper = getDynameDbMapper();
        DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
        scanExpression.addFilterCondition("accountId", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS(accountId)));
        List<Account> accounts = mapper.scan(Account.class, scanExpression);
        if (accounts != null && accounts.size() > 0) {
            account = accounts.get(0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return account;
}

public Boolean deleteAccountByAccountId(String accountId) {
    try {
        Account account = getAccountByAccountId(accountId);
        if (account != null) {
            DynamoDBMapper mapper = getDynameDbMapper();
            mapper.delete(account);
        } else {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

}

帐户.java

package com.account.datastore;

import java.io.Serializable;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;

@DynamoDBTable(tableName = "cd_accounts")
public class Account implements Serializable {

private static final long serialVersionUID = 244669855912873613L;

@DynamoDBAutoGeneratedKey
@DynamoDBHashKey
private String accountId;
private String documentTypeId;
private String accountName;
private Long isActive;
private Long isBill;

public String getAccountId() {
    return accountId;
}

public void setAccountId(String accountId) {
    this.accountId = accountId;
}

public String getDocumentTypeId() {
    return documentTypeId;
}

public void setDocumentTypeId(String documentTypeId) {
    this.documentTypeId = documentTypeId;
}

public String getAccountName() {
    return accountName;
}

public void setAccountName(String accountName) {
    this.accountName = accountName;
}

public Long getIsActive() {
    return isActive;
}

public void setIsActive(Long isActive) {
    this.isActive = isActive;
}

public Long getIsBill() {
    return isBill;
}

public void setIsBill(Long isBill) {
    this.isBill = isBill;
}

}

删除记录时出错如何使用java在amazon dynamodb中删除记录。

com.amazonaws.AmazonServiceException: The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 ERROR [AccountRepository] deleteAccountByAccountId Error:The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 DEBUG [AccountController] --------------deleteAccountByAccountId----------------END------------------
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1077)
    at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:725)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3106)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.deleteItem(AmazonDynamoDBClient.java:967)
    at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1364)
    at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1272)
    at com.account.dao.AccountRepository.deleteAccountByAccountId(AccountRepository.java:110)
    at com.account.service.AccountService.deleteAccountByAccountId(AccountService.java:40)
    at com.account.controller.AccountController.deleteAccountByAccountId(AccountController.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
cqoc49vn

cqoc49vn1#

documentTypeIdcd_documentTypes表的主键,此主键在cd_accounts表中用作外键。
如果表有外键关系,我们必须在Account类中的documentTypeId属性上提及@DynamoDBRangeKey注解。在属性documentTypeId上声明@DynamoDBRangeKey后,问题得到解决。

@DynamoDBRangeKey
    private String documentTypeId;

如果我们想用java在amazon dynamodb中保存、更新或删除记录,我们必须在primarykey列的顶部加上注解@DynamoDBHashKey

@DynamoDBAutoGeneratedKey
@DynamoDBHashKey
private String accountId;

下图显示了cd_accounts表中存在的外键关系。

**注意:**如果表Map到amaozong dynamodb中的另一个表主键,则显示Range key attribute字段。

相关问题