Can use this code for attach another database
@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);
}
}
In Dao interface use @SkipQueryVerification
for skip query verification like this.
@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);
...
}
Use :
LoanDatabase db = LoanDatabase.getInstance(this,"LoanDatabase1")
Book book= db.bookDao().getBookAndLoan(1)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…