房间更新(或插入,如果不存在)行,并返回更改的行数 [英] room update (or insert if not exist) rows and return count changed rows

查看:162
本文介绍了房间更新(或插入,如果不存在)行,并返回更改的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新,如果不存在,请在ROOM DB中插入行.

I need update and if not exist insert row to ROOM DB.

我这样做:productRepository.updateProducts(productsResponse.getProductItems());

并且:

@Override
public void updateProducts(final List<ProductItem> products) {
    new Thread(() -> {
        for (ProductItem item : products) {
            Product product = createProduct(item);
            productDao.insert(product);
        }
    }).start();
}

在DAO中:

@Insert
void insert(Product products);

但是我有方法

@Update
void update(Product product);

我有一些问题:

  1. 这两种方法均无效.插入后如何返回已保存的Product或boolean标志或插入的计数?

  1. both methods is void. How can I return saved Product or boolean flag or inserted count after insert?

如果我尝试致电update,但我没有行,它将插入吗?

if I try call update and I have not row will it be inserted?

如何更新(如果不插入)行并返回计数更新或已插入的行?

How can I update(if not - insert) row and return count updatet or inserted rows?

推荐答案

  1. @Insert注释的方法可以返回long.这是插入行的新生成的ID.用@Update注释的方法可以返回int.这是更新的行数.

  1. A method, annotated with @Insert can return a long. This is the newly generated ID for the inserted row. A method, annotated with @Update can return an int. This is the number of updated rows.

update将尝试使用where子句中的主键值更新所有字段.如果您的实体尚未持久存储在数据库中,则update查询将无法找到行,也不会更新任何内容.

update will try to update all your fields using the value of the primary key in a where clause. If your entity is not persisted in the database yet, the update query will not be able to find a row and will not update anything.

您可以使用@Insert(onConflict = OnConflictStrategy.REPLACE).这将尝试插入实体,如果存在具有相同ID值的现有行,它将删除该实体并将其替换为您尝试插入的实体.请注意,如果您使用的是自动生成的ID,则意味着结果行将具有与替换后的原始ID不同的ID.如果要保留ID,则必须提出一种自定义方式.

You can use @Insert(onConflict = OnConflictStrategy.REPLACE). This will try to insert the entity and, if there is an existing row that has the same ID value, it will delete it and replace it with the entity you are trying to insert. Be aware that, if you are using auto generated IDs, this means that the the resulting row will have a different ID than the original that was replaced. If you want to preserve the ID, then you have to come up with a custom way to do it.

这篇关于房间更新(或插入,如果不存在)行,并返回更改的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆