当插入或更新返回错误时,它返回一个长的(-1),插入相同的ID时是否总会返回错误实体?
我当前正在使用此代码:
// Inserting new product
long id = database.productDAO().insert(product);
// Product already exists
if (id == -1) {
Product existingProduct = database.productDAO().select(product.getId());
existingProduct.setInventory(product.getInventory());
if (count > existingProduct.getAllowedMax())
existingProduct.setAllowedMax(count);
database.productDAO().update(existingProduct);
}
@Dao
public interface ProductDAO {
/**
* @return all of products
*/
@Query("SELECT * FROM product")
List<Product> select();
@Insert(onConflict = OnConflictStrategy.IGNORE)
List<Long> insert(Product... products);
@Update(onConflict = OnConflictStrategy.IGNORE)
void update(Product... products);
}
我想要某种方式,以便我可以直接找到错误实体并进行更改,这样就可以摆脱选择查询并节省一些资源,例如:
Product existingProduct = database.productDAO().insert(product);
// Product already exists
if (existingProduct != null){
existingProduct.setInventory(product.getInventory());
if (count > existingProduct.getAllowedMax())
existingProduct.setAllowedMax(count);
database.productDAO().update(existingProduct);}
答案 0 :(得分:0)
productDAO().insert method should return the inserted product, and from there you can get the product id.
public Product insert(Product ObjectToAdd){
{
if (DuplicateId){ // use a flag or a try/catch block to know if there is a record with given id already.
return null // or set the id to -1 or some default value :) ObjectToAdd.setId(-1)
}
return ObjectToAdd
}
答案 1 :(得分:0)
从查询中删除OnConflictStrategy
。这会引发异常,以便您可以根据需要进行处理。
@Insert
List<Long> insert(Product... products);
现在,当您调用上述方法时,如果房间在运行时遇到任何错误,它将引发异常,您可以捕获并提供自定义错误处理逻辑
try {
long id = database.productDAO().insert(product);
} catch (Exception e) {
// handle it here
}