Reputation: 251
I have a sqlite database and i want to change my database to Room database
.
One of tables has no any primary key and just have two foreign key.
I created the table before room with this query:
CREATE TABLE student_performance(
class_id int ,
student_id char(10),
class_date date ,
absent boolean DEFAULT 0,
delay boolean DEFAULT 0,
positive int DEFAULT 0,
negative int DEFAULT 0,
quiz float ,
FOREIGN KEY (student_id , class_id) REFERENCES student(student_id , class_id)
ON DELETE CASCADE
ON UPDATE CASCADE);
Now i define table for room:
@Entity(tableName = "performance",
foreignKeys = {@ForeignKey(
entity = StudentEntry.class,
parentColumns = {CLASS_ID, STUDENT_ID},
childColumns = {CLASS_ID, STUDENT_ID},
onDelete = CASCADE, onUpdate = CASCADE)})
public class PerformanceEntry {
.
.
.
}
But it gives error :
error: An entity must have at least 1 field annotated with @PrimaryKey
I dont know how can define this table for room database.
Upvotes: 1
Views: 4874
Reputation: 771
Example:
primaryKeys = {"class_id", "lastName", "class_date", ... , "quiz"})
In Relational Databases when you don't have any primary key means all of the fields are primary key together.
When you use ORM
you should usually define an Id attribute for your entities.
Upvotes: 1
Reputation: 110
You need to use the autoGenerate property
Your annotation should be like this:
@PrimaryKey(autoGenerate = true)
Upvotes: 0
Reputation: 76639
One does not have to run CREATE TABLE
SQL, when having tableName
and @ColumnInfo
annotations present. Add a primary key entry_id
(since the class_id
barely is unique):
@Entity(
tableName = "performance",
foreignKeys = {
@ForeignKey(
entity = StudentEntry.class,
parentColumns = {CLASS_ID, STUDENT_ID},
childColumns = {CLASS_ID, STUDENT_ID},
onDelete = CASCADE,
onUpdate = CASCADE
)
}
)
public class PerformanceEntry {
/* Fields */
@ColumnInfo(name = "entry_id")
@PrimaryKey(autoGenerate = true)
private int entryId;
...
}
Upvotes: 6
Reputation: 363667
Check the official doc.
Just use the @PrimaryKey
annotation.
Each entity must define at least 1 field as a primary key. Even when there is only 1 field, you still need to annotate the field with the
@PrimaryKey
annotation. Also, if you want Room to assign automatic IDs to entities, you can set the@PrimaryKey
'sautoGenerate
property. If the entity has a composite primary key, you can use theprimaryKeys
property of the@Entity
annotation, as shown in the following code snippet:
Something like:
@Entity(...)
public class PerformanceEntry {
@PrimaryKey
public int class_id;
//..
}
or
@Entity(...)
public class PerformanceEntry {
@PrimaryKey(autoGenerate = true)
//..
}
Upvotes: 1