可以使用此代码附加另一个数据库
@Database(entities = {Book.class, User.class}, version = 1)
public abstract class LoanDatabase extends RoomDatabase {
public abstract UserDao userDao();
public abstract BookDao bookDao();
private static LoanDatabase INSTANCE;
public static LoanDatabase getInstance(Context context,final String attachDatabaseName) {
if (INSTANCE == null) {{
INSTANCE = Room.databaseBuilder(context,
LoanDatabase.class, "LoanDatabase").addCallback(new Callback() {
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
attach(attachDatabaseName,"/data/data/com.test.roomwithdagger/databases/");
super.onOpen(db);
}
})
.build();
}}
return INSTANCE;
}
private static void attach(final String databaseName, final String databasePath) {
String sql = "ATTACH DATABASE '" + databasePath + databaseName
+ "' AS \"" + databaseName + "\";";
INSTANCE. mDatabase.execSQL(sql);
}
}
public void attachDatabase(String databaseName,String databasePath){
String sql = "ATTACH DATABASE '" + databasePath + "/" + databaseName
+ ".db' AS \"" + databaseName + "\";";
INSTANCE.mDatabase.execSQL(sql);
}
}
在 Dao 接口中,使用这样的跳过查询验证。@SkipQueryVerification
@Dao
public interface BookDao {
...
@SkipQueryVerification
@Query("SELECT * FROM main.Book b INNER JOIN LoanDatabase1.Loan l on b.Id=l.BookId where b.Id=:bookId")
Book getBookAndLoan(int bookId);
...
}
用:
LoanDatabase db = LoanDatabase.getInstance(this,"LoanDatabase1")
Book book= db.bookDao().getBookAndLoan(1)