I am trying to delete the data from my DynamoDB table based on the Id(HashKey).
Association.java
#DynamoDBTable(tableName = "Association")
public class Association {
private String id;
private String name;
private String adminName;
private String email;
private String url;
private String contactNumber;
private String password;
public Association() { }
public Association(String name, String adminName, String email, String url,
String contactNumber, String password) {
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
public Association(String id, String name, String adminName, String email, String url,
String contactNumber, String password) {
this.id = id;
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
#DynamoDBHashKey(attributeName = "Id")
#DynamoDBAutoGeneratedKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBAttribute(attributeName="Name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#DynamoDBAttribute(attributeName="AdminName")
public String getAdminName() { return adminName; }
public void setAdminName(String adminName) { this.adminName = adminName; }
#DynamoDBAttribute(attributeName="Email")
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
#DynamoDBAttribute(attributeName="Url")
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
#DynamoDBAttribute(attributeName="ContactNumber")
public String getContactNumber() { return contactNumber; }
public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; }
#DynamoDBAttribute(attributeName="Password")
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
AssociationRepository.java:-
private AmazonDynamoDBClient getDynamoDBClient(){
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
client.setRegion(Region.getRegion(REGION));
client.setEndpoint(EndPoint);
return client;
}
private void deleteAssociation(String id) {
try {
DynamoDBConfig dynamoDBConfig = new DynamoDBConfig();
DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBConfig.getDBClient());
Association associationToDelete = new Association();
associationToDelete.setId(id);
// Delete the item.
mapper.delete(associationToDelete);
} catch (Exception exception) {
System.out.println(exception);
throw exception;
}
}
I am getting the below error:-
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: No method annotated with interface com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey for class class Association
I have searched the AWS docs for this but could not find any solution that fixes this.Does anyone of you ever faced this issue?
The issue is the same I mentioned on your other post, in DynamoDB you can’t work an item using attributes which are not the primary key (Partition Key only in your scenario).
Moreover, to delete an item it is mandatory to do it by its primary key, so in your case the attribute Name.
Try to do same operation by setting the name, the error is not very descriptive so maybe there is another underlying issue. However, if you don’t meet above requirement it will never work.
Related
I am trying to fetch the data from my DynamoDB table based on the Id(HashKey).
Association.java
#DynamoDBTable(tableName = "Association")
public class Association {
private String id;
private String name;
private String adminName;
private String email;
private String url;
private String contactNumber;
private String password;
public Association() { }
public Association(String name, String adminName, String email, String url,
String contactNumber, String password) {
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
public Association(String id, String name, String adminName, String email, String url,
String contactNumber, String password) {
this.id = id;
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
#DynamoDBHashKey(attributeName = "Id")
#DynamoDBAutoGeneratedKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBAttribute(attributeName="Name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#DynamoDBAttribute(attributeName="AdminName")
public String getAdminName() { return adminName; }
public void setAdminName(String adminName) { this.adminName = adminName; }
#DynamoDBAttribute(attributeName="Email")
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
#DynamoDBAttribute(attributeName="Url")
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
#DynamoDBAttribute(attributeName="ContactNumber")
public String getContactNumber() { return contactNumber; }
public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; }
#DynamoDBAttribute(attributeName="Password")
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
AssociationRepository.java:-
private AmazonDynamoDBClient getDynamoDBClient(){
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
client.setRegion(Region.getRegion(REGION));
client.setEndpoint(EndPoint);
return client;
}
public Association fetchById(String id) {
DynamoDBConfig dynamoDBConfig = new DynamoDBConfig();
DynamoDBMapper mapper = new DynamoDBMapper(getDBClient());
Association association = new Association();
association.setId(id);
Association scanResult = null;
try {
scanResult = mapper.load(association);
}
catch (Exception exception){
throw exception;
}
return scanResult;
}
Invoking fetchById("123"). Where "123" is an existing Id of the table It throws the below error to me:-
{
"errorMessage": "The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: IT6U9BJ0RAJUDPMLGGR67C542VVV4KQNSO5AEMVJF66Q9ASUAAJG)",
"errorType": "com.amazonaws.AmazonServiceException",
"stackTrace": [
"com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1305)",
"com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:852)",
DYNAMODB TABLE DETAILS:-
I have searched the AWS docs for this but could not find any solution that fixes this.Does anyone of you ever faced this issue?
If you realize, you defined Name as your partition key. However on code, you are trying to load an item by the attribute Id.
That's not possible as DynamoDB only allows you to load an item by its primary key, which in your case is only the partition key (the attribute Name).
So you have to modify either the table to set Id as partition key, or create a secondary global index to accomplish that:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html
This is the screenshot of my firestore structure
I want to get the data from my model stored in my firestore documents to my local variable
final EmployeeModel model = new EmployeeModel();
firebaseFirestore.collection("USERS").document(firebaseUser.getUid()).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
String username = documentSnapshot.getString(model.getUsername());
String email = documentSnapshot.getString(model.getEmail());
String location = documentSnapshot.getString(model.getLocation());
String phonenumber = documentSnapshot.getString(model.getPhonenumber());
String genderS = documentSnapshot.getString(model.getGender());
// Map<String, Object> userInfo = documentSnapshot.getData();
fragmentname.setText(username);
welcomeUser.setText(email);
employeeID.setText("1610225");
city.setText(location);
number.setText(phonenumber);
gender.setText(genderS);
} else {
Toast.makeText(getActivity(), "Document does not exist", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Error ", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
please correct my syntax I'm really new at this
This is EmployeeModel.class
And please show how to pass the .getUsername to a variable String username
public class EmployeeModel {
public static final String MFIELD_USERNAME = "username";
public static final String MFIELD_EMAIL = "email";
public static final String MFIELD_PASSWORD = "password";
public static final String MFIELD_LOCATION = "location";
public static final String MFIELD_PHONENUMBER = "phonenumber";
public static final String MFIELD_GENDER = "gender";
public static final String MFIELD_TYPE = "type";
private String username;
private String email;
private String password;
private String location;
private String phonenumber;
private String gender;
private String type;
private #ServerTimestamp Date timestamp;
public EmployeeModel() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public EmployeeModel(String username, String email, String password, String location, String phonenumber, String gender, String type, Date timestamp) {
this.username = username;
this.email = email;
this.password = password;
this.location = location;
this.phonenumber = phonenumber;
this.gender = gender;
this.type = type;
this.timestamp = timestamp;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}}
This is my EmployeeModel.class
and my Firestore screenshot, please help! Thank you
what you are missing is to get the model from the document
if(documentSnapshot.exists()){
EmployeeModel model = documentSnapshot.toObject(EmployeeModel.class);
//
just add the line after if statement to your existing code the rest seems fine.
I would like to find the data of all the users and sum of their scores on particular questions and find the highest rank
Now I can walk through the data users data but not through the questions node.
How do read all the data
This is how I have created my POJO :
private String id;
private String name;
private String contact;
private String email;
private String password;
private int score;
private String dob;
private String profession;
private String random;
private String status;
private String fbId;
private UserPuzzleDetails userPuzzleDetails;
public User() {
}
public User(String id, String name, String contact, String email, String password, int score,
String dob, String profession, String random, String status, String facebookid, UserPuzzleDetails userPuzzleDetails1) {
this.id = id;
this.name = name;
this.contact = contact;
this.email = email;
this.password = password;
this.score = score;
this.dob = dob;
this.profession = profession;
this.random = random;
this.status = status;
this.fbId = facebookid;
this.userPuzzleDetails = userPuzzleDetails1;
}
public User(String id, String name, String contact, String email, String password, int score,
String dob, String profession, String random, String status, String facebookid) {
this.id = id;
this.name = name;
this.contact = contact;
this.email = email;
this.password = password;
this.score = score;
this.dob = dob;
this.profession = profession;
this.random = random;
this.status = status;
this.fbId = facebookid;
}
public User(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getContact() {
return contact;
}
public String getDob() {
return dob;
}
public String getProfession() {
return profession;
}
public String getRandom() {
return random;
}
public UserPuzzleDetails getUserPuzzleDetails() {
return userPuzzleDetails;
}
public void setUserPuzzleDetails(UserPuzzleDetails questions) {
this.userPuzzleDetails = questions;
}
public String getStatus() {
return status;
}
public String getFbId() {
return fbId;
}
public void setFbId(String fbId) {
this.fbId = fbId;
}
Now I have used this function to retrieve the data but it is not logging.
How should I go by this data iterate through it.
private void getAllRank() {
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
final Query query = databaseReference.orderByChild("score").limitToLast(10);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userlist = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
User score = postSnapshot.getValue(User.class);
userlist.add(new User(score.getId(), score.getName(), score.getContact(), score.getEmail(),
score.getPassword(), score.getScore(), score.getProfession(), score.getDob(), score.getRandom(), score.getStatus(), score.getFbId(),score.getUserPuzzleDetails()));
Log.e(TAG, "onDataChange: "+userlist );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I am trying to retrieve data from mongodb via spring framework.
At first I made return type Map<String, Object>, but I decided to change to User value object.
Below is the class for User VO
#Document(collection = "user")
public class User {
#Id
#Field(value="id")
private String id;
#Field(value="name")
private String name;
#Field(value="password")
private String password;
#Field(value="professional")
private String professional;
#Field(value="email")
private String email;
#Field(value="gravatar")
private String gravatar;
#PersistenceConstructor
public User(String id, String name, String password, String professional, String email, String gravatar) {
super();
this.id = id;
this.name = name;
this.password = password;
this.professional = professional;
this.email = email;
this.gravatar = gravatar;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfessional() {
return professional;
}
public void setProfessional(String professional) {
this.professional = professional;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGravatar() {
return gravatar;
}
public void setGravatar(String gravatar) {
this.gravatar = gravatar;
}
};
and Here is #repository to retrieve data
#Repository
public class MongoMemberDao implements CommonDao<String, Map<String, Object>, Exception> {
#Autowired
MongoTemplate template;
final String COLLECTION_NAME = "user";
#SuppressWarnings("unchecked")
#Override
public Map<String, Object> read(String key) throws Exception {
Query findQuery = new Query();
findQuery.addCriteria(Criteria.where("id").is(key));
return template.findOne(findQuery, Map.class, COLLECTION_NAME);
}
public User readByDocument(String id) throws Exception {
Query findOneQuery = new Query();
findOneQuery.addCriteria(Criteria.where("id").is(id));
return template.findOne(findOneQuery, User.class, COLLECTION_NAME);
}
};
read method returns fine, but readByDocument does not(returns null not User instance). I read official document. But I do not get any clue of it.
FYI, The parameter Query looks same for both.
Query: { "id" : "system"}, Fields: null, Sort: null
I want to know why readByDocument returns null
Thanks.
---- Edit
Follow is my Database Config
#Configuration
public class MongoConfig extends AbstractMongoConfiguration {
private final String MONGO_URL = "127.0.0.1";
private final Integer MONGO_PORT = 27017;
#Override
protected String getDatabaseName() {
return "tfarm";
}
#Override
// #Bean
public Mongo mongo() throws Exception {
return new MongoClient(MONGO_URL, MONGO_PORT);
}
}
And I added this to WebApplictaionInitializer implement.
For current solution
I found follow on official site
A field annotated with #Id (org.springframework.data.annotation.Id)
will be mapped to the _id field.
A field without an annotation but named id will be mapped to the _id
field.
The default field name for identifiers is _id and can be customized
via the #Field annotation.
So I changed my VO like...
#Document(collection = "user")
public class User {
#Id
private ObjectId _id;
#Field(value="id")
private String id;
#Field(value="name")
private String name;
#Field(value="password")
private String password;
#Field(value="professional")
private String professional;
#Field(value="email")
private String email;
#Field(value="gravatar")
private String gravatar;
#PersistenceConstructor
public User(String id, String name, String password, String professional, String email, String gravatar) {
super();
this.id = id;
this.name = name;
this.password = password;
this.professional = professional;
this.email = email;
this.gravatar = gravatar;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfessional() {
return professional;
}
public void setProfessional(String professional) {
this.professional = professional;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGravatar() {
return gravatar;
}
public void setGravatar(String gravatar) {
this.gravatar = gravatar;
}
};
Added ObjectId. In alternative, just removing #Id annotation works fine too. However
#Id
#Field(value="id")
String id;
will not work. Thanks for help.
I try to save data to object user by gson but have an error:
java.lang.RuntimeException: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 911330 path $.assignedUser....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
at com.loopj.andro
User class is:
public class User {
#SerializedName("id")
int id;
#SerializedName("frontName")
String name;
#SerializedName("email")
String email;
#SerializedName("phoneNumber")
String phoneNumber;
#SerializedName("pesel")
String pesel;
#SerializedName("readableAdress")
String adress;
#SerializedName("avatar")
String avatar;
#SerializedName("city")
String city;
}
and code where I use gson:
User user = new User();
String response = new String(responseBody, "UTF-8");
Gson gson = new Gson();
user = gson.fromJson(response, User.class);
Problem is in the structure of the string response?
It seems that your JSON string is malformed. You can try this tool to validate it before parsing it with GSON.
https://jsonformatter.curiousconcept.com/
User Class:
public class UserData {
private int id;
private String name;
private String email;
private String phoneNumber;
private String pesel;
private String address;
private String avatar;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Now parse it like this:
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
Gson gson = new Gson();
response = gson.fromJson(br, User.class);