java - 有没有办法返回错误原因实体?

标签 java android android-room

当插入或更新返回错误时,它返回一个长整型(-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/

相关文章:

java - 在同一个项目中使用jpa存储库和hibernate(使用标准,HQL调用查询)可以吗

kotlin - TypeConverters 无法弄清楚如何将此字段保存到数据库中

java - @AutoAnnotation 有什么用?怎么可以用呢?

java - 反转字符串的顺序

java - 按顺序单击多个按钮,robotium 不起作用

java - 如何在 android Jelly Bean Launcher 中添加自定义 View

java - Android 中 DatatypeConverter 的替代品

kotlin - 带有 ViewModel、Repository、Room 和 Coroutines 的 Dagger 2

android - 如何在使用 Room 时立即获取查询结果?

java - 在现有行之间添加 2 行