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

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()

Related

How to update room database and How to get the insert status is working or completed?

The first:
I've got dataList from retrofit And insert Room Database.
I want to change dataList(Like insert a element). My Room Database can work because I used OnConflictStrategy.REPLACE. but when I delete dataList some elements, My Room Database can not delete elements.
Dao:
#Insert (onConflict = OnConflictStrategy.REPLACE)
suspend fun insertData(dataList : List<Data>)
Entity:
#Entity
data class Data(
#PrimaryKey val Id : Long,
val Fl : String,
val FlMc : String,
val Dm : String,
val Mc : String,)
ViewModel:
fun insertData(dataList: List<Data>) = viewModelScope.launch {
dataRepository.insertData(dataList)
}
//get data from server
fun getData():LiveData<List<Data>>
Activity:
dataViewModel.getData().observer(this){
dataViewModel.insertData(it)
}
How to resolve this situation except DELETE ALL THEN INSERT
The second:
I want to use a progressbar to indicate that I am inserting dataList
How to get the insert status is working or completed
If I understand correctly, you issue is that you cannot delete because you are building a DataList item but don't know the primary key value as it's generated.
As you haven't shown the DataList entity then assuming it is like:-
#Entity
data class DataList(
#PrimaryKey(autogenerate = true)
val id: Long,
val othercolumns: String
....
)
and if you change from suspend fun insertData(dataList : List<Data>) to suspend fun insertData(dataList : List<Data>): List<Long> (i.e. added the List as the result)
Then you have the values of the id column in the result. In the case above the value is the value of the id column.
If the #PrimaryKey is not an integer type e.g. a String then the long returned WILL NOT be the value of the primary key. It will be a special value known as the rowid.
In short using an integer with primary key makes the column an alias of the rowid. if not an integer primary key then it is not an alias BUT the rowid still exists.
You can still use the rowid to access a specific row as the rowid MUST be a unique value. e.g. (again assuming the above) you could have an #Query such as
#Query("SELECT * FROM the_datalist_table WHERE rowid=:rowid")
suspend fun getDataListById(rowid: Long)
Only of use if you know the rowid though.
You could get rowid's say by using
#Query("SELECT rowid FROM the_datalist_table WHERE othercolumns LIKE :something")
suspend fun getRowidOfSomeDataLists(something: String): List<Long>
still not of great use as the selection criteria would also be able to provide a list of Datalists.
Additional re the comment:-
How to use in viewModel or Activity?
As an example you could do something like :-
fun insertData(dataList: List<Data>) = viewModelScope.launch {
val insertedDataList: ArrayList<Data> = ArrayList()
val insertedIdList = dataRepository.insertData(dataList)
val notInsertedDataList: ArrayList<Data> = ArrayList()
for(i in 0..insertedIdList.size) {
if (insertedIdList[i] > 0) {
insertedDataList.add(
Data(
insertedIdList[i], //<<<<< sets the id as per the returned list of id's
dataList[i].Fl,
dataList[i].FlMc,
dataList[i].Dm,
dataList[i].Mc)
)
} else {
notInsertedDataList.add(
Data(
insertedIdList[i], //<<<<< sets the id as per the returned list of id's WILL BE -1 as not inserted
dataList[i].Fl,
dataList[i].FlMc,
dataList[i].Dm,
dataList[i].Mc
)
)
}
}
val notInsertedCount = notInsertedDataList.size
val insertedCount = insertedDataList.size
}
So you have :-
insertedDataList an ArrayList of the successfully inserted Data's (id was not -1) with the id set accordingly.
notInsertedDataList an ArrayList of the Data's that were not inserted (id was -1) id will be set to -1.
insertedCount an Int with the number inserted successfully.
notInsertedCount and Int with the number not inserted correctly.
DELETE ALL
To delete all rows, unless you extract all rows you can't use the convenience #Delete, as this works on being provided the Object (Data) and selecting the row to delete according to the primary key (id column).
The convenience methods #Delete, #Update, #Insert are written to generate the underlying SQL statement(s) bases upon the object (Entity) passed.
e.g. #Delete(data: Data) would generate the SQL DELETE FROM data WHERE id=?, where ? would be the value of the id field when actually run.
The simpler way to delete all columns is to use the #Query annotation (which handles SQL statements other than SELECT statements). So you could have.
#Query("DELETE FROM data")
fun deleteAllData()
note that this does not the return the number of rows that have been deleted.

JdbcTemplate. IncorrectResultSetColumnCountException: Incorrect column count

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

Spring Data - Custom DTO Query with filtering

I have a complexe application and I need to retrieve and filter 1000~5000 object for an xls export. Each object having multiple eager relationship (I need them for the export).
If I retrieve all the objects and their relationship as it is, I got some stackoverflow error.
Generaly when I need to make a big export, in order to make it efficient I use a DTO object with an #Query like this :
public interface myRepository extends JpaRepository<Car, Long> {
#Query("SELECT new com.blabla.myCustomObject(p.name, p.surname, c.model, c.number ...) "
+ "FROM Car c "
+ "LEFT JOIN c.person p "
+ "WHERE ... ")
List<myCustomObject> getExportCustomObject();
}
The problem is that the #Query is static and I want to add dynamic filter to my Query (Specifications, Criteria or some other system...)
How to do it ?
Specification cannot be used because this is only the where clause.
But you can use Criteria API. Here's an example. The BasicTeacherInfo is the DTO:
CriteriaQuery<BasicTeacherInfo> query = cb.createQuery(BasicTeacherInfo.class);
Root<Teacher> teacher = query.from(Teacher.class);
query.multiselect(teacher.get("firstName"),teacher.get("lastName"));
List<BasicTeacherInfo> results = em.createQuery(query).getResultList();
You can use #Param annotation to pass dynamic values to HQL, something like:
#Query("SELECT new com.blabla.myCustomObject(p.name, p.surname, c.model, c.number ...) "
+ "FROM Car c "
+ "LEFT JOIN c.person p "
+ "WHERE c.status = :status AND p.name = :name")
List<myCustomObject> getExportCustomObject(
#Param("status") Integer status,
#Param("name") String name
);
Below is one of the possible way where you can try to add offset and limit into your query you can make it dynamic with the help off placeholders.
Below is an sample pseudo code for reference:
Dao Layer:
#Query(value="SELECT e FROM tablename e WHERE condition_here ORDER BY e.id offset :offset limit:limit ")
public returnType yourMethod(String name, int offset, int limit);
Service Layer:
long count = number of records in db.
int a = // number of records to be fetched on each iterations
int num_iterations = count % a ;
int additionalrecords = count / a;
int start= 0;
while(num_iterations>0)
{
dao.yourMethod(start,a);
start = start+a;
count--;
// write your data to excel here
}
dao.yourMethod(start,additionalrecords);
Hope it is helpful.

Dynamic Linq Library can’t handling duplicate alias column names

I am trying to collect the data from database by using Dynamic Linq Library NeGet. When I loop through it showing this error ‘The item with identity 'FirstName' already exists in the metadata collection’
Seems like Dynamic Linq Library NuGet is can’t handle duplicate alias column names.
I have two tables and it has One-On-Many relationship as follow, containing the same Columns names in Lead table and CoBorrower table.
Table1: Lead
Columns: LeadID, FirstName,DateCreated
Table2: CoBorrower
Columns: LeadID, CoBorrowerID,FirstName,Tax,DateCreated
Here is my code snippet
var res = (from l in db.Leads
join db.CoBorrower.GetAll()
on l.LeadID equals cb.LeadID
select new { l, cb }).AsQueryable();
string myCustomCondition="FistName=myname";
IQueryable iq = res.Where(myCustomCondition)
.OrderBy(reportBulder.Group1)
.Select("new(l.LeadID,l.FirstName,cb.FistName)")
.GroupBy("LeadID", "it")
.Select("new (it.Key as Key, it as Value)");
foreach (dynamic group in iq)
{
string Key = group.Key.ToString();
List<dynamic> items = new List<dynamic>();
foreach (dynamic album in group.Value)
{
items.Add(album);
}
dataList.Add(Key, items);
}
I will appreciate your help in advance.
This is logical. The .Select("new(l.LeadID,l.FirstName,cb.FistName)") will create an anonymous object like:
new
{
LeadID = ....,
FirstName = ....,
FirstName = ....,
}
that is illegal (two properties with the same name)
Use the as
.Select("new(l.LeadID,l.FirstName,cb.FistName as FirstName2)")
so that the anonymous object created is
new
{
LeadID = ....,
FirstName = ....,
FirstName2 = ....,
}
as you do in the second .Select.

LINQ Distinct set by column value

Is there a simple LINQ query to get distinct records by a specific column value (not the whole record)?
Anyone know how i can filter a list with only distinct values?
You could use libraries like morelinq to do this. You'd be interested in the DistinctBy() method.
var query = records.DistinctBy(record => record.Column);
Otherwise, you could do this by hand.
var query =
from record in records
group record by record.Column into g
select g.First();
Select a single value first and then run the Distinct.
(from item in table
select item.TheSingleValue).Distinct();
If you want the entire record you need to use group x by into y. You then need to find a suitable aggregate function like First, Max, Average or similar to select one of the other values in the group.
from item in table
group item by item.TheSingleValue into g
select new { TheSingleValue = g.Key, OtherValue1 = g.First().OtherValue1, OtherValue2 = g.First().OtherValue2 };
You could make an implementation of the IEqualityComparer interface:
public class MyObjectComparer : IEqualityComparer<MyObject>
{
public bool Equals(MyObject x, MyObject y)
{
return x.ColumnNameProperty == y.ColumnNameProperty;
}
public int GetHashCode(MyObject obj)
{
return obj.ColumnNameProperty.GetHashCode();
}
}
And pass an instance into the Distinct method:
var distinctSource = source.Distinct(new MyObjectComparer());

Resources