使用Room Persistence Library插入多个表 [英] Insert into multiple tables using Room Persistence Library

查看:72
本文介绍了使用Room Persistence Library插入多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次使用Room.我有一堂课:

It's the first time I am using Room. I have a class called:

@Entity(tableName = "users")
class User{
   @PrimaryKey
   @ColumnInfo(name = "id")
   @SerializedName("id")
   String id;

   @ColumnInfo(name = "name")
   @SerializedName("name")
   String name;

   @SerializedName("shift")
   @Ignore
   List<Shift> shifts; 
}

@Entity(tableName = "shifts")
class Shift{
   @PrimaryKey
   @ColumnInfo(name = "id")
   @SerializedName("id")
   String id;

   @ColumnInfo(name = "start_time")
   @SerializedName("start_time")
   String startTime;

   @ColumnInfo(name = "end_time")
   @SerializedName("end_time")
   String endTime;
}

我希望这两个数据库是单独的表,因此我不能使用@Embedded注解,因为它将使用所有字段作为列来创建单个表.我也在使用上面的User类来存储来自服务器的json响应,在那里我获得了用户并在json对象中转移了详细信息.

I want these two to be seperate tables in the database, hence I cannot user @Embedded annotation, as it will create a single table using all field as columns. I am using the above User class to store json reponse from the server as well, where I get the user and shift details information in a json object.

一旦在用户表中插入用户详细信息,有什么方法可以在 shifts 表中插入Shift详细信息?最初,我认为这将使用@Embeded进行处理,但这会在不需要的 user 表中创建 shift 表列.

Is there any way I can insert the Shift details in shifts table as soon as I insert the User details in the users table ? I initially thought this will be handled using @Embeded but that will create shift table columns in the user table which I do not want.

有人建议我在Room Persistence Library中处理此事的方式吗?类似,我也需要删除.

Can someone help me as to how I am suppose to handle this in Room Persistence Library. Similar I will have to do for delete as well.

谢谢

推荐答案

在将用户详细信息插入到用户表后,有什么方法可以将班次详细信息插入到班次表中?

Is there any way I can insert the Shift details in shifts table as soon as I insert the User details in the users table ?

创建自己的DAO @Transaction方法,该方法调用UserShift的插入.

Create your own DAO @Transaction method that calls inserts for User and Shift.

类似,我也必须删除.

Similar I will have to do for delete as well.

如果修复您的Shift类,并使用适当的层叠删除选项将其与User建立@ForeignKey关系,则删除User也会删除其Shift行.在您当前的实现中,UserShift是不相关的.

If you fix your Shift class, such that it has a @ForeignKey relationship to User with the appropriate cascade-delete option, deleting a User will delete its Shift rows as well. In your current implementation, User and Shift are unrelated.

这篇关于使用Room Persistence Library插入多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆