如何设置外键

How do I set up a Foreign Key

我设置的是两个 table,一个用于用户创建的帐户,另一个用于让用户购买产品。

我两个 table 都是这样设置的

客户Table

@PrimaryKey(autoGenerate = true)
    private int custId;

    @ColumnInfo(name = "user_name")
    private String userName;

    @ColumnInfo(name = "password")
    private String password;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    @ColumnInfo(name = "address")
    private String address;

    @ColumnInfo(name = "city")
    private String city;

    @ColumnInfo(name = "postal_code")
    private String postalCode;

    @ColumnInfo(name = "country")
    private String country;

Phone Table


    @PrimaryKey(autoGenerate = true)
    private int productId;
    private String phoneMake;
    private String phoneModel;
    private String phoneColor;
    private String storageCapacity;
    private Float  price;

我设置的是两个外键,一一table。我的最后一个 table 是为了订购手机,这需要使用每个 table 的两个主键。我觉得我需要的是一个 ForeignKey,类似于已经创建的 PrimaryKey。问题是我不确定如何将其实现到程序中。我尝试做的一切都不起作用。我查看了文档,但没有任何点击。我希望你能帮助我提供正确的屏幕截图。如果需要更多信息,请告诉我(此代码是用 Java 代码编写的)

如果您只想让一个客户拥有 1 个 phone,那么您只有一个列(成员变量)用于存储 phone 的产品 ID 的关系。

例如

private int mapToPhone; //<<<<< ADDED no need for @ColumnInfo the column name will be as per the variable name.

显然你设置了一个合适的值。

然后使用 phone 的详细信息获取客户,然后您有一个使用 @Embedded 注释嵌入父级(客户)的 POJO 具有子级(Phone)使用 @Relation 注释。

例如:-

class CustomerWithPhoneDetails {
   @Embedded
   Customer customer;
   @Relation(
           entity = Phone.class,
           parentColumn = "mapToPhone",
           entityColumn = "productId"
   )
   Phone phoneDetails;
}

然后你可以在 @Dao 注释中有一个方法 interface/abstract class 查询父 table 但 returns 的 POJO 或 list/array POJO 例如:-

@Query("SELECT * FROM Customer")
abstract List<CustomerWithPhoneDetails> getAllCustomersWithPhoneDeytails();

例子

基于您的代码、附加示例代码以及 @Database 带注释的摘要 class :-

@Database(entities = {Customer.class,Phone.class}, version = 1, exportSchema = false)
abstract class TheDatabase extends RoomDatabase {
    abstract AllDao getAllDao();

    private static volatile TheDatabase instance = null;

    public static TheDatabase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context,TheDatabase.class,"the_database.db")
                    .allowMainThreadQueries()
                    .build();
        }
        return instance;
    }
}

和 Activity 例如:-

public class MainActivity extends AppCompatActivity {

    TheDatabase db;
    AllDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = TheDatabase.getInstance(this);
        dao = db.getAllDao();

        long phone01ProductId = dao.insert(new Phone("PhoneMaker001","Model001","Color001","100Mb",111.11F));
        long phone02ProductId = dao.insert(new Phone("PhoneMaker002","Model002","Color002","200Mb",222.22F));

        dao.insert(new Customer("c001","password001","firstname001","lastname001","address001","city001","country001","postcode001",(int) phone01ProductId));
        dao.insert(new Customer("c002","password002","firstname002","lastname002","address002","city002","country002","postcode002",(int) phone02ProductId));

        for(CustomerWithPhoneDetails cwpd: dao.getAllCustomersWithPhoneDeytails()) {
            Log.d("DBINFO","Customer is " + cwpd.customer.getUserName() + " etc.  Phone is " + cwpd.phoneDetails.getProductId() + " etc." );
        }
    }
}
  • 请注意,suitable 构造函数已在 Phone 和 Customer class (default/empty 构造函数和一,使用 @Ignore 注释进行注释,允许所有值禁止传递 id,如下例中所用)

  • 请注意,最好将 long 而不是 int 用于 id 列。

结果

日志 :-

D/DBINFO: Customer is c001 etc.  Phone is 1 etc.
D/DBINFO: Customer is c002 etc.  Phone is 2 etc.

应用检查 :-

和:-