Convert Object to Map<String,Object>in Java - 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?

Related

how to get a particular field value from map object using java

I am trying to set manufacture price code ,that value is in my map
object but when I want to get getName() from map object I am not able
to get that particular value. If I use
ipcToMFPNameMap.getClass().getName()
this line of code to get particular value I get "java.util.HashMap" in
my manufacture price code filed for your reference I post my code what I tried to get the particular result
private Item getItemManufacturerPriceCodes(Item item) {
List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
List<String> priceCodeList = new ArrayList<String>();
for (ItemPriceCode ipc : itemPriceCodes) {
//get the string value from the list
priceCodeList.add(ipc.getPriceCode());
}
//pass this string value in query
List<ManufacturerPriceCodes>mpc = manufacturerPriceCodesRepository.
findByManufacturerIDAndPriceCodeInAndRecordDeleted(item.getManufacturerID(),priceCodeList,NOT_DELETED);
//Convert list to map
Map<String, ManufacturerPriceCodes> ipcToMFPNameMap = mpc.stream().collect(
Collectors.toMap(ManufacturerPriceCodes :: getPriceCode,Function.identity()));// Object
for (ItemPriceCode ipcs : itemPriceCodes) {
ipcs.setManufacturerPriceCode(ipcToMFPNameMap.getClass().getName());
}
item.getItemPriceCodes()
.removeIf(ipcs -> DELETED.equals(ipcs.getRecordDeleted()));
return item;
}
I got this type of Result
But I want this this type of Result
I get issue exact at this point
ipcs.setManufacturerPriceCode(ipcToMFPNameMap.getClass().getName());
my manufacture price code is a string type
Your Map contains ManufacturerPriceCodes objects keyed on their priceCode which is defined as a String. So you can get the name of an item in the Map as follows (where priceCode is a String).
String manufacturerPriceCodesName = ipcToMFPNameMap.get(priceCode).getName();
The ManufacturerPricesCodes appears to capture the price code as a String but Item has a List<ItemPriceCode>. You'll have to figure out how to map back and forth.

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

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"));

How to map the POJO with the database ResultSet if the columnNames and fieldNames is different using java Reflection?

I am working in dynamically mapping the values from Result Set to POJO using Java reflection. It is working, but if the column name is different from the field in pojo it is not getting mapped.
For ex: if my column name is ORD_ID and in my pojo it is orderId, the ord_id is not getting mapped with order id. Here is the logic i'm using below.Kindly suggest a solution or an idea. Thanks in advance !
int colCount = resultSet.getMetaData().getColumnCount();
for (int i = 0; i < colCount; i++)
{
columnNames.put(resultSet.getMetaData().getColumnName(i + 1).toLowerCase(), i);
}
List<T> results = new ArrayList<>();
while(resultSet.next())
{
T newObj = clazz.newInstance();
for (Field field : clazz.getDeclaredFields())
{
String fieldName = field.getName().toLowerCase();
if (columnNames.containsKey(fieldName))
{
final int index = columnNames.get(fieldName);
field.setAccessible(true);
field.set(newObj, resultSet.getObject(index+1));
}
}
results.add(newObj);
}
but if the column name is different from the field in pojo it is not
getting mapped
Obviously, that wouldn't work since your code is written for that very purpose when both names match so I don't understand the surprise element.
Only way out that I can think of is a secondary global map of field name to DB Column name and you refer to it once columnNames.containsKey(fieldName) is false. That map is a manual work and that manual work will always be there since only you as a developer know that which column maps to which field in the POJO. That can't be automated if both are different & external mapping needs to be fed to Java progarm.
That mapping can be kept in an external property file.
There are APIs like apache-commons-dbutils but again manual mapping wouldn't go away as you will have to provide that in your custom - org.apache.commons.dbutils.BeanProcessor
Something else can be done the lines of JPA entity generation tools where we attach something like below to POJO fields -
#Column(name = "ADDRESS_IND")
private String addressInd;
but that is again a manual work as far as mapping specification is concerned. I think, you can retrieve annotation value and construct your mapping.
How to get annotation class name, attribute values using reflection
I did something similar recently, it's very crude but it works.
// finalData format will be [List<String>,List<List<String>>] i.e [column names, column data]
List<Object> finalData = new ArrayList<Object>();
List<String> columnNames = new ArrayList<>();
// columnData will be list of lists, where inner list comprised of each row data and outer list comprised of such row objects.
List<List<String>> columnData = new ArrayList<List<String>>();
ResultSet rs = serviceDao.generateData(query);//returns result set based on query
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++ ) {
String columnName = rsmd.getColumnName(i);
columnNames.add(columnName);
}
finalData.add(columnNames);// first object of finalData object
//Iterate through result set for each row, get all the columns data which are present in column names
while(rs.next()) {
List<String> rowData = new ArrayList<String>();
for(int i=0;i<columnNames.size();i++) {
rowData.add(rs.getString(columnNames.get(i)));
}
columnData.add(rowData);
}
finalData.add(columnData); // Second object of finalData object
Edit 1: you can use rs.getString("column name") to retrieve any datatype as Strings.
Oracle docs says
Note that although the method getString is recommended for retrieving the SQL types CHAR and VARCHAR, it is possible to retrieve any of the basic SQL types with it. Getting all values with getString can be very useful, but it also has its limitations. For instance, if it is used to retrieve a numeric type, getString converts the numeric value to a Java String object, and the value has to be converted back to a numeric type before it can be operated on as a number. In cases where the value is treated as a string anyway, there is no drawback. Furthermore, if you want an application to retrieve values of any standard SQL type other than SQL3 types, use the getString method.

Any collection object to hold list of combination of more than 2 elements?

Is there a collection object or a approach to hold a combination of elements?
For instance, I need to create a list that contains the combination of the elements name, age, height and weight.
Creating an object for this is not a good idea in my case. Because the number of fields keep changing.
I need to create this list to pass to a query.
Any solution?
class MyContainer {
String someString;
int someInt;
}
List <MyContainer> myList = new List<>();
Something like that!?
I donĀ“t know exactly, what you mean by "Creating an object for this is not a good idea in my case". You could as an alternative create a List<Object> and put in whatever you have or even a List<List<Object>> if you want to have a List of a number of grouped objects.
The best approach would be to make an Object with all the possible elements in it.
class myObject {
String name;
Integer age;
Float weight;
// Etc
}
Or have a base class then have another class which extends this with additional elements
class myExtendedObject extends myObject{
String streetAddress;
String city;
// etc;
}
Then if you don't have an element set it to null... you could always build your query from the object itself by including a method to return your query, juct check if its null and not include in your query (Assuming you mean an sql style query)
public String buildQuery{
String query = "Select * from blahtable Where ";
query += (name != null)?" name = " + name : "";
// etc, or what ever your query needs to be
return query
}
Other wise you could just have a method which returns a map of your elements then you know what the type of each element is based on the key
public Map<String, Object> getElements{
Map<String, Object> myMap = new HashMap<String, Object>();
if(name != null)
myMap.put("Name", name);
// etc
return myMap
}
What about just using a Map for that and use attribute name as key (e.g. Weight )?
You can use any combination of attributes you want and it would be convenient to pass such collection to the query
Consider Enum map should you require more column names type safety

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

Categories

Resources