Android Room - 通过自动生成获取新插入行的 id [英] Android Room - Get the id of new inserted row with auto-generate

查看:59
本文介绍了Android Room - 通过自动生成获取新插入行的 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用 Room Persistence Library 将数据插入数据库的方式:

This is how I am inserting data into database using Room Persistence Library:

实体:

@Entity
class User {
    @PrimaryKey(autoGenerate = true)
    public int id;
    //...
}

数据访问对象:

@Dao
public interface UserDao{
    @Insert(onConflict = IGNORE)
    void insertUser(User user);
    //...
}

是否可以在上述方法本身中完成插入后返回User的id,而无需编写单独的select查询?

Is it possible to return the id of User once the insertion is completed in the above method itself without writing a separate select query?

推荐答案

基于文档 此处(在代码段下方)

Based on the documentation here (below the code snippet)

使用@Insert注解的方法可以返回:

A method annotated with the @Insert annotation can return:

  • long 用于单次插入操作
  • long[]Long[]List 用于多个插入操作
  • void 如果你不关心插入的 id(s)
  • long for single insert operation
  • long[] or Long[] or List<Long> for multiple insert operations
  • void if you don't care about the inserted id(s)

这篇关于Android Room - 通过自动生成获取新插入行的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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