I have one table "company" with contains 3 columns [ name,id ,address ]. But I want to fetch only "name " column values. I am doing like this
Dao<Company, String> dao = getDBHelper().getCompanyDao();
QueryBuilder<Company, String> queryBuilder = dao.queryBuilder();
queryBuilder.orderBy(Company.USERNAME_FIELD_NAME, true);
**queryBuilder.selectColumns("name");**
PreparedQuery<Company> preparedQuery = queryBuilder.prepare();
CloseableIterator<Company> iterator = dao.iterator(preparedQuery);
AndroidDatabaseResults results = (AndroidDatabaseResults) iterator.getRawResults();
Cursor cursor = results.getRawCursor();
But application is crashing when I add "queryBuilder.selectColumns("name") ". Please help me.I want cursor since am using cursoradapter to fill data.
crash logs are here :
java.lang.NullPointerException
at com.j256.ormlite.stmt.QueryBuilder.appendFieldColumnName(QueryBuilder.java:593)
at com.j256.ormlite.stmt.QueryBuilder.appendColumns(QueryBuilder.java:585)
at com.j256.ormlite.stmt.QueryBuilder.appendStatementStart(QueryBuilder.java:405)
at com.j256.ormlite.stmt.StatementBuilder.appendStatementString(StatementBuilder.java:122)
at com.j256.ormlite.stmt.StatementBuilder.buildStatementString(StatementBuilder.java:106)
at com.j256.ormlite.stmt.StatementBuilder.prepareStatement(StatementBuilder.java:74)
at com.j256.ormlite.stmt.QueryBuilder.prepare(QueryBuilder.java:98)
But application is crashing when I add "queryBuilder.selectColumns("name")
Wow. This is a very subtle and long standing bug. It will happen whenever you try to select columns from an entity that does not have an ID field. I've added this bug report:
https://sourceforge.net/p/ormlite/bugs/162/
This has been fixed in trunk and will be in 4.49. Here's the check-in.
https://github.com/j256/ormlite-core/commit/ee95883040a3618a1d455b44f6bfd6935a8d4ec7
Related
I'm trying to rename one of my selected fields, but it doesn't really work as expected.
This is my code
...
final List<Field<?>> fields = new ArrayList<>();
fields.add(field(name("inner_id"), String.class).as("id"));
fields.add(field(name("inner_name"), String.class).as("name"));
create.select(fields).from(view).where(whereClause, whereBindings);
...
Which translates to:
select "inner_id" "id", "inner_name" "name"
from table
where (inner_id = x)
Instead of
select "inner_id as id", "inner_name as name"
from table
where (inner_id = x)
What am I missing?
Thanks!
The error was actually in the uneccesry quotes.
If anyone else has this error - see this.
I am new to querydsl and I'm trying to use querydsl in pure java (no hibernate, JPA or anything).
We have a database where the tables are linked through minimum 3 columns
I followed the doc here and ended up with my schema duly created.
Here are my pseudo tables :
Item
Corporation (pk) mmcono
Item number (pk) mmitno
Environnement (pk) mmenv
Item description mmitds
Item_warehouse
Corporation (fk for Item) mbcono
Item number (fk for Item) mbitno
Environnement (fk for Item) mbenv
Warehouse number mbwhlo
Other properties (not important)
Inside the Item_wharehouse class, I manually added the foreignKey (because it's not defined in the actual db schema)
public final com.querydsl.sql.ForeignKey<QItemWharehouse > _ItemWharehouseFk = createInvForeignKey(Arrays.asList(mbitno, mbcono, mbenv), Arrays.asList("mmitno", "mmcono", "mbenv"));
I'm working on the following code in my main class:
SQLTemplates templates = SQLServer2012Templates.builder().printSchema().build();
Configuration configuration = new Configuration(templates);
QItem mm = new QItem ("mm");
QItemWarehouse mb = new QItemWarehouse("mb");
JtdsDataSource ds = getDataSource();
SQLQueryFactory queryFactory = new SQLQueryFactory(configuration, ds);
String toto = queryFactory.select(mm.mmitno, mm.mmitds)
.from(mm)
.join( ???????????? )
.where(mb.mbwhlo.eq("122"))
.fetch()
As per doc here I should be able to do something like this : AbstractSQLQuery.innerJoin(ForeignKey<E> key, RelationalPath<E> entity)
What I want in the end is to allow joining table without having to specify manually all the columns required for the join condition.
As stated before, my model starts with minimum 3 columns in the pk, and it's not uncommon to have 6 or 7 cols in the on clause! It's a lot of typing and very error prone, because you can easily miss one and get duplicate results.
I would like something like .join(mb._ItemWharehouseFk, ???) and let querydsl handle little details like generating the on clause for me.
My trouble is that I can't find the second parameter of type RelationalPath<E> entity for the join method.
I am doing something wrong ? What do I miss ? Is it even possible to accomplish what I want ?
Oups I found the problem : I had it all in the wrong order.
The foreign key was located in the itemWarehouse class.
it should have been named this way :
public final com.querydsl.sql.ForeignKey<QItem> _ItemFk = createInvForeignKey(Arrays.asList(mbitno, mbcono, mbenv), Arrays.asList("mmitno", "mmcono", "mbenv"));
that means that you just have to reverse the order in the statement this way :
SQLTemplates templates = SQLServer2012Templates.builder().printSchema().build();
Configuration configuration = new Configuration(templates);
QItem mm = new QItem ("mm");
QItemWarehouse mb = new QItemWarehouse("mb");
JtdsDataSource ds = getDataSource();
SQLQueryFactory queryFactory = new SQLQueryFactory(configuration, ds);
List<Tuple> toto = queryFactory.select(mm.mmitno, mm.mmitds)
.from(mb)
.join(mb._ItemFk, mm )
.where(mb.mbwhlo.eq("122"))
.fetch()
And you get your nice on clause generated. It's just a question of how you construct your relation.
#Enigma, I sincerely hope it will help you for your Friday afternoon. I wouldn't want your boss to be disappointed with you :-)
Does anybody know is it possible to write in JOOQ select with a set of predefined values? I need it for insert if not exists.
For example,
INSERT INTO test
(text)
SELECT '1234567890123456789'
WHERE
NOT EXISTS (
SELECT id FROM test WHERE text = '1234567890123456789'
);
I've found the answer by myself:
List<Param<?>> params = new LinkedList<>();
params.add(DSL.val("1234567890123456789"));
List<Field<?>> fields = new LinkedList<>();
fields.add(TEST.TEXT);
SelectConditionStep<Record1<TEXT>> notExistsSelect = context.select(TEST.TEXT).from(TEST).where(TEST.TEXT.eq("1234567890123456789"));
SelectConditionStep<Record> insertIntoSelect = context.select(params).whereNotExists(notExistsSelect);
context.insertInto(TEST, fields).select(insertIntoSelect).execute();
But it would be great, if we had an ability to do it via InsertQuery. I've not found the way to do it.
I'm new here and would be great if someone could help me with this small crisis I have been having. I have been following Jeff Sharkeys Separate List Adapter tutorial which can be found here and I got it all working appropriately to how he explains it.
My problem is I have a database, pre made one which has a table that I am trying to put the extracted data into a list view using Jeffs adapter. I need this data to be put in different sections according to the Category ID column.
The table I am currently extracting data from is the Food table, which has 6 columns, categoriID, menuID, Item, Description, price and a PK _id
My database works properly as in other activities I use a SimpleCursorAdapter to bind data to a list view. (from other tables)
I use the following method in the Database Helper class to retrieve the data I need
public List<FoodModel> getData(String catid, String menuid) {
List<FoodModel> FoodListModel = new ArrayList<FoodModel>();
Cursor cursor = myDataBase.query(FOOD_TABLE, new String [] {FOODITEM_COLUMN, FOODITEMDESCRIPTION_COLUMN,FOODPRICE_COLUMN}, "catid = ? AND menuid = ?",
new String[] { catid, menuid},null, null, null, null);
if (cursor.moveToFirst()){
do{
FoodModel FoodModel = new FoodModel();
FoodModel.setItem(cursor.getString(0));
FoodModel.setdescrription(cursor.getString(1));
FoodModel.setprice(Double.parseDouble(cursor.getString(2)));
FoodListModel.add(FoodModel);} while (cursor.moveToNext());
}
return FoodListModel;
}
the Food Model class is the standard get set class to store the cursors data.
This public method works accordingly as in my main activity (jeffs ListSample.java) I output to the log cat the required information using
Log.d("Reading: ", "Testing Cursor");
List<FoodModel> Data1 = dba.getData("1", "1");
for (FoodModel fd : Data1){
String log = "Item: "+fd.getitem()+" ,Description: " + fd.getdescription() + " ,Price: " + fd.getprice();
Log.d("Name: ", log);
This outputs a list of all the data I need to put into 1 section of the SeperateListAdapter but to the log cat
The 3 things i am trying to output to the list view are the Item, description and price.
My problem is How do I add this data to the list view under the correct section?
as oposed to manually inserting it as Jeff shows
List<Map<String,?>> security = new LinkedList<Map<String,?>>();
security.add(createItem("Remember passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Clear passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Show security warnings", "Show warning if there is a problem with a site's security"));
I didn't want to start my first experience of using this site by pasting all my classes is as this is my first time using this website, my English is not the best and it took me a while to write this I hope it is acceptable as a question, I would be really great full if someone could kindly help me or point me in the right direction.
EDIT: Will gladly post the rest of my code just didnt whant to bombard everyone with loads of information
When trying to update a record for one of my records I am using this code
private void UpdateCattleRecord(UpdateCattleRecord updateRecord){
mDB.beginTransaction();
String where = "_ID=";
String[] RecordToUpdate = {Cattle._ID};
Toast.makeText(this,"Updating Animal "+ RecordToUpdate, Toast.LENGTH_LONG).show();
try {
ContentValues CattleFieldsToUpdate = new ContentValues();
CattleFieldsToUpdate.put(Cattle.CATTLE_ANIMALID,updateRecord.getCattleName());
CattleFieldsToUpdate.put(Cattle.CATTLE_TYPE, updateRecord.getCattleType());
CattleFieldsToUpdate.put(Cattle.CATTLE_LOCATION, updateRecord.getCattleLocation());
CattleFieldsToUpdate.put(Cattle.CATTLE_DOB, updateRecord.getCattleDob());
CattleFieldsToUpdate.put(Cattle.CATTLE_DAM, updateRecord.getCattleDam());
CattleFieldsToUpdate.put(Cattle.CATTLE_SEX, updateRecord.getCattleSex());
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, where, RecordToUpdate);
mDB.setTransactionSuccessful();
} finally {
mDB.endTransaction();
}
}
My log shows
Tag Database sqlite returned: error code =1, msg = near "=": syntax error
After researching this, I think I have everything in the right place but obviously I don't,
when I look at the next error in the log it's of course in 'red' and it shows me all the correct data,
03-27 15:15:29.291: E/Database(12011): Error updating date_of_birth=March 27, 2012 animaltype=Calf sex=F location=Eastern dam=601 animal_id=601A using UPDATE cattle SET date_of_birth=?, animaltype=?, sex=?, location=?, dam=?, animal_id=? WHERE _ID=
I've obviously got a problem with the value for _ID but can't seem to locate it. Can someone please point out where my Syntax error is?
Update
The problem occurred because I was failing to pass the actual value of the record (_ID) that I wanted to update. Once I passed that as a parameter to my updaterecords function the update went as scheduled.
Thanks for the input, it helped me narrow down what I was doing wrong.
Check your database creation, your probably have a column named _id(although you refer to it by _ID, its name is _id) and not _ID:
String where = "_id= ?"; // ? represent the value from the selection arguments String array
or better:
String where = Cattle._ID + "= ?";
Edit:
In your where selection argument you put:
String[] RecordToUpdate = {Cattle._ID};
you probably want to put in there some id you get from somewhere(of the record you want to update, a long number), right now you're doing:
WHERE _ID = _ID (or _id)
and this will fail.
try:
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, "_ID="+Cattle._ID, null);
try:
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, "_ID="+updateRecord.getId(), null);