如何使用Android Room自动插入链接的实体?

时间:2018-10-18 10:59:03

标签: android relational-database android-room

我有一个用户类,该用户具有订单列表和类似的模型

@Entity
public class User implements Parcelable{
    @PrimaryKey
    @ColumnInfo(name = "_id" )
    int id;
    String email;
    String password;

    List<Order> orders;

    public User(String email, String password) {
       this.email = email;
       this.password = password;
    }
}



@Entity (tableName = "Order",foreignKeys = @ForeignKey(entity = User.class,parentColumns = "_id",childColumns = "user_id", onDelete = ForeignKey.CASCADE),
        indices = {@Index(value = {"user_id"}, unique = true)})
public class Order implements Parcelable{
    @PrimaryKey
    @ColumnInfo(name = "order_id")
    int id;
    @ColumnInfo(name = "user_id")
    int userId;
    String orderName;

    public Order(int id, int userId, String orderName) {
       this.id = id;
       this.userId = userId;
       this.orderName = orderName;
    }
}

关于此模型结构,我应该怎么做才能在@Dao中制作一个名为insertUser的方法,该方法将用户对象与嵌套Order列表一起使用,并在检索数据时将它们保存在一起从用户那里检索喜欢的订单

@Dao
public abstract class DatabaseDao {
    @Insert 
    public abstract void insertUser(User user);
    @Query("SELECT * FROM User WHERE _id =:userId")
    public abstract User getUser(int userId);
  }

要像这样使用

public class MainActivity extends AppCompatActivity {

    AppDatabase db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = Room.databaseBuilder(getApplicationContext(),
                AppDatabase.class, "database-name").build();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                User user = new User("Fady1", "123");
                user.setId(1);
                Order order1 = new Order(1,1,"Order1");
                Order order2 = new Order(2,1,"Order2");
                Order order3 = new Order(3,1,"Order3");
                List<Order> orders = new ArrayList<>();
                orders.add(order1);
                orders.add(order2);
                orders.add(order3);
                user.setOrders(orders);

                db.databaseDao().insertUser(user);
            }
        });

        thread.start();
    }
}

1 个答案:

答案 0 :(得分:0)