You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Room API技术问题:如何获取刚插入实体的自动生成ID?

How to Get Auto-Generated ID After Inserting a Room Entity

Hey there! Let's walk through how to grab that auto-generated ID right after inserting your Student entity with Room—just like you're used to with Hibernate's merge method.

First, let's confirm your setup is correct, since that's key to making this work:

1. Verify Your Entity Class

Your Student entity already has the right annotation for auto-generated IDs, but let's make sure the full class is properly set up with getters and setters (Room needs these to populate the ID after insertion):

@Entity
public class Student {
    @PrimaryKey(autoGenerate = true)
    private Integer id;
    private String name;
    // Add any other fields you need

    // Getters and Setters are crucial here!
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2. Check Your DAO Setup

Your DAO's insertStudent method just needs the basic @Insert annotation. Room will handle populating the ID back into your entity object automatically. Here's how the DAO should look:

@Dao
public interface StudentDao {
    @Insert
    void insertStudent(Student student);

    // Optional: If you prefer to get the ID directly as a return value, you can also do this:
    // @Insert
    // long insertStudent(Student student);
}

3. Fetch the Generated ID After Insertion

Your original code is actually on the right track! Room automatically assigns the generated ID to your Student object's id field once the insertion is successful. The only catch is that you can't run database operations on the main thread (Room enforces this by default to avoid UI freezes).

Here's a working example with proper threading (using Java's Executor for background work):

// Run the insertion on a background thread
Executors.newSingleThreadExecutor().execute(() -> {
    Student s = new Student();
    s.setName("foo");
    // Call other setter methods as needed

    // Perform the insert
    appDatabase.getGenericDAO().insertStudent(s);

    // Now you can grab the auto-generated ID directly from the student object!
    Integer generatedId = s.getId();

    // If you need to update the UI with this ID, switch back to the main thread
    runOnUiThread(() -> {
        // Use the generatedId here (e.g., display it, save it to a ViewModel, etc.)
    });
});

Why This Works

Room behaves similarly to Hibernate's merge here: when you insert an entity with an auto-generated primary key, it writes the entity to the database, generates the ID, and immediately sets that ID back on the original object you passed in. No extra steps needed!

A quick note: If the insertion fails (due to a constraint violation or other error), Room will throw an exception. Make sure to add try/catch blocks around the insertion if you want to handle these cases gracefully.

内容的提问来源于stack exchange,提问作者talha06

火山引擎 最新活动