I want to get data from my room db with the following query:
#Query("SELECT address.address_id, first_name, last_name, street, postal_code, city," +
"(SELECT employee.employee_id FROM employee WHERE employee.address_id = address.address_id) AS employee_id, " +
"(SELECT project.project_id FROM project WHERE project.address_id = address.address_id) AS project_id " +
"FROM address WHERE last_name IN (:pattern) OR first_name IN (:pattern) ORDER BY last_name ASC, first_name ASC")
LiveData<List<AddressBookAddress>> loadAddressBookWithFilter(String... pattern);
As you can see my parameter accepts an array with one or more search strings.
Let's take for example "max" and "muster"
Now I want to get all records which contain the first names "max" or "muster" or the last names "max" or "muster". But currently, I'm not receiving any data at all.
The docs show it as quite straightforward thing. Look at Room Query docs. There you can see this example:
As an extension over SQLite bind arguments, Room supports binding a list of parameters to the query. At runtime, Room will build the correct query to have matching number of bind arguments depending on the number of items in the method parameter.
#Query("SELECT * FROM user WHERE uid IN(:userIds)")
public abstract List findByIds(int[] userIds);
For the example above, if the userIds is an array of 3 elements, Room will run the query as: SELECT * FROM user WHERE uid IN(?, ?, ?) and bind each item in the userIds array into the statement.
So, change signature from "String..." to "String[]" to clearly state an array presence.
There is no document for kotlin on this page but you can use this code for the same.
#Query("SELECT * FROM employee WHERE id IN(:idList)")
fun getAllSelectedEmployee(idList:Array<String?>): List<Model>
Related
I have a table for orders and customers. Customers contains an order ID and email. I wish to search for orders by customer email.
This is what I have come up with:
#RewriteQueriesToDropUnusedColumns
#Query(
"SELECT * FROM orders INNER JOIN order_customers ON order_customers.order_id = orders.id " +
"WHERE (order_customers.email LIKE '%' || :email || '%') ORDER BY orders.collection_time DESC"
)
protected abstract fun loadByEmail(email: String): LiveData<List<Order>>
I get a cursor mismatch warning "the query returns some columns which are not used" that I am loading all of the customer columns, when really all I want is orders. Adding the suggested #RewriteQueriesToDropUnusedColumns does not do anything. So what is the best syntax here? Should I just be embedding customers into the order DAO, or is there a simple solution without remodeling and migrating the data?
I can see that instead of saying SELECT * I can individually specify every order column but that is supposed to be the whole reason for Room...
You can use SELECT orders.* FROM orders INNER JOIN ....
Adding the suggested #RewriteQueriesToDropUnusedColumns does not do anything.
This could be because of the caveat:-
Note that Room will not rewrite the query if it has multiple columns that have the same name as it does not yet have a way to distinguish which one is necessary.
I'd suggest always using unique column names, doing so can avoid issues with ambiguities
Note that it appears that when there are duplicate column names, then the value of last column with the duplicated name is used by room. As can be seen in this example
I am trying to sort my data by ascending and descending order using room database. So I need to pass those parameter to the DAO.
This is my code:
#Query("SELECT * FROM DEVICES_TABLE ORDER BY :sortQuery")
fun sortDatabase(sortQuery: String): Flow<List<DeviceData>>
But when I pass title DESC as sortquery (title is column name), the query becomes:
SELECT *
FROM DEVICES_TABLE
ORDER BY 'title ASC'
I need to remove those single quotes from query for achieving the results. I need to sort with title, price, type etc. both ascending and descending. How can I do that?
i have a query like this
#Query("SELECT * FROM table WHERE type IN(:types) AND selection = 0 ORDER BY timestamp DESC")
my problem is that i have one type in my type list lets say it's type=4 for which i want selection = 1.
Is it possible to get the results in one query and how should the query look like?
I have 2 queryes from ROOM DB:
#Query("SELECT * FROM basket_items")
Flowable<List<BasketItem>> getAll();
#Query("SELECT SUM(count*amount) FROM basket_items")
Flowable<Long> totalSum();
How can I merge this queryes to one query? And what type of model it will be return?
Room Queries can return POJO (not an #Entity), and therefore you can make temporary model for your DAO.
As I already asked in comments, I don't know what you're trying to achieve (as in what value you want to get from those queries).
But hopefully this example might help:
YourDao.java
#Query("SELECT name AS nameItem, (count * amount) AS countItem FROM basket_items")
Flowable<List<CountedBasketItem>> getAllCounted();
static class CountedBasketItem {
String nameItem;
Long countItem;
}
Additional Answer
What you want to return List and total sum is not possible by the query. SUM is aggregation method, you aggregate the list.
So there're 2 options that you might want to do:
Use GROUP BY in your query
Or execute those 2 Flowable and get the result.
you can create field totalSum in your pojo and use this query
#Query("SELECT *,SUM(count*amount) AS totalSum FROM basket_items")
Flowable<List<BasketItem>> getAll();
you will get all table and the field totalSum is SUM(count*amount)
i'm trying to use chaining orderBy for this code:
List messages = G.messagesListsDao.queryBuilder().where().eq("group_id", group_id).query();
i can not find good document for how to use orderBy() chain for this code befor using .query() for example this code:
GenericRawResults<String[]> raw_result =G.messagesListsDao.queryRaw("SELECT * FROM messageslist WHERE group_id = " + group_id + " ORDER BY received_date");
to:
List messages = G.messagesListsDao.queryBuilder().where().eq("group_id", group_id).orderby("id",false).query();
You can call orderBy() more than once, like this:
List messages = G.messagesListsDao.queryBuilder().where().eq("group_id", group_id).orderBy("id",false).orderBy("received_date",false).query();
This is covered by the documentation. To quote:
Add "ORDER BY" clause to the SQL query statement to order the results
by the specified column name. Use the ascending boolean to get a
ascending or descending order. This can be called multiple times to
group by multiple columns.
Hope it works !