通过Room 库的@Relation和@ForeignKey可以很容易地在数据库的两个表之间建立关系
在SQLite
我们可以连接来自不同数据库的表
但是我如何通过 Room Library 做到这一点?
通过Room 库的@Relation和@ForeignKey可以很容易地在数据库的两个表之间建立关系
在SQLite
我们可以连接来自不同数据库的表
但是我如何通过 Room Library 做到这一点?
在 Room 中,您将无法编写跨数据库外键。同样的限制适用于 SQLite。但是,关系的存在不需要外键,它是用于强制关系完整性的约束(规则)。
同样,在 Room 中,您将无法使用跨数据库关系。@Relation 注释基本上定义了用于 Room 生成的查询的连接条件。
但是,您可以通过对象以编程方式在两个房间数据库之间建立关系。
示例 作为一个基本示例(基于我正在查看的 Room 数据库)考虑:-
第一个数据库(已经存在),其抽象类是Database,它有一个在Login类中定义的实体,并且在接口AllDao中具有所有 Dao 。
一个具有 4 个成员/字段/列的登录对象,重要的是一个带有用户哈希的 byte[],名为userHashed。
第二个数据库,其抽象类是OtherDatabase ,它在UserLog类中定义了一个实体,并且在接口OtherDBDao中具有所有 Dao 。
具有 3 个成员/字段/列的UserLog对象,重要/相关列是相应用户(登录)(登录表中的父级)的哈希。
综上所述,请考虑以下几点:-
//First Database
db = Room.databaseBuilder(this,Database.class,"mydb")
.allowMainThreadQueries()
.build();
allDao = db.allDao();
//Other Database
otherdb = Room.databaseBuilder(this,OtherDatabase.class,"myotherdb")
.allowMainThreadQueries()
.build();
otherDBDao = otherdb.otherDBDao();
// Add some user rows to first db
Login l1 = new Login(t1,t2,t3,10);
Login l2 = new Login(t2,t3,t4,20);
Login l3 = new Login(t3,t4,t1,30);
Login l4 = new Login(t4,t1,t2,40);
allDao.insertLogin(l1);
allDao.insertLogin(l2);
allDao.insertLogin(l3);
allDao.insertLogin(l4);
// Get one of the Login objects (2nd inserted)
Login[] extractedLogins = allDao.getLoginsByUserHash(t2);
// Based upon the first Login retrieved (only 1 will be)
// add some userlog rows to the other database according to the relationship
if (extractedLogins.length > 0) {
for (int i = 0;i < 10; i++) {
Log.d("USERLOG_INSRT","Inserting UserLog Entry");
otherDBDao.insertUserLog(new UserLog(extractedLogins[0].getUserHashed()));
}
}
UserLog[] extractedUserLogs = otherDBDao.getUserLogs(extractedLogins[0].getUserHashed());
for(UserLog ul : extractedUserLogs ) {
// ....
}
以上 :-
当然,这样的设计可能永远不会被使用。
以下是触发断点时调试屏幕的屏幕截图:-