📘 第一实体 · Entity 基础

#Room 入门
🧩 @Entity 声明 🔑 @PrimaryKey 主键 ⚡ 创建第一个实体

🎒 在 Room 中,Entity 就是数据库表的映射。每一个 Entity 类对应一张表,每个字段对应一列。 今天我们用最轻松的方式,创建第一个实体,并理解 @Entity 和 @PrimaryKey 的用法。

📌 1. @Entity 注解

@Entity 标记一个类为 Room 实体。默认情况下,Room 使用类名作为表名,也可以自定义:

@Entity(tableName = "student")
public class Student {
    // 字段...
}

🎯 常用选项:

属性作用示例
tableName指定表名(默认类名)@Entity(tableName = "student_info")
indices定义索引@Entity(indices = {@Index("name")})
primaryKeys复合主键@Entity(primaryKeys = {"id", "type"})
ignoredColumns忽略字段@Entity(ignoredColumns = {"temp"})

🔐 2. @PrimaryKey 主键定义

每个 Entity 必须 至少定义一个主键。使用 @PrimaryKey 标记,支持自动生成:

💡 小贴士: 对于自增主键,使用 autoGenerate = true,字段类型通常为 int 或 long。

🧪 3. 创建第一个实体:Student

我们一起来写一个 Student 实体,包含 id、name、age 和 grade 四个字段。

@Entity(tableName = "student")
public class Student {
    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "full_name")
    private String name;

    private int age;

    private String grade;  // 例如 "五年级"

    // 构造器、getter/setter 省略(实际开发中必须)
}

✅ 这样就完成了一个标准的 Room Entity。Room 会自动生成 DAO 所需的代码。

📂 字段映射 · @ColumnInfo

使用 @ColumnInfo 自定义列名,如上例中的 full_name。如果不指定,默认使用字段名。

字段列名(默认)自定义列名
ididid (主键)
namenamefull_name
ageageage
gradegradegrade

🧩 实体关系 · 架构示意

@Entity Student 🔑 id : INTEGER (PK) 📛 full_name : TEXT 📅 age : INTEGER 📚 grade : TEXT 映射 📋 student 表 🔑 id (INTEGER, PK) 📛 full_name (TEXT) 📅 age (INTEGER) 📚 grade (TEXT)

⬆️ Entity 类与数据库表一一对应,@PrimaryKey 映射为主键约束

📄 完整 Student 实体(含 getter/setter)

@Entity(tableName = "student")
public class Student {
    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "full_name")
    private String name;

    private int age;
    private String grade;

    // 构造器(Room 2.1+ 推荐使用 @Ignore 标记其他构造器)
    public Student(int id, String name, int age, String grade) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.grade = grade;
    }

    // 必须提供无参构造 (Room 使用)
    public Student() {}

    // Getter / Setter
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

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

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }

    public String getGrade() { return grade; }
    public void setGrade(String grade) { this.grade = grade; }
}

✅ 关键要点

⚠️ 常见错误: 忘记添加 @PrimaryKey 或主键字段缺失 → Room 编译报错 Entity must have a primary key。另外,复合主键必须使用 @Entity(primaryKeys = {...}) 形式。