ORMLITE order by a column from another table - android

I would like to get information by a sql like this but in "ORMLITE"
SELECT * FROM tableA a INNER JOIN tableB b on a.fieldA = b.fieldB
ORDER BY a.fieldZ, b,fieldX;
I try this in ORMLITE:
QueryBuilder<B, Integer> bQuery = bDao.queryBuilder();
bQuery.orderby("fieldX", true);
QueryBuilder<A, String> aQuery = aDao.queryBuilder();
aQuery.orderby("fieldZ", true);
list = (List<T>) aQuery.join(bQuery).query();
But the result is not correct because it is not order by a.fieldZ. How can I do this?
Thank you.

instead :
aQuery.orderby("fieldZ", true);
you should use :
aQuery.orderbyRaw("a.fieldZ, b.fieldX");
it's work for me

Related

Adding two .sqlite DB into a list and showing by adapter

I have two databases .sqlite in Android.
productosdb.sqlite and entradas.sqlite with one table each.
In productosdb I have the table "entradas"={id,cod1,cod2,descrip,present,pale} and in the other "entradas"={id,idref(that is cod1 already saved from the other table),cant,vto}
I want to show all items of table "entradas" but giving to the adapter a list that has all fields of both tables. When I get a row from table "entradas" I get the message idrefto search the other the missing fields. Something is not working. Here's some of the code:
private List<ProductoSUMADO> listasumada = new LinkedList<ProductoSUMADO>();
Producto temporalProducto = new Producto();
List<ProductoConVencimiento> temporalEntrada = new LinkedList<ProductoConVencimiento>();
String asd = bundle.getString("codigo");
temporalProducto = managerdb.getProductoPorCodigoBarras(asd);
String sss = temporalProducto.getCodprod();
temporalEntrada = db.getProductosPorIDRef(sss);
for (int pos = 0; pos < temporalEntrada.size(); pos++)
{
ProductoSUMADO p = new ProductoSUMADO(temporalProducto.getCodbar()),
temporalProducto.getCodprod(),
temporalProducto.getDescrip(),
temporalProducto.getPresent(),
temporalProducto.getPale(),
temporalEntrada.get(pos).getCant(),
temporalEntrada.get(pos).getVto(),
temporalEntrada.get(pos).getNotas());
listasumada.add(p);
}
CustomAdapter2 adapter = new CustomAdapter2(this, listasumada);
listview.setAdapter(adapter);
Maybe you understand what I want to do and show another way to do this.
You are doing it wrong. Just create one database and two tables "productos" and "entradas"
then you will be able to JOIN data using rawQuery.
Learn more about SQLite here: vogella
it has examples so you can test it!
Join example:
String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});

Multiple Query Condition in Android using ORMLITE

i want to make a simple query, with multiple conditions
I use OrmLite to map entity object.
Now I want to search for an object into my table.
Supposing i have a Person entity that maps PERSON table, what I want to do is to initialize an object with some parameters and search it.
Suppose a function searchPerson(Person oPerson)
If i pass an object OPerson like this
Id = null
Name = John
Age = null
Sex = male
Is possible to write a query to reach that goal? Something like this pseudo-code
pers = (from p in db.Table<Person>()
where (if OPerson.Id !=null) p.Id==OPerson.Id}
AND {(if OPerson.Name !=null) p.Name.Contains(OPerson.Name)}
AND {(if condition) where-contion}
select p).ToList();
I know that i can do multiple query in this way
list=PersonDao.queryBuilder().where().eq("name",OPerson.name)
.and().eq("sex",OPerson.sex").query();
but I want also to check if the value exists
where (if OPerson.Id !=null) p.Id==OPerson.Id}
#ArghArgh is close but doesn't have the ANDs right. The problem is that the AND statements are conditional on whether there were any previous statements. I'd do something like:
QueryBuilder<Person, Integer> queryBuilder = dao.queryBuilder();
Where<Person, Integer> where = queryBuilder.where();
int condCount = 0;
if (oPerson.id != null) {
where.eq("id", oPerson.id);
condCount++;
}
if (oPerson.name != null) {
where.like("name", "%" + oPerson.name + "%");
condCount++;
}
...
// if we've added any conditions then and them all together
if (condCount > 0) {
where.and(condCount);
}
// do the query
List<Persion> personList = queryBuilder.query();
This makes use of the where.and(int) method which takes a number of clauses on the stack and puts them together with ANDs between.
I think that you must use the QueryBuilder.
Try something like this
QueryBuilder<Person, Integer> queryBuilder = PersonDao.queryBuilder();
// get the WHERE object to build our query
Where<Person, String> where = queryBuilder.where();
if(oPerson.Name!=null)
where.like("Name", "%"+oPerson.Name+"%");
// and
where.and();
if(Person.Sex!=null)
where.like("Sex", "%"+oPerson.sex+"%");
PreparedQuery<Person> preparedQuery = queryBuilder.prepare();
Than you can call it in this way
List<Person> list = PersontDao.query(preparedQuery);

Ormlite orderBy max(ColumnName)

Hi I need to use order by max(columnName) in ORMLite. I have the SQL query but I need to know how this query is used. This is my query:
SELECT * FROM table where place = 'somePlace' group by name
order by MAX (statusDate)
statusDate column contains date in "yyyy-dd-mm" format. The result I got is the list with recentDates.
Use a query builder, and function where and orderBy to preoceed
QueryBuilder<YourObject, Integer> q = yourDaoObject.queryBuilder();
Where<YourObject, Integer> wh = q.where();
wh.eq("place", "some_place");
q.orderBy("statusDate", false);
List<YourListOfObects> yourList = q.query();
But before that you should store a long instead to store your Date https://stackoverflow.com/a/6993420/2122876
i got same names with different dates and i need only the recent date.
If you are trying to get element from Table with the maximum statusDate then you should be doing an descending order-by with a limit of 1. Something like:
QueryBuilder<Foo, Integer> qb = fooDao.queryBuilder();
qb.where().eq("place", "some_place");
qb.orderBy("sttusDate", false); // descending sort
// get the top one result
qb.limit(1);
Foo result = qb.queryForFirst();
I did something like this. Please create your own query builder on the first line.
QueryBuilder<MyRowObject, Integer> queryBuiler = "Get Query builder" //getDaoXXX().queryBuilder();
MyRowObject firstLatestRow = queryBuiler.orderBy("dateColoumn", false).queryForFirst();
Hope this helps

ORMLite joins queries and Order by

I'm tring to make join in two tables and get all columns in both, I did this:
QueryBuilder<A, Integer> aQb = aDao.queryBuilder();
QueryBuilder<B, Integer> bQb = bDao.queryBuilder();
aQb.join(bQb).prepare();
This equates to:
SELECT 'A'.* FROM A INNER JOIN B WHERE A.id = B.id;
But I want:
SELECT * FROM A INNER JOIN B WHERE A.id = B.id;
Other problem is when taking order by a field of B, like:
aQb.orderBy(B.COLUMN, true);
I get an error saying "no table column B".
When you are using the QueryBuilder, it is expecting to return B objects. They cannot contain all of the fields from A in B. It will not flesh out foreign sub-fields if that is what you mean. That feature has not crossed the lite barrier for ORMLite.
Ordering on join-table is also not supported. You can certainly add the bQb.orderBy(B.COLUMN, true) but I don't think that will do what you want.
You can certainly use raw-queries for this although it is not optimal.
Actually, I managed to do it without writing my whole query as raw query. This way, I didn't need to replace my query builder codes (which is pretty complicated). To achieve that, I followed the following steps:
(Assuming I have two tables, my_table and my_join_table and their daos, I want to order my query on my_table by the column order_column_1 of the my_join_table)
1- Joined two query builders & used QueryBuilder.selectRaw(String... columns) method to include the original table's + the columns I want to use in foreign sort. Example:
QueryBuilder<MyJoinTable, MyJoinPK> myJoinQueryBuilder = myJoinDao.queryBuilder();
QueryBuilder<MyTable, MyPK> myQueryBuilder = myDao.queryBuilder().join(myJoinQueryBuilder).selectRaw("`my_table`.*", "`my_join_table`.`order_column` as `order_column_1`");
2- Included my order by clauses like this:
myQueryBuilder.orderByRaw("`order_column_1` ASC");
3- After setting all the select columns & order by clauses, it's time to prepare the statement:
String statement = myQueryBuilder.prepare().getStatement();
4- Get the table info from the dao:
TableInfo tableInfo = ((BaseDaoImpl) myDao).getTableInfo();
5- Created my custom column-to-object mapper which just ignores the unknown column names. We avoid the mapping error of our custon columns (order_column_1 in this case) by doing this. Example:
RawRowMapper<MyTable> mapper = new UnknownColumnIgnoringGenericRowMapper<>(tableInfo);
6- Query the table for the results:
GenericRawResults<MyTable> results = activityDao.queryRaw(statement, mapper);
7- Finally, convert the generic raw results to list:
List<MyTable> myObjects = new ArrayList<>();
for (MyTable myObject : results) {
myObjects.add(myObject);
}
Here's the custom row mapper I created by modifying (just swallowed the exception) com.j256.ormlite.stmt.RawRowMapperImpl to avoid the unknown column mapping errors. You can copy&paste this into your project:
import com.j256.ormlite.dao.RawRowMapper;
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.table.TableInfo;
import java.sql.SQLException;
public class UnknownColumnIgnoringGenericRowMapper<T, ID> implements RawRowMapper<T> {
private final TableInfo<T, ID> tableInfo;
public UnknownColumnIgnoringGenericRowMapper(TableInfo<T, ID> tableInfo) {
this.tableInfo = tableInfo;
}
public T mapRow(String[] columnNames, String[] resultColumns) throws SQLException {
// create our object
T rowObj = tableInfo.createObject();
for (int i = 0; i < columnNames.length; i++) {
// sanity check, prolly will never happen but let's be careful out there
if (i >= resultColumns.length) {
continue;
}
try {
// run through and convert each field
FieldType fieldType = tableInfo.getFieldTypeByColumnName(columnNames[i]);
Object fieldObj = fieldType.convertStringToJavaField(resultColumns[i], i);
// assign it to the row object
fieldType.assignField(rowObj, fieldObj, false, null);
} catch (IllegalArgumentException e) {
// log this or do whatever you want
}
}
return rowObj;
}
}
It's pretty hacky & seems like overkill for this operation but I definitely needed it and this method worked well.

How to update column with ORMLite

I have an already created database for Android application and I'm using ORMLite for query to SQLLite.
I have added a column in category and I want to insert data in that column.
I have row, e.g.
catId=5 catname="food" catType=?
I want to update catType on the basis of catId. How can I update this catType column with the catId in ORMLite.
I am using this approach:
Dao<Category, Integer> catDao = getHelper().getCategoryDao();
QueryBuilder<Category, Integer> queryBuilder = catDao.queryBuilder();
queryBuilder.where().eq("categoryId", 5);
PreparedQuery<Category> pq = queryBuilder.prepare();
Category category = catDao.queryForFirst(pq);
category.setCategoryType("BarType");
catDao.createOrUpdate(category);
Please provide me a better solution.
I want to update catType on the basis of catId. How can I update this catType column with the catId in ORMLite.
ORMLite also supports an UpdateBuilder. Here's how you could use it:
UpdateBuilder<Category, Integer> updateBuilder = catDao.updateBuilder();
// set the criteria like you would a QueryBuilder
updateBuilder.where().eq("categoryId", 5);
// update the value of your field(s)
updateBuilder.updateColumnValue("catType" /* column */, "BarType" /* value */);
updateBuilder.update();
See the UpdateBuilder docs for more examples.
Dao<Category, Integer> catDao = getHelper().getCategoryDao();
List <Category> categoryList = catDao.queryForAll();
for (Category c: categoryList ) {
c.setCategoryType("BarType");
catDao.update(c);
}

Categories

Resources