after string formatting method result changes - java

I'm using force-rest-api to do queries to salesforce and retrieve json answer and make java object.
public class SomeObject {
#JsonProperty("field")
private String field;
#JsonProperty("list")
private List<AnotherObject> list;
}
When I query string plainly - it returns correct result.
String requestQuery1 = "SELECT ... ='1111'";
return forceApi.query(requestQuery, clazz); // both field and list have data
But when add wildcard and use string format to create parametrized query - it returns incorrect result
String requestQuery = "SELECT ... ='%s'";
requestQuery = String.format(query, (Object[]) queryParams); // array of parameters. usually new Object[] { 1111 }.
return forceApi.query(requestQuery, clazz); // field is not null, list is null
I tried to check strings using
assert requestQuery1.equals(requestQuery);
but they are the same. When I put requestQuery manually using debug and set its value
"SELECT ... ='1111'"
It works fine.
But why it doesn't work when I use formatting? What's the problem?

Related

Error when passing List/Set of Strings to be Used in an "IN" clause in a query: Can't infer type

I am attempting to pass an array of string values so that said array of strings can be used in an "IN" clause like so with Java/PostgreSQL:
Sample query (contained in a string variable):
private static final String strSQLQueryAcceptingAnArray = "SELECT count(*) FROM sometable WHERE clm IN (:arrStringValues);";
public List<SampleReturnObject> getInClauseResults(List<String> lstStringValues) {
Set<String> setStringValues = new HashSet<String>(lstStringValues);
return this.query(strSQLQueryAcceptingAnArray, previouslyDefinedRowMapper, new Object[] { setStringValues });
}
However, when I run this, I get the following error message:
Can't infer the SQL type to use for an instance of ors.springframework.jdbc.namedparam.MapSQLParameterSource. Use setObject() with an explicit Types value to specify the type to use.
How can I pass a list/array of strings to use in an "IN" clause in PostgreSQL using Java and Spring Framework?
You can use a NamedParameterJdbcTemplate with SqlParameterSource like this:
private static final String strSQLQueryAcceptingAnArray = "SELECT count(*) FROM sometable WHERE clm IN (:arrStringValues)";
#Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public List<SampleReturnObject> getInClauseResults(List<String> lstStringValues) {
Set<String> setStringValues = new HashSet<String>(lstStringValues);
SqlParameterSource sqlParameterSource = new MapSqlParameterSource("arrStringValues", setStringValues);
return namedParameterJdbcTemplate.query(strSQLQueryAcceptingAnArray, sqlParameterSource, previouslyDefinedRowMapper);
}
Append the array values in a string by seperating the values using comma and then use that string in sql query IN clause.

Hibernate SQLQuery list method returns Object instead of object array

I have this strange behavior with Hibernate SQLQuery.list() method.
Following is the description of the issue:
I have a sql select query which retrieves only single column(group) from the database (i.e., select group from peopleGroup where groupid = 10)
And i'm recieving the result of the above list in List of Object array
i.e,
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
Ideally, the result should contain a list of object arrays but when I inspect, 0'th index of the result contains String object instead of an Object array.
However if I use more than one column let's say 2 columns in the select clause of the query I was able to see that 0'th index of the result as Object array i.e., Object[2]={"group","groupid"};
How do I get the Object array even if I have only one column mentioned in the select clause of the query?
Docs states:
List list()
Return the query results as a List. If the query contains multiple
results per row, the results are returned in an instance of Object[].
Convert it by yourself, like so.
List<Object[]> l = new ArrayList<>();
for(Object o : query.list()) {
Object[] arr = {o};
l.add(arr);
}
you can create a object mapper like below code
public class QueryMapper {
private String group;
//setter and getter
}
And you have to change your code like below
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
List<QueryMapper> list = new ArrayList<QueryMapper>();
for(Object[] object: result){
QueryMapper queryMapper = new QueryMapper();
if(object[0]!=null){
queryMapper.setGroup((String)object[2]);
}
list.add(queryMapper);
}
All i wanted is to fix the ClassCastException which was caught during the assignment of result.get(0) to the container i.e., container = result.get(0);
Since the value returned by mentioned list() method contains object in case of single column in the select clause of the query and i won't be allowed to cast from certain object to Object[](Object array).
Instead i have tried a work around like below
Already existing code
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
Object[] container = result.get(0);
now i have put condition like below to decide how to assign value to the Object[]
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
Object[] container = null;
if(result.get(0) instanceof Object[])
container = result.get(0);
else {
container = new Object[1];
container[0] = result.get(0);
}
The above solution seems working in my case !

extract Object parameters to POJO

How is it possible to get the [0], ..., [4] parameter's values of the Object below ?
The Object you see below is a result from EntityManager.createNativeQuery().
I would like to use the values to create a POJO. I know I could use EntityManager.createNativeQuery("SQL Query", MyPOJO.class), but it returns POJO only with ID, all other variables are null?! and I am interested in how to get object's parameters.
It's not possible to cast returned object to MyPOJO, because MyPOJO is a JPA Entity with references to another JPA Entities, and the returned object contains only IDs of another JPA Entities.
Thank you!
I solved it the following way:
Let nativeQuery to return me result as a List of Object[] and access the Object's values through index.
Here is my solution:
List<Object[]> executeObjects = null;
Query query = mgr.createNativeQuery("SQL Query");
executeObjects = (List<Object[]>) query.getResultList();
for (Object[] object : executeObjects) {
Long id = new Long((Integer) object[0]);
Long id2 = new Long((Integer) object[1]);
String desc = (String) object[2];
...
...
}

getting class cast exception while storing the content of list into set

I have fired the below hibernate query which is fetching the data perfectly but the return type is of List as shown below..
public List<Object[]> Extractingc()
{
Criteria criteria = session.createCriteria(IDetails.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("ter")); //is of string type
proList.add(Projections.property("sem")); //is of string type
proList.add(Projections.property("tid")); //is of long type in pojo *******
proList.add(Projections.property("def")); //is of string type
criteria.setProjection(proList);
List<Object[]> settlementIdList = criteria.list();
return sst;
}
now the problem comes in java code is that i am putting the result of above method in an an list further in code as shown below...
List<Object[]> ioaist = = ioabookandinstrumenthome.Extractingc();
now further i have created a set as in set i want to store the combination of all 4 parameters that is sem+tid+ter+def in the set that is I am doing as shown below...
Set<String> st = new HashSet<String>();
for (Object[] arr : ioabookandinstrumenthomelist)
{
s=((String) arr[0]+ (String) arr[1]+ (String) arr[2]+ (String) arr[3]); //*** getting class cast exception
st.add(s);
s=null;
}
but I am getting class cast exception as my parameter tid is long type which is not converted in string
Yes, you can't cast longs to Strings. You can however use String.valueOf()

JPA TypedQuery: Parameter value element did not match expected type

I am using JPA 2.0 and having following code in DAO layer:
public void test() {
String key = "status";
String[] statuses = {"A", "B"};
List<TestTable> result = find(key, statuses);
}
public List<TestTable> find(String key, Object valueArr) {
String sql = "SELECT nd FROM TestTable nd WHERE nd." + key + " IN :" + key;
TypedQuery<TestTable> query = entityManager.createQuery(sql, TestTable.class);
query.setParameter(key, Arrays.asList(valueArr))//***Error Line***
return query.getResultList();
}
In the above Error Line it throws following exception:
java.lang.IllegalArgumentException: Parameter value element [[Ljava.lang.String;#cbe5bc] did not match expected type [java.lang.String]
Why it expected type is String whereas actually it is String[] ? Please help!
Note: This is the extracted and simplified code from the generic routine I cannot change the 'Object valueArr' to String[] because its being used for others...
You've got a variable of type Object, and you're calling Arrays.asList. That means you've effectively called:
List<Object> values = Arrays.asList(new Object[] {valueArr});
So you're creating a list of a single element, where that element is an array. That's not what you want... you want a List<Object> with as many elements as you had to start with. The simplest way to do that is to change your parameter type:
public List<TestTable> find(String key, Object[] values)
...
query.setParameter(key, Arrays.asList(values));

Categories