Reputation: 1952
I want to update a record in my SQLite DB. This record is stored in a table with fields described by annotation @DatabaseField(canBeNull = false)
. Firstly I store a record, I fill all required values and later I try to update it.
I want to update only some values of record. For example:
Order o = new Order();
o.setStatus(OrderStatus.PENDING);
o.setIdOrder(1);
orderDAO.update(order);
I use update
method of RuntimeExceptionDao
. It constructs full update query with all columns.
For example:
UPDATE `order` SET `idCustomer` = ?, `number` = ?, `orderDate` = ?, `status` = ? WHERE `idOrder` = ?
And it throws me the exception
java.lang.RuntimeException: java.sql.SQLException: Unable to run update stmt on object Order
How can I specify fields for UPDATE
query? I want only this query
UPDATE `order` SET `status` = ? WHERE `idOrder` = ?
Upvotes: 0
Views: 2730
Reputation: 116908
By default dao.update(...)
updates all fields. It doesn't know that you've only changed a couple of them or anything.
Typically you request the item from the database, change it and call dao.update(...)
:
Order order = orderDao.queryForId(1);
if (order.getStatus() != OrderStatus.PENDING) {
order.setStatus(OrderStatus.PENDING);
orderDao.update(order);
}
This allows you to test the current Order
status, etc.. If you must create a custom UPDATE
method, you can use the UpdateBuilder
:
For example:
UpdateBuilder<Order, Integer> updateBuilder = orderDAO.updateBuilder();
updateBuilder.updateColumnValue(Order.STATUS_FIELD_NAME, OrderStatus.PENDING);
updateBuilder.where().eq(Order.ID_FIELD_NAME, 1);
updateBuilder.update();
Upvotes: 4