I have a problem in my roomDatabase.
I searched on google and found some solutions but I can't solve my problem.
Can anyone help me?
Note : I want to use Object Oriented in my project.
Error :
Multiple fields have the same columnName: class_id. Field names: classId, classId.
ClassEntry :
@Entity(tableName = "class")
public class ClassEntry {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = COLUMN_CLASS_ID)
private int classId;
@ColumnInfo(name = "name")
private String className;
@ColumnInfo(name = "day")
private String classDay;
public ClassEntry(int classId, String className, String classDay) {
this.classId = classId;
this.className = className;
this.classDay = classDay;
}
@Ignore
public ClassEntry(int classId) {
this.classId = classId;
}
StudentEntry :
@Entity(tableName = "student",
primaryKeys = {COLUMN_CLASS_ID, COLUMN_STUDENT_ID},
foreignKeys = {@ForeignKey(
entity = ClassEntry.class,
parentColumns = COLUMN_CLASS_ID,
childColumns = COLUMN_CLASS_ID,
onDelete = CASCADE)})
public class StudentEntry extends ClassEntry{
@ColumnInfo(name = COLUMN_CLASS_ID)
private int classId;
@NonNull
@ColumnInfo(name = COLUMN_STUDENT_ID)
private String studentId;
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;
public StudentEntry(int classId, @NotNull String studentId, String firstName, String lastName) {
super(classId);
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
}
Your issue is that you are extending the StudentEntry class with the ClassEntry class. This is not how you manage related data with Room. You are effectively saying you want a table inside. Rather as you want a one (class) to many (students) relationship.
As such you want an Object that will contain a ClassEntry and the respective StudentEntries (0 or more). For this you create a normal POJO class embedding the Parent table and relating the child class(es).
So your ClassEntry class is fine as it is. However your StudentEntry class could be :-
Then you add another POJO class such as :-
The Dao's could be :-
Working Example using the above
Consider the following code, this adds 2 Classes Class1 and Class2. Class1 has 2 students added, Class 2 has 3 students added. Finally the ClassEntriesWithStudnetEntries are extracted using the
getAllClassEntriesWithStudentEntriesQuery:-Result as output to the log