JdbcTemplate. IncorrectResultSetColumnCountException: Incorrect column count - spring

I use Spring JdbcTemplate to query list of several values:
List<String[]> tankNames = jdbcTemplate.queryForList(
"select name, country, level from tanklist", String[].class);
get the following error:
org.springframework.jdbc.IncorrectResultSetColumnCountException:
Incorrect column count: expected 1, actual 3
Why it expects 1 as I use String[]?
How I can get a list of values of several columns (maybe in an array of Strings) without creating an object of these 3 values?
My final goal to transform this response to a list of strings.

You can use following method instead to simplify your implementation
<T> List<T> query(String sql, RowMapper<T> rowMapper)
If you want to get list of String array (String[]) i.e. columns of each row are elements of a String array, use following
List<String[]> allTankNames = jdbcTemplate.query(
"select name, country, level from tanklist",
(rs, rowNum) -> new String[] {rs.getString(1), rs.getString(2), rs.getString(3)});
However, your code suggests you want to get one string per row having concatenated all columns, for that, use following
List<String> allTankNames = jdbcTemplate.query(
"select name, country, level from tanklist",
(rs, rowNum) -> String.format("%s %s %s", rs.getString(1),rs.getString(2), rs.getString(3)));

I did the following:
List<Map<String, Object>> allTankNames = jdbcTemplate.queryForList(
"select name, country, level from tanklist");
My goal was to transform this into a list of strings:
List<String> tankNamesWithInfo = allTankNames.stream().map(m -> (String) m.get("name") + m.get("country") + m.get("level")).collect(Collectors.toList());

Related

How to INNER JOIN a jsonb column with CriteriaBuilder

I've been researching a while about how can I implement an Inner Join using CriteriaBuilder, but the thing is that one of the arguments which both tables have in commons is located inside a jsonb column, so the question is:
How can I INNER JOIN 2 tables by an argument that is located inside a jsonb column called "data" with criteria?
I'll drop down the example code of what I currently have.
public final CriteriaQuery<TutenBookingMacarena> createRatedBookings(
MacarenaBookingSearchFilter filters,
Integer page,
Integer pageSize,
Security security
) {
final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaQuery<TutenBookingMacarena> criteria = builder.createQuery(TutenBookingMacarena.class);
final Root<TutenBookingMacarena> root_Booking = criteria.from(TutenBookingMacarena.class);
Join<TutenBookingMacarena, TutenCaseMacarena> rootJoin = root_Booking.join(String.valueOf(
builder.function("jsonb_extract_path_text",
String.class,
root_Booking.<String>get("data"),
builder.literal("caseId")
)
));
...
}
But when executing those lines of code I get an error message that says the named attribute can not be found. Any idea what's wrong here?

Room database: how to retrieve column names into list of strings?

I have a Room table named "addresses" with 15 columns. I retrieve one row and want to get values into List< String >, not List< Addresses >. Is that possible?
#Query("SELECT * FROM addresses WHERE myid= :id")
List<String> getAddressAsList(int id);
Moreover, is it possible to retrieve database table column names together with values into list of map <"column name","value"> like this?
#Query("SELECT * FROM addresses WHERE myid= :id")
List<Map<String, String> getAddressAsList(int id);
You can use a SupportSQLiteDatabase but not a Dao.
Say you have, in an activity,
db = yourRoomDatabase.getInstance(this);
i.e. you'd typically then use something like yourDao = db.getYourDao(); and then
myAddressList = dao.getAddressList();
You can then do:-
SupportSQLiteDatabase sdb = db.getOpenHelper().getWritableDatabase();
Cursor csr = sdb.query("SELECT * FROM address WHERE myid=?",new String[]{String.value(id)}
Then to get the list of column names in the Cursor you can use:-
val columnNames = csr.columnNames
To get the Map of columnnames and values you could use :-
val columnsAndValues: MutableMap<String,String> = mutableMapOf()
while (csr.moveToNext()) {
for (i: Int in 0..csr.columnCount) {
columnsAndValues.put(csr.columnNames.get(i),csr.getString(i))
}
}
csr.close()

How to get the data in query(search result of hql)?

I am a novice to use jdbc and I have some problems.
I use hql to search data in MySQL, and the result is Query type. I don't know how to get the data from the "Query".This is my code:
final String hql = "select app.appkey,app.type from " + getClassName() +
"app where app.appkey<>'no-appkey' group by app.type";
Query query = getEntityManager().createQuery(hql);
Thanks a lot.
You have to do the following:
final String hql = "select app.appkey,app.type from " + getClassName() + " app where app.appkey<>'no-appkey' group by app.type";
Query query = getEntityManager().createQuery(hql);
query.list(); //or query.getSingleResult();
query.list() will give a list of results.
query.getSingleResult() will give you a object.
You can check this.
If you are expecting a list of results, so:
List<Object[]> results = query.getResultList();
If you are expect one single result:
Object[] result = query.getSingleResult(); // if more than one result was found, this method will throw a NonUniqueResultException
If column information will be stored in a position of the Object array. Example:
String appKey = (String) result[0];
String appType = (String) result[1];
But work with Object array is not good. Try to use Dto, like explained here.

Elasticsearch get elements fulfilling two conditions

I have in db elements with following structure:
{
"id": 324214,
"modDate": "2014-10-01",
"otherInfo": {
..
..
}
}
Let's suppose that I have list of pairs [id, modDate]:
Map<String, String> idAndModDate
which contains f.e (324214, "2014-10-01"), (3254757, "2015-10-04")..
Now, I would like to use Java Api Elasticsearch QueryBuilder to build Query which in result give me list of all "ids" which are present in system but for who modDate is different as given.
Suppose that I have in database elements with following id/date pairs:
id, date
1, 2015-01-01
2, 2014-03-02
3, 2000-01-22
4, 2020-09-01
Now, I want to create query for
Map with following data:
Map<String, String> idDataPairs =[
(1, 2015-01-01)
(2, 2014-03-03)
(3, 2000-01-22)
(7, 2020-09-01)]
now I want create function like
List<String> ids = search(Map<String, String>) {
QueryBuilder.(sth).(sth) <--- thats what I'm asking about
}
which will return ids: 1, 3 because those ids exist in DB and dates from query are equal to dates in db respectively.
This is what you are looking for, more or less.
//build the test data in the map
Map<String, String> idDataPairs = new HashMap<String, String>();
idDataPairs.put("1", "2015-01-01");
idDataPairs.put("2", "2014-03-03");
idDataPairs.put("3", "2000-01-22");
idDataPairs.put("4", "2020-09-01");
//construct the query
BoolQueryBuilder should = QueryBuilders.boolQuery();
for(String id : idDataPairs.keySet()){
BoolQueryBuilder bool = QueryBuilders.boolQuery();
bool.must(QueryBuilders.termQuery("id", id));
bool.must(QueryBuilders.termQuery("modDate", idDataPairs.get(id)));
should.should(bool);
}
should.minimumNumberShouldMatch(1);
What i am doing is this:
For each of the Pairs, i am constructing a BoleanQuery called bool. This boolean query has two must conditions, that both the id and the date MUST match the document.
After constructing one bool Boolean Query, I add it to a parent BooleanQuery as well. This time, i say that the inner bool query should match, but its not required to. The final line says that at least one of these queries should match, if we want the document to match.
This structure is easier to understand, because must functions like AND and should functions like OR, but another way to do this is to use a TermsQuery, where we construct several TermsQuerys, and then add them to another parent BooleanQuery using should.
So, for the data
id, date
1, 2015-01-01
2, 2014-03-02
3, 2000-01-22
4, 2020-09-01
the above code will return the documents with ids 1,2,3

LINQ : How to check CONTAINS with multiple dynamic input values

I am facing a problem regarding a LINQ query.
I have multiple input values which is stored in List< string > variable.
I have to form a LINQ query which would have a where clause which check for the respective column with CONTAINS keyword. The issue I am facing is that List< string > can contain any number of values in it.
So i want to know how can i form a query which can read input values from collection object. and display the result.
Any suggestion would be appreciated.
Thanks in advance.
Linq extension method:
public static bool ContainsAny<T>(this IEnumerable<T> Collection, IEnumerable<T> Values)
{
return Collection.Any(x=> Values.Contains(x));
}
Then you can use like:
List<string> List1 = getStringList1();
List<string> List2 = getStringList2();
bool List2ItemsInList1 = List1.ContainsAny(List2);
Your question is not clear. Suppose you have three values X, Y and Z. If you want to fetch the results where a Column is either X, Y or Z, then habib-osu's answer will do this.
If you are looking for all records where a particular column contains X, Y and Z then the following should work
List<string> options = new List<string>();
options.Add("X");
options.Add("Y");
options.Add("Z");
var query = (from r in dc.Table select r);
foreach(var option in options)
query = (from r in query where r.Column.Contains(option) select r);
var list = query.ToList();
This will produce one sql query similar to the following
select * from Table where Column like '%X%' and column like '%Y%' and column like '%Z%'

Resources