繁体   English   中英

如何在一张表中与数组建立关系,而在其他表中则不然?

[英]How to do relation with array in one table but not in other?

(更新)我有这样的表:

@Entity(tableName = "author_table")
public class Author {

  @PrimaryKey(autoGenerate = true)
  @ColumnInfo(name = "authorId")
  private int mAuthorId;
    
  @ColumnInfo(name = "authorName")
  private String mAuthorName;

  @ColumnInfo(name = "authorPublisherName")
  private String mAuthorPublisherName;

@Entity(tableName = "book_table")
public class Book{

  @PrimaryKey(autoGenerate = true)
  @ColumnInfo(name = "bookId")
  private int mBookId;

  @ColumnInfo(name = "bookName")
  private String mBookName;

  @ColumnInfo(name = "bookAuthors")
  private String[] bookAuthors;

数周以来,我一直在尝试并重新尝试此方法,但我无法完成任何工作。 我试过变通的方法来做到这一点,没有任何关系,没有运气。 我尝试过各种关系(外键、关系、连接等)。 “知道”数据库理论很奇怪,并且已经参加了这方面的 uni 课程,但我无法让它与 Android Room 一起使用。 如何从一本书中获取或查询作者或作者出版商? (如果我问得对的话......)

我想要这本书的所有作者的出版商。

此外,嵌入如何影响存储? 如果我在每本书中“嵌入”一个作者(Android 应用程序中的数千名作者和数千本书),这是否基本上会在每个 Book 实体中创建每个 Author 的副本或副本?

我试过了:

  @Query("select authorPublisherNamefrom author_table where authorName IN (:names)")
  LiveData<List<String>> getAllThePublishers(List<String> names);

这给了我 1 的列表大小。我假设它只是 ping 查询列表中得分为真的第一个名称。

然后我尝试创建另一个类,例如@ sergiy tikhonov 的评论方式以及我如何表示与 Android Room 的多对多关系?

@Entity(primaryKeys = {"authName", "bookAuth"})
public class BookAndAuthors{

  private int authName, bookAuth;
}

public class BooksWithAuthors{

  @Embedded
  public Book book;
  @Relation(
      parentColumn = "authorName",
      entityColumn = "bookAuthors",
      associateBy = @Junction(
          value = BookAndAuthors.class,
          parentColumn = "authName",
          entityColumn = "bookAuth")
  )
  public List<FastMoveEntity> fastMoveList;
}

但是现在我不知道如何查询以获取发布者(authorPublisherName)。

旁注:随着 sergiy 的回答是将钥匙绑在课堂上,我不知道该怎么做或让它发挥作用。 他们是否必须以某种方式插入这种关系?

如果子表使用字符串数组而父表具有字符串值,我如何/如何引用或使用外键?

我建议不要搜索这个问题的答案,而只是改变你的表格结构。 对于所有关系数据库(和 Sqlite 就在其中),好的(并且被时间证明)方法是实现表的规范化

因此,不要使用两个表,而是使用三个。 第三个是BookAuthors 同样常见的方法是为您的表使用整数主键。

@Entity(tableName = "author_table")
public class Author {

  @PrimaryKey
  @ColumnInfo(name = "id")
  public int id;

  @ColumnInfo(name = "authorName")
  private String authorName;
  ........

@Entity(tableName = "book_table")
public class Book {

  @PrimaryKey
  @ColumnInfo(name = "id")
  public int id;

  @ColumnInfo(name = "bookName")
  private String bookName;
  ........

@Entity(tableName = "book_authors_table", primaryKeys = {"bookId", "authorId"}) // you could set there foreign keys for both fields if you want
public class BookAuthors {
 
  @ColumnInfo(name = "bookId")
  public int bookId;

  @ColumnInfo(name = "authorId")
  public int authorId;
}

使用这种结构,您可以轻松获得所需的任何数据连接(所有作者的书籍和所有书面书籍的作者)。 如何实现 - 查看多对多关系的文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM