具有复杂 Json 结构的房间 [英] Room with complex Json structure

查看:68
本文介绍了具有复杂 Json 结构的房间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Room 的新手,目前正在做我的一个项目,我应该在其中插入一些改造的 GSON 数据.首先,让我在下面展示我的 JSON,它会给出一个清晰的结构.

<代码>{组织":{id":0,标题":字符串",描述":HTML 字符串",风格":{导航背景颜色":#cd1325","navigationTextColor": "#ffffff",topBarLabel":27July2015abcd",topBarBackgroundColor":#cd1325",topBarTextColor":#ffffff",bodyBackgroundColor":#f5c233",bodyTextColor":#646363",横幅背景颜色":#ffffff",bannerTextColor":#000000",buttonBackgroundColor":#000000",buttonTextColor":#ffffff",baseTextSize":0,htmlWrapper":字符串"}登录选项":[{名称":字符串",标题":电子邮件",描述":字符串",状态":字符串",allowed_email_domain":字符串",restricted_email_domain":字符串";}, {名称":字符串",标题"e:GOOGLE",描述":字符串",网址":字符串",clientId":字符串",clientSecret":字符串",redirectUri":字符串",状态":字符串",nonce":字符串",authorizationEndpointUri":字符串",tokenEndpointUri":字符串"}]}

}

我正在通过改造来解析这个,效果很好.以下是从

好的.现在我必须通过我的存储库将这些插入到 Room 数据库中,我面临着很多困难.任何人都可以帮助我如何创建实体以及如何将这些数据模型插入​​房间.仍然不确定是将 GSON 模型插入 Room 还是创建实体并将解析数据放入这些模型然后插入.到目前为止我所尝试的.

登录选项表

@Parcelize@实体公共类登录选项表{@列信息@PrimaryKey(autoGenerate = true)公共长登录OpnId;@ColumnInfo(name = "login_options_name")公共字符串名称;@ColumnInfo(name = "login_options_title")公共字符串标题;@ColumnInfo(name = "login_options_description")公共字符串描述;@列信息公共字符串状态;@列信息public String allowedEmailDomain;@列信息公共字符串受限制的电子邮件域;@列信息公共字符串网址;@列信息公共字符串clientId;@列信息公共字符串clientSecret;@列信息公共字符串redirectUri;@列信息公共字符串随机数;@列信息公共字符串授权端点Uri;@列信息public String tokenEndpointUri;公共静态列表fromObject(Listm选项){List组 = 新的 ArrayList();for(int i=0; i

}

样式实体:

@Parcelize@实体公共类样式表{@列信息@PrimaryKey(autoGenerate = true)公共长样式Id;@列信息公共字符串导航背景颜色;@列信息公共字符串导航文本颜色;@列信息公共字符串 topBarLabel;@列信息公共字符串 topBarBackgroundColor;@列信息公共字符串 topBarTextColor;@列信息公共字符串 bodyBackgroundColor;@列信息公共字符串 bodyTextColor;@列信息公共字符串横幅背景颜色;@列信息公共字符串横幅文本颜色;@列信息公共字符串按钮背景颜色;@列信息公共字符串按钮文本颜色;@列信息公共整数 baseTextSize;@列信息公共字符串 htmlWrapper;公共静态 StyleTable fromObject(Style mStyle) {StyleTable st = new StyleTable();st.navigationBackgroundColor = mStyle.getNavigationBackgroundColor();st.navigationTextColor = mStyle.getNavigationTextColor();st.topBarLabel = mStyle.getTopBarLabel();st.topBarBackgroundColor = mStyle.getTopBarBackgroundColor();st.topBarTextColor = mStyle.getTopBarTextColor();st.bannerBackgroundColor = mStyle.getBodyBackgroundColor();st.bannerTextColor = mStyle.getBannerTextColor();st.buttonBackgroundColor = mStyle.getButtonBackgroundColor();st.buttonTextColor = mStyle.getButtonTextColor();st.baseTextSize = mStyle.getBaseTextSize();st.htmlWrapper = mStyle.getHtmlWrapper();返回 st;}

}

组织实体:

@Parcelize@Entity(foreignKeys = {@ForeignKey(entity = StyleTable.class, parentColumns ="styleId", childColumns = "stId"),@ForeignKey(entity = LoginOptionsTable.class, parentColumns =loginOptionId", childColumns = loginOpnId")})公共类组织表{@列信息@首要的关键公共长ID;@列信息公共字符串标题;@列信息公共字符串描述;@列信息公共长stId;//TODo 使其适用于多表@列信息public Long loginOptionsId;@忽略公共 StyleTable 样式;@忽略公共列表登录选项 = 空;public static OrgTable fromObject(组织组织){OrgTable org = new OrgTable();org.id = organization.getId();org.title = organization.getTitle();org.description = organization.getDescription();StyleTable st = StyleTable.fromObject(organization.getStyle());org.style = st;//通过Id建立关系org.stId = st.styleId;List洛 =LoginOptionsTable.fromObject(organization.getLoginOptions());org.loginOptions = lo;//通过Id建立关系org.loginOptionsId = lo.get(0).loginOpnId;返回组织;}

}

DAO

@Dao公共接口 OrgDAO {@Query(SELECT * FROM OrgTable")组织表 getOrganization();@插无效插入组织(组织表组织);

}

我尝试创建这些,但无法理解如何保持这些之间的关系并插入/获取保存的数据.

解决方案

我尝试创建这些,但无法理解如何保持这些之间的关系并插入/获取保存的数据.

您可以通过以下两种方式执行此操作:

  • 一个包含所有三个表的 POJO @Embedded(仅适用于 1 个组织 -> 1 个登录和 1 个样式)

  • 带有 OrgTable @Embedded 的 POJO 和带有 @Relation 注释的 LoginOptionsTable 和 StyleTable

第一个示例(所有三个表 @Embedded)是 :-

class OrgWithLoginAndStyle {/* 注意使用查询用登录表加入 Orgtable并用样式表加入 Orgtable*/@嵌入式组织表组织表;@嵌入式登录选项表登录选项表;@嵌入式StyleTable styleTable;}

使用此功能的 Dao 示例是:-

@Query("SELECT * FROM OrgTable " +"JOIN StyleTable ON StyleTable.styleId = OrgTable.stId "+JOIN LoginOptionsTable ON LoginOptionsTable.loginOpnId = OrgTable.loginOptionsId")ListgetOrganizationLoginAndStyle();

  • 这在查询方面更加灵活,因为所有列都可用于 WHERE 子句等,但查询更复杂.

第二个例子(LoginOptionsTable 和 StyleTable 带有 @Relation 注释):-

class OrganizationWithLoginOptionsAndWithStyles {@嵌入式组织表组织表;@Relation(entity = LoginOptionsTable.class,parentColumn = "loginOptionsId",entityColumn = "loginOpnId")List登录选项表;@Relation(entity = StyleTable.class,parentColumn = "stId",entityColumn = "styleId")列表<样式表>样式表;}

  • 这可能更容易编码.但是,它的效率较低,因为 Styles 和 LoginOptions 是为每个 OrgTable 独立检索的.因此,查询更简单,因为您只需要获取 OrgTable(s).Room 负责构建相关对象的工作.查询仅限于 OrgTable 列上的 WHERE 等(如果您加入了其他表,此类子句可能不会获得所需的结果(在您的情况下可能没问题,因为每个 OrgTable 对象只有 1 个 LoginOptions 和 1 个样式))

使用此功能的 Dao 示例是:-

@Transaction@Query(SELECT * FROM OrgTable")ListgetOrganizationsLoginsAndStyles();

  • 请注意,建议使用 @Transaction 是因为(我相信)正在运行底层查询以获取 LoginOptionsTable 对象和 StyleTable 对象.

注意关于您的 getOrganization 查询(见评论)

@Query(SELECT * FROM OrgTable")//OrgTable getOrganization();/* <<<<<<<<<<WRONG 应该是一个列表 */列表<OrgTable>getOrganizations();

还有你的insertOrg

@Insert//void insertOrg(OrgTable org)长插入组织(组织表组织);/* <<<<<<<<<<也可以允许获取插入行的id */

<块引用>

好的.现在我必须通过我的存储库将这些插入到 Room 数据库中,为此我遇到了很多困难.

而且我相信您的 OrgTable FK 定义应该按照 :-

@Entity(foreignKeys = {@ForeignKey(entity = StyleTable.class, parentColumns ="styleId", childColumns = "stId"),@ForeignKey(entity = LoginOptionsTable.class, parentColumns =loginOpnId",childColumns = loginOptionsId")})

  • 即 LoginOptions 子级和父级是错误的,而且父级应该是 loginOptionsId 而不是 loginOptionId(不是 s 后的 Option).

基本测试

除了创建OrgDao 类之外,使用上面的以下代码:-

@Dao公共接口 OrgDAO {@Query(SELECT * FROM OrgTable")//OrgTable getOrganization();/* <<<<<<<<<<WRONG 应该是一个列表 */列表<OrgTable>getOrganizations();@Query("SELECT * FROM OrgTable " +"JOIN StyleTable ON StyleTable.styleId = OrgTable.stId "+JOIN LoginOptionsTable ON LoginOptionsTable.loginOpnId = OrgTable.loginOptionsId")ListgetOrganizationLoginAndStyle();@交易@Query(SELECT * FROM OrgTable")ListgetOrganizationsLoginsAndStyles();@插//void insertOrg(OrgTable org)长插入组织(组织表组织);/* <<<<<<<<<<也可以允许获取插入行的id */@插长插入样式(样式表样式表);@插long insertLoginOptions(LoginOptionsTable loginOptionsTable);}

并使用:-

@Database(entities = {OrgTable.class,StyleTable.class,LoginOptionsTable.class},version = 1)抽象类 OrgLoginStyleDatabase 扩展了 RoomDatabase {抽象 OrgDAO getOrgDao();}

还有一个活动(注意你的一些代码被注释掉了,即@Parcelize和实体的@Ignored构造函数的使用):-

公共类 MainActivity 扩展 AppCompatActivity {OrgLoginStyleDatabase db;OrgDAO 道;public static final String TAG =OLSINFO";@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);db = Room.databaseBuilder(this,OrgLoginStyleDatabase.class,orgloginoptionsstyle.db").allowMainThreadQueries().建造();dao = db.getOrgDao();样式表 s1 = 新样式表();s1.bannerBackgroundColor = "X";s1.bannerTextColor = "X";s1.baseTextSize = 20;s1.bodyBackgroundColor = "X";s1.bodyTextColor = "X";s1.buttonBackgroundColor = "X";s1.buttonTextColor = "X";s1.htmlWrapper = "X";s1.navigationBackgroundColor = "X";s1.navigationTextColor = "X";s1.styleId = 100;s1.topBarBackgroundColor = "X";s1.topBarLabel = "X";s1.topBarTextColor = "X";long s1Id = dao.insertStyle(s1);LoginOptionsTable l1 = new LoginOptionsTable();l1.allowedEmailDomain = "Y";l1.authorizationEndpointUri = "Y";l1.clientId =Y";l1.clientSecret = "Y";l1.description =Y";l1.loginOpnId = 1000;l1.name = "Y";l1.nonce =Y";l1.redirectUri = "Y";l1.restrictedEmailDomain = "Y";l1.state =Y";l1.title = "Y";l1.url = "Y";long l1Id = dao.insertLoginOptions(l1);OrgTable o1 = new OrgTable();o1.description =Z";o1.id = 10000;o1.loginOptionsId = l1Id;o1.stId = s1Id;dao.insertOrg(o1);列表<OrgTable>orgTableList = dao.getOrganizations();for(OrgTable o: orgTableList) {logOrgTable(o,"FROM getOrganizations -> ");}List组织LoginsAndStylesList = dao.getOrganizationsLoginsAndStyles();for(OrganizationWithLoginOptionsAndWithStyles owloaws:organizationLoginsAndStylesList){logOrgTable(owloaws.orgTable,"FROM (@Relations) getOrganizationsLoginsAndStyles -> ");for(LoginOptionsTable 批量:owloaws.loginOptionsTables){logLoginOptionsTable(lot,"\t");}for(StyleTable s: owloaws.styleTables) {logStyleTable(s,"\t");}}List猫头鹰 = dao.getOrganizationLoginAndStyle();for(OrgWithLoginAndStyle o:猫头鹰){logOrgTable(o.orgTable,"FROM (@Embeddeds) getOrganizationLoginAndStyle -> ");logLoginOptionsTable(o.loginOptionsTable,"\t");logStyleTable(o.styleTable,"\t");}}private void logOrgTable(OrgTable o,String preamble) {Log.d(TAG,preamble + "OrgTable Description = " + o.description + " ID = " + o.id);}私有无效 logStyleTable(StyleTable s, 字符串序言) {Log.d(TAG,preamble + "StyleTable Description = " + s.topBarTextColor + "ID =" + s.styleId);}私人无效logLoginOptionsTable(LoginOptionsTable l,字符串序言){Log.d(TAG,preamble + "LoginOptionsTable Description = " + l.description + "ID = " + l.loginOpnId);}}

结果

运行时(只会在使用硬编码 ID 时运行一次)输出到日志的结果是:-

2021-04-12 21:51:50.981 D/OLSINFO: FROM getOrganizations ->组织表描述 = Z ID = 100002021-04-12 21:51:50.987 D/OLSINFO:FROM (@Relations) getOrganizationsLoginsAndStyles ->组织表描述 = Z ID = 100002021-04-12 21:51:50.987 D/OLSINFO:登录选项表描述 = Y ID = 10002021-04-12 21:51:50.987 D/OLSINFO:样式表描述 = X ID =1002021-04-12 21:51:50.989 D/OLSINFO:FROM (@Embeddeds) getOrganizationLoginAndStyle ->组织表描述 = Z ID = 100002021-04-12 21:51:50.989 D/OLSINFO:登录选项表描述 = Y ID = 10002021-04-12 21:51:50.989 D/OLSINFO:样式表描述 = X ID =100

  • 所有三个对象都已成功插入,并且所有三个查询都按预期工作.

I am pretty new in Room and currently doing one of my projects in which I'm supposed to insert some retrofit GSON data into it. First of all, let me show my JSON below which will give a clear structure.

{
"organization": {
    "id": 0,
    "title": "string",
    "description": "HTML String",
    "style": {
        "navigationBackgroundColor": "#cd1325",
        "navigationTextColor": "#ffffff",
        "topBarLabel": "27July2015abcd",
        "topBarBackgroundColor": "#cd1325",
        "topBarTextColor": "#ffffff",
        "bodyBackgroundColor": "#f5c233",
        "bodyTextColor": "#646363",
        "bannerBackgroundColor": "#ffffff",
        "bannerTextColor": "#000000",
        "buttonBackgroundColor": "#000000",
        "buttonTextColor": "#ffffff",
        "baseTextSize": 0,
        "htmlWrapper": "string"
    }
    "login_options": [{
            "name": "string",
            "title": "EMAIL",
            "description": "string",
            "state": "string",
            "allowed_email_domain": "string",
            "restricted_email_domain": "string"
        }, {
            "name": "string",
            "titl"e: "GOOGLE",
            "description": "string",
            "url": "string",
            "clientId": "string",
            "clientSecret": "string",
            "redirectUri": "string",
            "state": "string",
            "nonce": "string",
            "authorizationEndpointUri": "string",
            "tokenEndpointUri": "string"
        }
    ]
}

}

I am parsing this with retrofit which is working pretty well. Below are the model classes names which has created from https://www.jsonschema2pojo.org/

Ok. Now I have to insert these into the Room database through my repository for which I am facing a lot of difficulties. Can anyone help me with how to create the entities and how to insert these data models into the Room. Still not sure whether to insert the GSON models to Room or to create Entities and put the parsing data to those and then to insert. What I have tried till now.

LoginOptionsTable

@Parcelize
@Entity
public class LoginOptionsTable {

@ColumnInfo
@PrimaryKey(autoGenerate = true)
public long loginOpnId;

@ColumnInfo(name = "login_options_name")
public String name;

@ColumnInfo(name = "login_options_title")
public String title;

@ColumnInfo(name = "login_options_description")
public String description;

@ColumnInfo
public String state;

@ColumnInfo
public String allowedEmailDomain;

@ColumnInfo
public String restrictedEmailDomain;

@ColumnInfo
public String url;

@ColumnInfo
public String clientId;

@ColumnInfo
public String clientSecret;

@ColumnInfo
public String redirectUri;

@ColumnInfo
public String nonce;

@ColumnInfo
public String authorizationEndpointUri;

@ColumnInfo
public String tokenEndpointUri;

public static List<LoginOptionsTable> fromObject(List<LoginOption> 
mOptions){

    List<LoginOptionsTable> groups = new ArrayList<>();

    for(int i=0; i<mOptions.size(); i++){
        LoginOptionsTable st = new LoginOptionsTable();

        st.name = mOptions.get(i).getName();
        st.title = mOptions.get(i).getTitle();
        st.description = mOptions.get(i).getDescription();
        st.state = mOptions.get(i).getState();
        st.allowedEmailDomain = mOptions.get(i).getAllowedEmailDomain();
        st.restrictedEmailDomain = 
        mOptions.get(i).getRestrictedEmailDomain();
        st.url = mOptions.get(i).getUrl();
        st.clientId = mOptions.get(i).getClientId();
        st.clientSecret = mOptions.get(i).getClientSecret();
        st.redirectUri = mOptions.get(i).getRedirectUri();
        st.nonce = mOptions.get(i).getNonce();
        st.authorizationEndpointUri = 
        mOptions.get(i).getAuthorizationEndpointUri();
        st.tokenEndpointUri = mOptions.get(i).getTokenEndpointUri();

        groups.add(st);
    }


    return groups;
}

}

Style Entity:

@Parcelize
@Entity
public class StyleTable {

@ColumnInfo
@PrimaryKey(autoGenerate = true)
public long styleId;

@ColumnInfo
public String navigationBackgroundColor;
@ColumnInfo
public String navigationTextColor;
@ColumnInfo
public String topBarLabel;
@ColumnInfo
public String topBarBackgroundColor;
@ColumnInfo
public String topBarTextColor;
@ColumnInfo
public String bodyBackgroundColor;
@ColumnInfo
public String bodyTextColor;
@ColumnInfo
public String bannerBackgroundColor;
@ColumnInfo
public String bannerTextColor;
@ColumnInfo
public String buttonBackgroundColor;
@ColumnInfo
public String buttonTextColor;
@ColumnInfo
public Integer baseTextSize;
@ColumnInfo
public String htmlWrapper;


public static StyleTable fromObject(Style mStyle) {
    StyleTable st = new StyleTable();

    st.navigationBackgroundColor = mStyle.getNavigationBackgroundColor();
    st.navigationTextColor = mStyle.getNavigationTextColor();
    st.topBarLabel = mStyle.getTopBarLabel();
    st.topBarBackgroundColor = mStyle.getTopBarBackgroundColor();
    st.topBarTextColor = mStyle.getTopBarTextColor();
    st.bannerBackgroundColor = mStyle.getBodyBackgroundColor();
    st.bannerTextColor = mStyle.getBannerTextColor();
    st.buttonBackgroundColor = mStyle.getButtonBackgroundColor();
    st.buttonTextColor = mStyle.getButtonTextColor();
    st.baseTextSize = mStyle.getBaseTextSize();
    st.htmlWrapper = mStyle.getHtmlWrapper();

    return st;
}

}

OrgEntity:

@Parcelize
@Entity(foreignKeys = {@ForeignKey(entity = StyleTable.class, parentColumns = 
"styleId", childColumns = "stId"),
    @ForeignKey(entity = LoginOptionsTable.class, parentColumns = 
"loginOptionId", childColumns = "loginOpnId")
})
public class OrgTable {

@ColumnInfo
@PrimaryKey
public long id;

@ColumnInfo
public String title;

@ColumnInfo
public String description;

@ColumnInfo
public long stId;

//TODo make it for mutiple table
@ColumnInfo
public Long loginOptionsId;

@Ignore
public StyleTable style;

@Ignore
public List<LoginOptionsTable> loginOptions = null;

public static OrgTable fromObject(Organization organization){
    OrgTable org = new OrgTable();
    org.id = organization.getId();
    org.title = organization.getTitle();
    org.description = organization.getDescription();
    StyleTable st = StyleTable.fromObject(organization.getStyle());
    org.style = st;
    //make the relation through Id
    org.stId = st.styleId;

    List<LoginOptionsTable> lo = 
   LoginOptionsTable.fromObject(organization.getLoginOptions());
    org.loginOptions = lo;
    //make the relation through Id
    org.loginOptionsId = lo.get(0).loginOpnId;


return org;
}

}

DAO

@Dao
public interface OrgDAO {

@Query("SELECT * FROM OrgTable")
OrgTable getOrganization();

@Insert
void insertOrg(OrgTable org);

}

I have tried to create these, but not able to understand how to keep the relation between these and insert/get the saved data.

解决方案

I have tried to create these, but not able to understand how to keep the relation between these and insert/get the saved data.

You can do this 2 ways either with:

  • a POJO with all three tables @Embedded (only suitable for 1 Org -> 1 Login and 1 Style)

  • with a POJO with the OrgTable @Embedded and with the LoginOptionsTable and StyleTable with @Relation annotations

An example of the first (all three tables @Embedded) being :-

class OrgWithLoginAndStyle {

    /* Note use Query that
        JOINS the Orgtable with the Login table
        and JOINS the Orgtable with the Style table
     */

    @Embedded
    OrgTable orgTable;
    @Embedded
    LoginOptionsTable loginOptionsTable;
    @Embedded
    StyleTable styleTable;

}

An example of a Dao that utilises this is:-

@Query("SELECT * FROM OrgTable " +
        "JOIN StyleTable ON StyleTable.styleId = OrgTable.stId " +
        "JOIN LoginOptionsTable ON LoginOptionsTable.loginOpnId = OrgTable.loginOptionsId")
List<OrgWithLoginAndStyle> getOrganizationLoginAndStyle();

  • This is more flexible query wise as all columns are available for WHERE clauses etc but the query is more complicated.

An example of the second (with @Relation annotations for the LoginOptionsTable and the StyleTable) :-

class OrganizationWithLoginOptionsAndWithStyles {

    @Embedded
    OrgTable orgTable;
    @Relation(entity = LoginOptionsTable.class,parentColumn = "loginOptionsId",entityColumn = "loginOpnId")
    List<LoginOptionsTable> loginOptionsTables;
    @Relation(entity = StyleTable.class,parentColumn = "stId",entityColumn = "styleId")
    List<StyleTable> styleTables;
}

  • This is perhaps simpler to code. However, it is less efficient as the Styles and LoginOptions are retrieved independently for each each OrgTable. As such the query is simpler as you only need to get the OrgTable(s). Room does the work of building related objects. The query is limited to WHERE etc on only the OrgTable columns (if you JOINed the other tables such clauses would possibly not have the desired result (probably OK in your case as there is only 1 LoginOptions and 1 Style per OrgTable object))

An example of a Dao that utilises this is:-

@Transaction
@Query("SELECT * FROM OrgTable")
List<OrganizationWithLoginOptionsAndWithStyles> getOrganizationsLoginsAndStyles();

  • Note that @Transaction is advised due to (I believe) underlying queries being run to get the LoginOptionsTable objects and the StyleTable objects.

Note Regarding your getOrganization query (see comment)

@Query("SELECT * FROM OrgTable")
//OrgTable getOrganization(); /* <<<<<<<<<< WRONG should be a List */
List<OrgTable> getOrganizations();

And your insertOrg

@Insert
//void insertOrg(OrgTable org)
long insertOrg(OrgTable org); /* <<<<<<<<<< might as well allow the id of the inserted row to be obtained */

Ok. Now I have to insert these into the Room database through my repository for which I am facing a lot of difficulties.

And I believe that your OrgTable FK definitions should be as per :-

@Entity(foreignKeys = {@ForeignKey(entity = StyleTable.class, parentColumns =
        "styleId", childColumns = "stId"),
        @ForeignKey(entity = LoginOptionsTable.class, parentColumns =
                "loginOpnId", childColumns = "loginOptionsId")
})

  • i.e the LoginOptions child and parent are the wrong way round and also that the parent should be loginOptionsId rather than loginOptionId (not s after Option).

Basic test

Using the following code as above except making the OrgDao class :-

@Dao
public interface OrgDAO {

    @Query("SELECT * FROM OrgTable")
    //OrgTable getOrganization(); /* <<<<<<<<<< WRONG should be a List */
    List<OrgTable> getOrganizations();

    @Query("SELECT * FROM OrgTable " +
            "JOIN StyleTable ON StyleTable.styleId = OrgTable.stId " +
            "JOIN LoginOptionsTable ON LoginOptionsTable.loginOpnId = OrgTable.loginOptionsId")
    List<OrgWithLoginAndStyle> getOrganizationLoginAndStyle();

    @Transaction
    @Query("SELECT * FROM OrgTable")
    List<OrganizationWithLoginOptionsAndWithStyles> getOrganizationsLoginsAndStyles();

    @Insert
    //void insertOrg(OrgTable org)
    long insertOrg(OrgTable org); /* <<<<<<<<<< might as well allow the id of the inserted row to be obtained */

    @Insert
    long insertStyle(StyleTable styleTable);

    @Insert
    long insertLoginOptions(LoginOptionsTable loginOptionsTable);
}

And using :-

@Database(entities = {OrgTable.class,StyleTable.class,LoginOptionsTable.class},version = 1) abstract class OrgLoginStyleDatabase extends RoomDatabase { abstract OrgDAO getOrgDao(); }

And with an activity (note that some of your code was commented out namely the use of @Parcelize and the @Ignored Concstructors for the Entities) :-

public class MainActivity extends AppCompatActivity {

    OrgLoginStyleDatabase db;
    OrgDAO dao;
    public static final String TAG = "OLSINFO";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = Room.databaseBuilder(this,OrgLoginStyleDatabase.class,"orgloginoptionsstyle.db")
                .allowMainThreadQueries()
                .build();
        dao = db.getOrgDao();

        StyleTable s1 = new StyleTable();
        s1.bannerBackgroundColor = "X";
        s1.bannerTextColor = "X";
        s1.baseTextSize = 20;
        s1.bodyBackgroundColor = "X";
        s1.bodyTextColor = "X";
        s1.buttonBackgroundColor = "X";
        s1.buttonTextColor = "X";
        s1.htmlWrapper = "X";
        s1.navigationBackgroundColor = "X";
        s1.navigationTextColor = "X";
        s1.styleId = 100;
        s1.topBarBackgroundColor = "X";
        s1.topBarLabel = "X";
        s1.topBarTextColor = "X";
        long s1Id = dao.insertStyle(s1);
        LoginOptionsTable l1 = new LoginOptionsTable();
        l1.allowedEmailDomain = "Y";
        l1.authorizationEndpointUri = "Y";
        l1.clientId = "Y";
        l1.clientSecret = "Y";
        l1.description = "Y";
        l1.loginOpnId = 1000;
        l1.name = "Y";
        l1.nonce = "Y";
        l1.redirectUri = "Y";
        l1.restrictedEmailDomain = "Y";
        l1.state = "Y";
        l1.title = "Y";
        l1.url = "Y";
        long l1Id = dao.insertLoginOptions(l1);
        OrgTable o1 = new OrgTable();
        o1.description = "Z";
        o1.id = 10000;
        o1.loginOptionsId = l1Id;
        o1.stId = s1Id;
        dao.insertOrg(o1);
        List<OrgTable> orgTableList = dao.getOrganizations();
        for(OrgTable o: orgTableList) {
            logOrgTable(o,"FROM getOrganizations -> ");
        }
        List<OrganizationWithLoginOptionsAndWithStyles> organizationsLoginsAndStylesList = dao.getOrganizationsLoginsAndStyles();
        for(OrganizationWithLoginOptionsAndWithStyles owloaws: organizationsLoginsAndStylesList) {
            logOrgTable(owloaws.orgTable,"FROM (@Relations) getOrganizationsLoginsAndStyles -> ");
            for(LoginOptionsTable lot: owloaws.loginOptionsTables) {
                logLoginOptionsTable(lot,"\t");
            }
            for(StyleTable s: owloaws.styleTables) {
                logStyleTable(s,"\t");
            }
        }
        List<OrgWithLoginAndStyle> owlas = dao.getOrganizationLoginAndStyle();
        for(OrgWithLoginAndStyle o: owlas) {
            logOrgTable(o.orgTable,"FROM (@Embeddeds) getOrganizationLoginAndStyle -> ");
            logLoginOptionsTable(o.loginOptionsTable,"\t");
            logStyleTable(o.styleTable,"\t");
        }
    }

    private void logOrgTable(OrgTable o,String preamble) {
        Log.d(TAG,preamble + "OrgTable Description = " + o.description + " ID = " + o.id);
    }
    private void logStyleTable(StyleTable s, String preamble) {
        Log.d(TAG,preamble + "StyleTable Description = " + s.topBarTextColor + " ID =" + s.styleId);
    }
    private void logLoginOptionsTable(LoginOptionsTable l, String preamble) {
        Log.d(TAG,preamble + "LoginOptionsTable Description = " + l.description + " ID = " + l.loginOpnId);
    }
}

Result

When run (will only run the once as hard coded ID's have been used) the result output to the log was :-

2021-04-12 21:51:50.981 D/OLSINFO: FROM getOrganizations -> OrgTable Description = Z ID = 10000

2021-04-12 21:51:50.987 D/OLSINFO: FROM (@Relations) getOrganizationsLoginsAndStyles -> OrgTable Description = Z ID = 10000
2021-04-12 21:51:50.987 D/OLSINFO:  LoginOptionsTable Description = Y ID = 1000
2021-04-12 21:51:50.987 D/OLSINFO:  StyleTable Description = X ID =100

2021-04-12 21:51:50.989 D/OLSINFO: FROM (@Embeddeds) getOrganizationLoginAndStyle -> OrgTable Description = Z ID = 10000
2021-04-12 21:51:50.989 D/OLSINFO:  LoginOptionsTable Description = Y ID = 1000
2021-04-12 21:51:50.989 D/OLSINFO:  StyleTable Description = X ID =100

  • All three objects were inserted successfully and all three queries worked as expected.

这篇关于具有复杂 Json 结构的房间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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