I am using java 7 and jdbc template to query a integer array from postgresql.My code is as below:
#Autowired
private JdbcTemplate jdbcTemp;
String SQL = "select item_list from public.items where item_id=1";
List<Integer> ListOfitems=jdbcTemp.queryForList(SQL , Integer.class);
My item_list column is integer[] in postgresql.But when I try like thid it throws an error as Bad value for type int psql exception.
Any help is appreciated
You can use java.sql.Array.
If you want to get only integer array you can try like this
String SQL = "select item_list from public.items where item_id=1";
Array l = template.queryForObject(SQL, Array.class);
List<Integer> list = Arrays.asList((Integer[]) l.getArray());
Or use RowMapper
Foo foo = template.queryForObject(SQL, new RowMapper<Foo>(){
#Override
public Foo mapRow(ResultSet rs, int rowNum) throws SQLException {
Foo foo = new Foo();
foo.setName(rs.getString("name"));
foo.setIntegers(Arrays.asList((Integer[]) rs.getArray("item_list").getArray()));
return foo;
}
});
Class Foo:
class Foo {
private String name;
private List<Integer> integers;
public String getName() {
return name;
}
// ...
}
queryForList saves each row that you got as a result from your query as an element of a List. It doesn't take the list that is saved into a column and returns it for you.
From the documentation : "The results will be mapped to a List (one entry for each row) of result objects, each of them matching the specified element type."
At best you will get a List<List<Integer>> returned, but I'm not sure fi you can use List<Interger>.class as a parameter for the call.
Related
I have a mysql query in this format
SELECT * from xyz where (key1, key2) in (('val1', 'val2'), ('val3', 'val4'));
I'm using jdbi to make this query. How do I bind the list of tuples in jdbi ?
I was trying to use something like this
List<String[]> query = new ArrayList<>();
for(String key: vars.keySet()){
String[] entry = {key, vars.get(key)};
query.add(entry);
}
List<String> result = getBasicQuery() + " WHERE (key, val) in (<query>)".bindList("query", query);
Getting this error on using bind this way
No argument factory registered for '[Ljava.lang.String;#11fa461a' of type class [Ljava.lang.String;
It's actually quite easy to do this in JDBI3, but for some reason the solution isn't documented on jdbi.org.
Here it is:
List<String> result = handle.createQuery(getBasicQuery() + " WHERE (key, val) in (<query>)")
.bindMethodsList("query", query, List.of("getKey", "getValue"))
.mapTo(String.class)
.list();
Note that to use bindMethodsList() you'll need to have your query objects defined as instances of a class with public methods (ie. getters). Something like this would work just fine:
class Query {
String key;
String value;
Query(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
Alternatively, you can skip the getters by making the properties themselves public and using bindBeanList().
As #talon55 said, bindBeanList method is an alternative:
String QRY_STRING = "SELECT id FROM settlement_report WHERE (user_id, reference_id, has_type_id, record_type) IN (<conditions>)";
List<String> fieldsBean = Arrays.asList("userId", "referenceId", "hasTypeId", "recordType");
handle.createQuery(QRY_STRING)
.bindBeanList("conditions", records, fieldsBean);
I have a List ids populated by database query (Hibernate). The database
is PSQL. The ids column is bigint type.
Now the ids list is populated without any exception like this
List<Long> ids = getIds();//getIds returns List<Long>
but when I try to loop through the items on the ids list by
for (Long id : ids)
I get the exception
java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
The value is 206131954. I don't know why it can add the value to the list, but later there is the error when trying to go through the list.
public List<Long> getIds() {
List<Long> externalIds = new ArrayList<Long>();
List<Person> persons = repository.getPeople();
for (Person person : persons) {
List<Long> ids = repository.getIdentifications(person);
if (ids.size() > 0) {
externalIds.addAll(ids);
}
}
return externalIds;
}
public List<Long> getIdentifications() {
String q = "select person_id from relevantpeople";
Query query = entityManager.createNativeQuery(q);
return (List<Long>) query.getResultList();
}
Use List<BigInteger> instead of List<Long>
BigInteger is capable of holding bigger integer numbers than Long.
BigInteger holds (2^32)^Integer.MAX_VALUE;
Long holds (2^63)-1;
hi i'm working in a spring mvc project using spring data jpa, i have a nativeQuey in a interface that extends from JpaRepository, in that query i select a few values from diferent tables and i return a
ArrayList<Object>
i printed the value of that ArrayList and it content this :
[[Ljava.lang.Object;#1f634fe, [Ljava.lang.Object;#1361a15, [Ljava.lang.Object;#1c8c51c]
since the query return 3 rows with 7 values for each row i suspect that those object are 3 (lists) and every list have 7 fields i'm very sure that are strings and ints, i have this two imports in my class where i watn to cast the values.
import java.util.ArrayList;
import java.lang.Object;
my question is how can i cast these list with have 3 listw inside to get my values?
this is my class that extends JpaRepository
import java.util.ArrayList;
import java.lang.Object;
public interface I_GL_JE_Lines extends JpaRepository<C_GL_JE_LINES, Long>{
#Query(value ="select value1, value2, value3, value4, value5"
+ "from DB_Table, DB_Table2, DB_Table3"
+ "where id_value = 1 ",
nativeQuery = true)
public ArrayList<Object> queryWithValues();
the method in my service class MyServiceClass.java :
import java.util.ArrayList;
import java.lang.Object;
public ArrayList<Object> getQueryValues() {
ArrayList<Object> results = null;
results = serviceAutoWiredVariable.queryWithValues();
return results;
}
and my controller class where i try to get my values
#Autowired MyServiceClass_autoWiredServiceClassVariable;
#RequestMapping(value = "/getVaules", method = RequestMethod.GET)
public String getValues(Model model)
{
ArrayList<Object> objectlist = null;
objectlist = _autoWiredServiceClassVariable.getQueryValues(); <--i call my method here and it return the lists that have 3 lists inside with 7 or more values each
.... HERE i want an idea how to get those values or how to cast them
//i tried this but i gives me this exception
//java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.ArrayList
Iterator itr = objectlist .iterator();
Iterator innerIterator;
while(itr.hasNext())
{
ArrayList<Object> obj = (ArrayList<Object>) itr.next();
innerIterator= obj.iterator();
while(iteradorInterno.hasNext())
{
Object[] innerObj = (Object[]) innerIterator.next();
value = String.valueOf(innerObj[0]);
}
}
this line:
ArrayList<Object> obj = (ArrayList<Object>) itr.next();
gives me this exceptio:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.ArrayList
An Object[] cannot be cast to any other type (apart from Object). Period.
If you want your Object[] instances to be usable as lists then you need to either copy them to new List objects, or wrap them using Arrays.asList().
The other approach (in theory!) would be to convince JPA to map the rows in the resultset to something other than Object[]. However, my (limited) research didn't reveal a way to do that .... at least, using the Spring-data #Query annotation.
What I used is explicitly defining my class type in the query itself and created parameterized constructor in the custom object that includes all the attributes I want to load from query output.
So The repository class would look like this:
public interface CustomObjectDAO extends CrudRepository<CustomObject, Integer> {
#Query("SELECT new CustomObject(obj.attribute1, obj.attribute2,
obj.attribute3, obj.attribute4) from CustomObject obj where
obj.attribute2 not in ("SELECT obj2.id FROM
AnotherCustomObject obj2)")
List<CustomObject> findByCustomObject();
}
Here is how CustomObject would look like:
public class CustomObject{
private int attribute1;
private String attribute2;
private String attribute3;
private String attribute4;
public CustomObject(){}
public CustomObject(int attribute1, String attribute2, String attribute3, String attribute4, String attribute5){
this.attribute1 = attribute1;
this.attribute1 = attribute2;
this.attribute1 = attribute3;
this.attribute1 = attribute4;
this.attribute1 = attribute5;
}
//getters and setters
}
That way it will cast list to CustomObject without any explicit casting.
What the exception says is you are trying to convert an Object array to ArrayList. So to fix the issue you can use this line of code in your service class:
Object[] results = null;
results = serviceAutoWiredVariable.queryWithValues();
Since I am a late comer in this thread, I hope someone else will get the benefit. I faced the same problem and lost a day while working with custom #Query.
In your case, the Exception has occurred at the iterator. What you are getting from _autoWiredServiceClassVariable.getQueryValues() is an ArrayList of Array of Objects. And you are tring to convert an array of Objects to ArrayList of Objects which causes the problem. You would be able to get the values of the query result if you modify the iteration as below.
Iterator itr = objectlist.iterator();
while(itr.hasNext()) {
Object[] arrObj = (Object[])itr.next();
for(Object obj:arrObj) {
System.out.println(String.valueOf(obj));
}
}
I have a method which needs to return a list of Strings from a DB.
private static List<String> getUserForAccount(final String account) {
String sql = "SELECT NAME FROM CLIENTS WHERE ACCOUNT = ?";
}
I am unsure which jdbcTemplate method is the best to use for this situation. I don't think I can use queryForList() because the SQL has a parameter.
Any suggestions would be welcome .
Thanks
Check out the JdbcTemplate API. You argument that "I don't think I can use queryForList() because the SQL has a parameter" really doesn't make much sense. I think all the queryForList() takes parameters, which is the parameter Object[] args, as in
List<Map<String,Object>> queryForList(String sql, Object[] args, int[] argTypes
There are many overloaded methods for queryForList() but I think this is the one you want. Basically just pass your query, an array of arguments, which will only be account in your case, and pass the db Types (int) argument. Something like
public class SomeDaoImpl extends JdbcTemplate implements SomeDao {
private static final String NAME_BY_ACCOUNT =
"SELECT NAME FROM CLIENTS WHERE ACCOUNT = ?"
public List<Map<String, Object>> getUsernameByAccount(String account) {
return (List<Map<String, Object>>) queryForList(
NAME_BY_ACCOUNT,
new Object[] { account },
new int[] { Types.VARCHAR });
}
}
The key returns will be the name of the column. Then you can iterate the list of maps like
List<Map<String, Object>> result = someDao.getUsernameByAccount(account);
for (Map map : result) {
System.out.println(map.get("NAME"));
}
You may also find some interest in some of the overloaded query() methods, which take variations of PreparedStatementSetter and RowMapper. Look at the API I linked above
I want to call course name in combobox and print course Id which selected coursename How can I solve this problem?
public void coursename(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query= session.createQuery("select a.courseName,a.courseId from Semester e inner join e.course as a");
for (Iterator it = query.iterate(); it.hasNext();) {
Object row[] = (Object[]) it.next();
combocourse.addItem(row[0]);
}
session.close();
}
private void combocourseActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox combocourse = (JComboBox)evt.getSource();
Object row[] = (Object[])combocourse.getSelectedItem();
System.out.println("id"+row[1] );
}
By not trying to cast a String to an Object[]. Look at the return value of the methods you're using, and use variables typed appropriately to store those return values. JComboBox#getSelectedItem returns an Object (in this case apparently a String), not an array (of any kind). But in this line:
Object row[] = (Object[])combocourse.getSelectedItem();
...you're trying to cast it to be an Object[] (array of Object) so you can store it in an Object[]. You can't do that.
It seems like row should just be Object or String, not Object[], and that when you use it you should just use it directly, not as row[1]:
Object row = combocourse.getSelectedItem();
System.out.println("id"+row );
Or
String row = (String)combocourse.getSelectedItem();
System.out.println("id"+row );
In a comment you asked:
I called coursename in combobox but i should save course id in my database. How can I get courseId?
I don't know JComboBox. Fundamentally, you need to store something that contains both values (the ID and name) and then use that something when you get the selected item. Unless JComboBox has some functionality for this built in, you might need a simple class for that that holds the values and implements toString by returning courseName. Something vaguely like:
class CourseItem {
private String courseName;
private String courseId; // Or int or whatever
CourseItem(String courseName,String courseId) {
this.courseName = courseName;
this.courseId = courseId;
}
public String getCourseName() {
return this.courseName;
}
public String getCourseId() {
return this.courseId;
}
public String toString() { // For display
return this.courseName;
}
}
Then:
public void coursename() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("select a.courseName,a.courseId from Semester e inner join e.course as a");
for (Iterator it = query.iterate(); it.hasNext();) {
Object row[] = (Object[]) it.next();
combocourse.addItem(new CourseItem((String)row[0], (String)row[1]));
}
session.close();
}
private void combocourseActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox combocourse = (JComboBox) evt.getSource();
CourseItem item = (CourseItem)combocourse.getSelectedItem();
System.out.println("id" + item.getCourseId());
}
try:
Object row = (Object)combocourse.getSelectedItem();
System.out.println("id"+row );
You only add single objects into the combocourse, not arrays of objects.
combocourse.getSelectedItem(); in your case returns String and string cannot be cast to array of objects. If you want to get List of Objects, they use getSelectedObjects()