I'm trying to retrieve all elements in database and display in webpage.But with my code it able to retrieve only one row element. Problem is, it retrieves all element but it adds the last row element to the object. I think all elements retrieved first are overwritten Because of that it displays last row element. Can anyone tell me how add all row elements to the JSON object. Please help me.
code :
while(rs.next()){
ImageFile.setName(rs.getString("imagename").trim());
ImageFile.setDisc(rs.getString("imagedisc").trim());
ImageFile.setImageid(rs.getInt("imageid"));
ImageFile.setalbumid(rs.getInt("albumid"));
byte imageData[] = rs.getBytes("imagethumb");
String encoded = DatatypeConverter.printBase64Binary(imageData);
ImageFile.setThumb(encoded);
byte image1Data[] = rs.getBytes("imagethumb");
String encoded1 = DatatypeConverter.printBase64Binary(image1Data);
ImageFile.setFull(encoded1);
}
The complete source code is in this question
Please help me........Thanks....
Use a list Collection to keep all the row-values of db, like - List<ImageFileInfo> which denotes List containing of ImageFileInfo Objects . And then serialize the list to json String.
List<ImageFileInfo> imageFileList = new ArrayList<ImageFileInfo>();
while(rs.next()){
ImageFileInfo info = new ImageFileInfo();
info..setName(rs.getString("imagename").trim());
...
imageFileList.add(info);
}
Json serialization -
Type typeOfList= new TypeToken<List<ImageFileInfo>>(){}.getType();
String s = gson.toJson(imageFileList , typeOfList);
Related
Below is the snapshot of my API XML response
<Plaintiff>
<PlaintiffName>SEB B.A.
</PlaintiffName>
<PlaintiffName>SEB??
</PlaintiffName>
</Plaintiff>
I want to extract all the PlaintiffName under the Plaintiff node.
Code:
String caseResponseText = response.getResponseText()
def xmlResult = new XmlSlurper().parseText(caseResponseText)
def plaintiff = xmlResult.Case.Plaintiff.PlaintiffName[0].text()
The above one i got the result of first plaintiff name / second plaintiff name. But how should i looping thru this node and get all the palintiff value dynamically?
Because response may have only one plaintiff or more than one, so I need to parse dynamically and get all the values thru looping
Simply loop over the nodes:
def plaintiffs = xmlResult.Case.Plaintiff.PlaintiffName
for (plaintiff in plaintiffs) {
// do something with plaintiff
}
I have a Document that has an array field called listsOfItems. Its contents are Documents and they all contain another array field called setOfItems, which is composed of Document.
So the structure is like listsOfItems(Array of Documents) > setOfItems(Array of Documents) > Items(Documents)
Each Document in listsOfItems has a listId field which is used to uniquely identify it's contents.
Each Document in setOfItems has a itemId field which is used to uniquely identify it's contents.
I want to change the value of a field inside a Document of setOfItems given the listId and itemId.
Currently, I'm trying to do it like this:
final var filter = Filters.and(Filters.eq("accessDetail.email", email),
Filters.eq("listsOfItems.listId", listId),
Filters.eq("listsOfItems.$.setOfItems.itemId", itemId));
final var updateQuery = Updates.set("listsOfItems.$.setOfItems.obtained", BsonBoolean.TRUE);
usersCollection.findOneAndUpdate(filter, updateQuery)
The query doesn't match any Document
I cannot access the elements in the setOfItems by directly accessing them by index because they are ordered by other indexes and not according to their itemId field.
What is the right query for performing the update given the condition?
EDIT1
I have replaced my filter to:
final var filter = Filters.and(Filters.eq("accessDetail.email", email),
Filters.elemMatch("listsOfItems",
Filters.eq("listId", listId)),
Filters.elemMatch("listsOfItems.setOfItems",
Filters.eq("itemId", itemId)));
Now I get the error message: 'Cannot create field 'obtained' with the correct sub-document that it should make changes in.
The issue boils down to the updateQuery.
To do this, you need to make use of arrayFilters.
Document filter = new Document("base-doc-field","<value>");//query for base doc
//fields if any
Document updateDoc = new Document("$inc",
new Document("listOfItems.$[elem].setOfItems.$[elem1].fieldName","value to
update"));
//prepare array filters.
List<Bson> arrayFilters = new ArrayList<>();
arrayFilters.add(new Document("elem.listId","<list_id>"));
arrayFilters.add(new Document("elem1.itemId","<item_id>"));
//prepare update options, and set these array filters to update options.
UpdateOptions options = new UpdateOptions().
arrayFilters(filterArr).bypassDocumentValidation(true);
//execute update method.
collection.updateOne(filter,updateDoc,options);
Visit https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#update-nested-arrays-in-conjunction-with
I have trying to get the string value from the arraylist values.
But In my arraylist if the value already exists , just update the count . otherwise need to create a new one. Here values are updating, but how can i create a new one element if the name didn't match with the arraylist element name? Please tell me , how can i verify the element(GlobalData.getCRole) already exists in the arraylist.
In this code the arraylist name is GlobalData.getrolecount
GlobalData.getCRole = item.getRole_name();
if (GlobalData.getrolecount.size() > 0) {
for (int i = 0; i < GlobalData.getrolecount.size(); i++) {
Role getrc = GlobalData.getrolecount.get(i);
Role getrcverify = new Role();
getrcverify.setRole_name(GlobalData.getCRole);
if (getrc.getRole_name().equalsIgnoreCase(GlobalData.getCRole)) {
String inccount = GlobalData.getrolecount.get(i).getCount();
int getcount = Integer.parseInt(inccount) + 1;
getrc.setCount(Integer.toString(getcount));
}
}
} else {
Role getrc = new Role();
getrc.setRole_name(GlobalData.getCRole);
getrc.setCount("1");
GlobalData.getrolecount.add(getrc);
}
Adding to #GabeSechan's answer, here's a snippet that would help you:
//let's say you store your data in a Map called myHashMap
String keyToMatch = "your_key_here"; // replace this line with whatever code you use to get your key
if(myHashMap.containsKey(keyToMatch)) // Check if your map already contains the key
{
int val = myHashMap.get(keyToMatch);
myHashMap.put(keyToMatch, val++); // Can be shrunken to a single line
}
else
{
myHashMap.put(keyToMatch, 1); // If it doesn't exist in the map, add it (with count 1)
}
This code can be shrunken much more because Map<> is a very robust tool. But I've written it in a way similar to your implementation so you can understand it better.
Let me know if you need further explanation or help trying to init myHashMap.
I'd use a different data structure. A list isn't what you want. You want a Map (probably a HashMap) of strings to Count, or of strings to Roles. That way you can do O(1) searches to see if a role already exists, rather than an O(n) walk of the list, and checking if the role exists is a simple check to see if get returns null.
How to compare list of records against database? I have more than 1000 records in list and need to validate against database. How to validate each record from list to database? Select all the data from database and stored in list, then have to compare the values? Please advise...
The below code lists values to validate against database.
private void validatepart(HttpServletRequest req, Vector<String> errors) {
Parts Bean = (Parts)req.getAttribute("partslist");
Vector<PartInfo> List = Bean.getPartList();
int sz = partList.size();
for (int i = 0; i < sz; i++) {
PartInfo part = (PartInfo)partList.elementAt(i);
System.out.println(part.getNumber());
System.out.println(part.getName());
}
}
This depends on what you mean by compare. If it's just one field then executing a query such as select * from parts_table where part_number = ?. It's not that much of a stretch to add more fields to that query. If nothing is returned you know it doesn't exist.
If you need to compare and know exactly which values are different then you can try something like this
List<String> compareObjects(PartInfo filePart, PartInfo dbPart) {
List<String> different = new LinkedList<String>();
if (!filePart.getNumber().equals(dbPart.getNumber())) {
different.add("number");
}
//repeat for all your fields
return different;
}
If your list of objects that you need to validate against the database includes a primary key, then you could just build a list of those primary key values and run a query like:
SELECT <PRIMARY KEY FIELD> FROM <TABLE> WHERE <PRIMARY_KEY_FIELD> IN <LIST OF PRIMARY KEYS> SORT BY <PRIMARY KEY FIELD> ASC;
Once you get that list back, you can compare the results. My instinct would be to put your data (and the query results too) into a Set object and then call removesAll() to get the items not in the database (reverse this for items in the database but not in your set):
yourDataSet.removeAll(queryResults);
This assumes that you have an equals() method implemented in your PartInfo object. You can see the Java API documentation for more details.
I have managed to fetch a string from the database and be able to store some of its elements in variable so as to reduce the number of times the app interacts with the databse. However I wanted the first element to be fetched from the database to be stored in a list but it keeps generating an error when i parse the string to a new list. please help
//String fetched from the database
final String[] rec = split(myresult,seperator);
//loc is the first String to be parsed to a String..
//desc is the 2nd string to be parsed to a textarea
//coords 3rd string which contains coordinates..
String loc=rec[0];
final String desc=rec[1];
String coords=rec[2];
//ERROR IS GENERATED HERE!!!
listmboya=new List(loc);
//Separate the coordinates in the string...
String seperator2=",";
String [] coordinates=split(coords,seperator2);
String lat=coordinates[0];
String lot=coordinates[1];
//convert them to floats..
item1=Float.parseFloat(lat);
item2=Float.parseFloat(lot);
list is an iterface,
try
listmboya=new ArrayList();
listmboya.add(loc);
You cannot instantiate List object. Its an interface and not a class. You need an ArrayList which is the implementing class of List and also, there is no constructor for ArrayList that takes String as parameter.
So, you need to create an ArrayList<String> and then add your String to it.
So you need to do it like this: -
List<String> listmboya=new ArrayList<String>();
listmboya.add(loc);
Make sure to declare your listmboya as List<String>
UPDATE: - Post some more Code in case this doesn't work. We need to look at more of them.
List is the abstract class, can not be instantiated.
just try like this:
listmboya = new ArrayList<String>();
listmboya.add(loc);