Retrieve the entire row with ResultSet of a CQL query - java

I have set up a Cassandra connection through Java driver. And I want to retrieve an entire row as a collection. I want to get rid of using getString() or getInt() always. When I give a query saying select all columns in the users table using CQL. the entire result should be sent to a collection rather than a string. How do I achieve this?
I have done the following to retrieve the columns. It gives me the proper results. But I want to retrieve the entire row as a collection.
Outside the for loop I want to retrieve these fields as one object. How do I do this??
String name=null;
String age=null;
ResultSet results = session.execute("SELECT * FROM admin.users");
for (Row row : results) {
name=row.getString("firstname");
age=row.getString("age");
System.out.println("name::"+name);
System.out.pintl("age::"+age);
}

If you want to obtain all fields in a collection you could use getMap(..) function and you will get a Map with keys and values.
On the other hand, check new object Mapping API since version 2.1 and you can map a class directly from ResultSet with annotations in your entity class.

Related

How can I select a column by name in jooq, when result record has two columns of different tables with the same name?

I am using Jooq and as a result of a query with some joins I have a list of Record .
This record includes two columns with name "id" and I would need to select one of them.
This method has String as parameter and it is not failing when passing "id" (probably returning the first occurrence).
The other alternative I saw is to use the method that receives an int with the index. This would work ok but I would prefer to avoid it.
The best alternative I found on this case is to use the method that receives Field as parameter.
By using Field we can specify the table and column name so we are sure that we are selecting the column that we want.
So basically if we have table A and B both with "id" columns on the result of the query we can just define a field
final Field<UUID> bId = tableB.ID;
And then when processing the results we can access it by
query.fetch().forEach(r -> { UUID theId = r.get(bId); });

Select array fields from Hive table using JDBC

I have a Hive table which has column with array data type. I am using JDBC to select rows from the table.
SELECT col1 FROM hive_table WHERE condition = 'condition'
After receiving the resultset, I am using res.getArray() method for the specific array field while looping through resultset.
Array arrayCol = res.getArray(1);
This is throwing a "Method not supported" error. Is it valid to use getArray() method for such queries executed on Hive table?
Unfortunately, no. You can see getArray() method is not implemented in ResultSet class for Hive JDBC. The actual class name is HiveBaseResultSet and the source code is located here.
Depends on what type of values the array holds, a client program need to decode its value by itself. For example, a column of type array<string> is encoded as a single String object like `["VALUE1","VALUE2",...,"VALUEN"]'. And we can use getString() method and freely re-construct any object of type Array<String> or List<String>.
You can loop though the result set and add the column values to arraylist in java. See example below assuming that your table column is of String type.
List<String> list = new ArrayList<String>();
while (res.next()) {
list.add( res.getString(1));
}

spring data mongodb method query

Suppose my document contains two field - from and to. I want to fetch all the documents whose from is lessThanEqual the provided value and to is greaterthanEqual the provided value.
the way I can do that is
List<T> findAllByFromLessThanEqualAndToGreaterThanEqual(Integer from, Integer to)
I am using method query way to achieve it.
Now suppose I have a list of Integer, is there any efficient way to fetch the records in single query.
Something like instead of iterating over the list of Integer and firing the query again and again
List<T> list = someIntList
.stream()
.map(someInt -> someRepository.findAllByFromLessThanEqualAndToGreaterThanEqual(someInt, someInt))
.flatMap(Collection::stream).collect(Collectors.toList());
The above way will hit the database again and again, so is there any more efficient way to achieve it in a single query.

How do I create an object for Hibernate's query response?

Using an object that extends HibernateDaoSupport, I ran a query using this right here:
List<Object> trialList2 = getSession().createSQLQuery(trialQuery2).list();
Where trialQuery2 is just some query that returned a single row. I got back a list with one Object on it, which when inspected in Eclipse looks like this:
[some, random, data]
I'd like to create an Object that can accommodate what I got back from the query, but a simple Javabean object that can has those fields doesn't seem to work. Does anyone know what kind of object I would have to make to be able to access those values?
It would be actually Object[] not Object
List<Object[]> trialList2
Based on columns in your select query, you get values from index
Let us say, if your query is select firstname, lastname from employee;
Object[0] would be firstname
Object[1] would be lastname.
As per documentation :
These will return a List of Object arrays (Object[]) with scalar values for each column in the table
U can replace any class name for BEANCLASSNAME
List<BEANCLASSNAME> trialList2 = getSession().createSQLQuery(trialQuery2).setResultTransformer(new AliasToBeanResultTransformer(BEANCLASSNAME.class)).list();

How to get auto generated keys of a table while using java prepared statement Batch?

How to get auto generated keys of a table while using java prepared statement Batch? One way to do is to iterate the resultset that is returned? Is there is any other efficient way of doing it?
Use getGeneratedKeys() method from your Statement or PreparedStatement object to identify the new auto generated values. Iterate the returned ResultSet object to get the newly generated key values in the order of batch statements.
Edit: This call may throw java.sql.SQLFeatureNotSupportedException if the JDBC driver, that you are using, does not support this method.
According to me, you need to retrieve result set by prepared statement and from you need to get that auto generated key fieldname.
Suppose auto generated field name is "ID" and tablename is student
then you need to retrieve resultset by query like select id from student.
then you will get object of resultset which contains Id.
To retrieve,
resultsetobj.getString(0);
OR
resultsetobj.getString("Id");
i think that it is really dangerous to set a record's id (numeric-autonumber) outside the RDBMS, it may cause a conflict if there is another user doing the same execution as you do at the same time.
if you want to know what is the id of the next persisting record, you have to re-query it just after persisting it. Unless you are going to use ORM to help you doing this. by using ORM, you won't need to re-query, just persist the record and you'll get the id assigned to it,.
hope this help,.
I think you need to use the OUTPUT clause,like this:
--====== make our test table to insert to
Create Table InsertIDTst(
ID int identity primary key
, ColName nvarchar(255)
, object_id int);
GO
--====== make a table variable to hold the new ID's
Declare #IDList Table(ID int);
--====== insert a bunch of rows,
-- and save the new IDs at the same time
INSERT into InsertIDTst(ColName, object_id)
Output INSERTED.ID Into #IDList(ID)
Select name, object_id
From sys.columns
--====== show that we have the new IDs
SELECT * from #IDList

Categories

Resources