Android-多数据库一个项目 [英] Android - Multiple database one project

查看:131
本文介绍了Android-多数据库一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下,使用Room Persistence Library是否可以在一个项目下拥有多个数据库?动态更改数据库的选择. 谢谢

I would like to ask if is possible to have multiple database under one project, with Room Persistence Library? Changing dynamic the selection of the database. Thanks

推荐答案

有可能. 假设您有两组实体和两组DAO.您可以通过以下方式获得对两个数据库的访问权限:

It is possible. Let's assume you have two sets of entities and two sets of DAOs. You can obtain access to two databases by:

  • 创建两个扩展RoomDatabase的类:

AppDatabase 1:

AppDatabase 1:

@Database(entities = {/*... the first set of entities ...*/}, version = 1)
public abstract class AppDatabase1 extends RoomDatabase {
    // the first set of DAOs
}

AppDatabase2:

AppDatabase2:

@Database(entities = {/*... the second set of entities ...*/}, version = 1)
public abstract class AppDatabase2 extends RoomDatabase {
    // the second set of DAOs
}

  • 实例化两个数据库:
  • 请注意,您将使用两个不同的文件名.

    Note that you'll use two different file names.

    AppDatabase db1 = Room.databaseBuilder(getApplicationContext(), AppDatabase1.class, "database1.db").build();
    
    AppDatabase db2 = Room.databaseBuilder(getApplicationContext(), AppDatabase2.class, "database2.db").build();
    

    在这种情况下,您可以同时使用两个数据库,但无法在它们之间创建查询.如果需要附加两个数据库,则应查看提供的@Anees链接

    In this case, you can use both databases, but you won't be able to create queries between them. If you need to attach the two databases, then you should take a look at the link @Anees provided

    这篇关于Android-多数据库一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆