How to get values from #result-set-1 in SimpleJdbcCall - java

When executing SimpleJdbcCall, I get two parameters #result-set-1, #update-count-1
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("name", "something");
Map<String, Object> resultFromProcedure = cstmt.execute(parameterSource);
#result-set-1 have variables
[{
id = 123,
name = "something",
accountnumber = 123456,
balance = 789999
}]
Everything is fine until I tried to access
resultFromProcedure.get("accountnumber")
Which getting null. The Question is how to access the values in #result-set-1

If I understand this correctly; Map<String, Object> resultFromProcedure consist of 2 entries having keys #result-set-1 and #update-count-1.
And the object of #result-set-1 is an object having 4 member variables. (If it is a String, then you'd need to convert the Json to a Java Object (Example))
Thus your call to resultFromProcedure.get("accountnumber") is trying to fetch an object using the key accountnumber, but the map doesn't contain that key. You need to first get the object for #result-set-1 e.g.
SomeDTO someDTO = resultFromProcedure.get("#result-set-1");
Then you can call
someDTO.getAccountNumber();

As there could be more than one result set, SimpleJdbcCall returns an object in the arraylist within another map marked as "#result-set-1". To access the values in it, try the following:
ArrayList arrayList = new ArrayList();
arrayList = (ArrayList) resultFromProcedure.get("#result-set-1");
Map resultMap = (Map) arrayList.get(0);
System.out.println("Account Number: " + resultMap.get("accountnumber"));

Related

Convert Object to Map<String,Object>in Java

I have a piece of code.
List<Bson> results = queryBuilder.createQuery(request, tableName, pivotValues);
Publisher<Employee> rows = getCollection().aggregate(results);
Flux.from(rows).map().collect(Collectors.toList());
inside map() function - I need to write a lambda expression to convert the Employee object to Map<String, Object> - String Key is field name and Object is field value. Employee has fields id and name.
Can someone help on this?

How to create multiple key value hashmaps from a resultset

I would like to create multiple hashmaps from a resultset.
The final result should be something like below;
{
slot_name = recommend,
data = 7,
},
{
slot_name = service,
data = Good,
},
{
slot_name = staff,
data = Great,
},
I tried as below:
HashMap<String, String> data = new HashMap<String, String>();
while (resultSet.next()) {
data.put("slot_name", resultSet.getString("name"));
data.put("data", resultSet.getString("param_value"));
}
But when I printout the value of the hashmap, I get one record as below
System.out.println(data);
{
slot_name = staff,
data = Great,
}
How can I achieve this? Someone assist, thank you
I would recommend to have a list and create a model class(instead of HashMaps) for "slot_name" and "data". Inside loop, construct object and add to the list. The reason, you are not getting as expected, is because, HashMap will have unique keys. So, for the same key when the value is again added, it will get updated.
class YourModel {
String slotName;
String data;
}
// inside loop
list.add(new YourModel(resultSet.getString("name"), resultSet.getString("param_value"));
A HashMap is a key value store. If you put the same key more than once, previous will be overwritten. This is the reason you saw only the last entry in the output.
if you want multiple maps, well create multiple ones.
Eg.,
List<HashMap<String,String> maps = new ArrayList();
while (resultSet.next()) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("slot_name", resultSet.getString("name"));
data.put("data", resultSet.getString("param_value"));
maps.add(data);
}

Getting values in hash map in Java

I am not a java developer, and this is not my homework or something. I am just in need of getting the values of these parameters: end & begin. this is what I have:
rs = [{}, {end=2013/11/5, begin=2012/11/6}]
I am wonder if I could get values like this:
rs[1].end
rs[1].begin
the source is:
protected QueryParameters prepareForm(final ActionContext context) {
final SearchErrorLogForm form = context.getForm();
Map<String, Object> rs = form.getValues();
System.out.println(rs);
/*the output is: {pageParameters={}, period={end=2013/11/5, begin=2013/11/6}} */
}
sorry, the rs type is hashmap.
That is not a valid statement.
A proper way of assigning an array would be:
String dates[] = {"2013/11/5","2012/11/6"};
String start = dates[0];
String end = dates[1];
There is a excellent tutourial at oracle docs
Okay, that is a Map containing two Maps as it seems. The first map named "pageParameters" is empty. The second one is named period and contains two items. The key "end" maps to the value "2013/11/5". The key "begin" maps to the value "2013/11/6".
To access the objects in the map you could do like this:
final Map<String, String> period = (Map<String, String>) rs.get("period");
final String begin = period.get("begin");
final String end = period.get("end");
If you would like to change a value in the map period you will need to overwrite the already existing one:
period.put("end", "NEW_END");
rs.put("period", period);
For further information, Oracle has great tutorials on Hashmaps.
you can do like following:
rs[1][0] for the first
rs[1][rs[1].length-1] for the last

Comparing java variables and printing

Suppose , I have some variables as :
String x="abcd";
String y="qwert";
String z="mnvji";
and more...
I take an input from user.
If user inputs 'x' , I print that string i.e. I print "abcd"
If user inputs 'y' , I print "qwert" and so on...
Is there any way to do it without switches or ifs??
Thank you,friends, in advance.
You could create a map from input string to result. Initialize the map:
Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
And when you want to print the result from the input from the user:
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));
Local variable names aren't available at runtime and reading field knowing it's name requires some reflection (see #amit's answer). You need a map:
Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Now just take value from that map:
String value = map.get(userInput);
value will be null if it doesn't match any of x/y/z.
As we can approach like that also,
String input[]=new String['z'];
input['X']="abcd";
input['Y']="qwert";
input['Z']="mnvji";
System.out.println(input['X']);
But it will come under some limitation
Map collection using key value pair implementation solve your problem .
put varible x,y,z as key and "abcd" ,.. as value.
Retrieve value from specific key according to input value.
Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
to get value
String value = map .get(inputValue).
Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));
will probably work.
Put your variable set into a HashMap as (key,value) pairs and just retrieve the value for the particular key when user inputs the key.
create an string array in which x,y,z should be indexes and store the content relatively ...
get the user input and pass it to the array as index ..you will get it..
If you really don't want to use switches or ifs (and I'd assume you include maps in that) then you'd have to use reflection to get the names of all the variables and decide which to print on them. Here's the basics:
Class yourClass = Class.forName("yourpackagename.YourClassName")
Field[] allFields = yourClass.getDeclaredFields();
String[] fieldNames = new String[allFields.length];
for(int i = 0; i < fieldNames.length; i++)
{
fieldNames[i] = allFields [i].getName();
}
//Get name of field user wants to display, and look it up in
//the fieldNames array to get the index of it, store this index
Object instance = yourClass.newInstance();
System.out.println(allFields[indexToDisplay].get(instance));
Of course, this could well be overkill.
If you have no choice but using object variables (fields) and not a Map as suggested by other answers - you might want to use reflection, and specifically the Class.getField() and Class.getDeclaredField() methods-
Field f = MyClass.class.getDeclaredField("x");
System.out.println(f.get(myObject));
Where MyClass is your class name and myObject is the object you want the value from.
Note that with this approach - you cannot add fields - you can only get existing ones.

How to get a java.util.Map from id to string prop in couchdb using ektorp

I'm having trouble dealing with what I thought would be a simple problem. Basically, I need a java.util.Map<String, String>, where ids end up being the map keys, and someField of my document ends up in the values.
I'm really really stuck on this, which greatly surprises me. I've tried writing a separate view:
#View(map="function(d) { if (d.someField) { emit(d.someField, null); } }", name = "someField")
and then use the following Java:
public Map<String, String> getSomeFields() throws JsonParseException, JsonMappingException, IOException {
ViewQuery q = new ViewQuery().designDocId("_design/" + entity.getSimpleName()).viewName("someField");
String result = StreamUtils.inputStreamAsString(db.queryForStream(q), false);
TypeReference<Map<String, String>> mapTypeRef = new TypeReference<Map<String,String>>() {};
// mapper is a Jackson ObjectMapper
return mapper.readValue(result, mapTypeRef);
}
This is already really ugly, but it also doesn't actually work, as it seems the JSON results that queryForStream returns includes random other stuff, rather than just the result of the query. This causes the readValue call to throw an IOException.
I've also tried using reduce to generate a single object containing all these values, but the result of that is that Couch complains the reduce doesn't reduce enough...
I would do something like this:
ViewQuery query = ...
Map<String, String> map = new HashMap<String, String>();
for (ViewResult.Row row : db.queryView(query)) {
map.put(row.getId(), row.getKey());
}
return map;
You will need to pre parse the output from CouchDB as there is no way to avoid returning all of that metadata with the query.
Firstly, your view needs to emit the right data (the object id, and its value).
#View(map="function(d) { if (d.someField) { emit(d.id, d.someField); } }", name = "someField")
The form of the reply is a JSON object String => Object. I would start by mapping the entire reply to this, then selecting the object with the key "rows" which is a JSON Array. Each element in this array is another JSON Object with keys "id", "key", "value". You will then need to map each of these objects to a key value pair in your output.
public Map<String, String> getSomeFields()
throws JsonParseException, JsonMappingException, IOException {
ViewQuery q =
new ViewQuery().designDocId("_design/" +
entity.getSimpleName()).viewName("someField");
String queryRresult =
StreamUtils.inputStreamAsString(db.queryForStream(q), false);
TypeReference<Map<String, Object>> mapTypeRef =
new TypeReference<Map<String,Object>>() {};
TypeReference<List<Map<String,String>>> rowsTypeRef =
new TypeReference<List<Map<String,String>>>() {};
// Map of the top level results which includes the couch meta and the
// rows. We have to use object, because Each value is of a different
// type (string, ints, json objects)
Map<String,Object> topResultMap =
mapper.readValue(queryRresult, mapTypeRef);
// Once we have the top level result, cast the value for key "rows" as
// String, and parse it as a rows type, which is a list of maps.
List<Map<String,String>> rows =
mapper.readValue((String) topResultMap.get("rows"), rowsTypeRef);
// Finally iterator over that list pulling out the id and the value in
// the key and value for the results
Map<String,String> results = new HashMap<String,String>();
for (Map<String,String> row : rows)
results.put(row.get("id"), row.get("value"));
// And return them
return results;
}
Lastly, you need to make sure you don't have a reduce part of your CouchDB view. If you do, you must pass "reduce=false" through to couch.

Categories

Resources