简体   繁体   中英

Inserting into 2 tables with auto-generated primary key

I have two entities, Workout and Exercise. Each workout can have many exercises. When I want to insert a new workout with a list of exercises into the two tables, I'm first inserting the workout data into Workout and then I'm trying to insert the exercises into the Exercise table.

The two tables are related by a foreign key in Exercise (workout_id and id in Workout). The problem is the primary key in Workout is auto-generated so when I go to insert the exercises, I don't know what to give the foreign key value unless I query the Workout id as well. Is that the best thing to do?

@Entity(tableName = "workouts")
public class Workout {
  @PrimaryKey(autoGenerate = true)
  public int id;
  ...
}

@Entity(tableName = "exercises", foreignKeys = @ForeignKey(entity = Workout.class,
                                                            parentColumns = "id",
                                                            childColumns = "workout_id"))
public class Exercise {
  @PrimaryKey(autoGenerate = true)
  public int id;

  @ColumnInfo(name = "workout_id")
  public int workoutId;
  ...
}

In your WorkoutDao class you can return long value(generated id) when insert, like this:

@Insert
long insert(Workout work);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM