当插入或更新返回错误时,它返回一个长整型(-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);}
最佳答案
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
}
关于java - 有没有办法返回错误原因实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57038612/