简体   繁体   中英

This might cause a full table scan when resolving the relationship, it is highly advised to create an index that covers this column

I have many-to-many relationship between User and Poll. While creating the relating class below I'm getting this warning on compile time:

warning: The column pollId in the junction entity com.example.appproject.model.user.UserPollCrossRef is being used to resolve a relationship but it is not covered by any index. This might cause a full table scan when resolving the relationship, it is highly advised to create an index that covers this column.

@Entity(primaryKeys = {"uid","pollId"})
public class UserPollCrossRef {
    @NonNull
    public String uid;
    @NonNull
    public String pollId;

    public UserPollCrossRef(@NonNull String uid, @NonNull String pollId) {
        this.uid = uid;
        this.pollId = pollId;
    }
}

I wanted to ask what does it mean and how can I fix it?

It looks as though the UserPollCrossRef is an associate/reference/mapping (and other names) table for a many-many relationship between user and poll.

what does it mean

The primary key is according to uid and pollid combined in that order, thus finding the uid is fast as the uid is the first part of the primary key.

However when/if searching for the pollid then there is no index ordered according to the pollid and hence the suggestion that such an index is created.

you may wish to consider looking at https://www.essentialsql.com/what-is-a-database-index/

Room is simple saying that in some circumstances and index may be beneficial, it is just a warning.

how can I fix it?

The simplest way is to use @ColumnInfo(index = true) eg

@Entity(primaryKeys = {"uid","pollId"})
public class UserPollCrossRef {
    @NonNull
    public String uid;
    @NonNull
    @ColumnInfo(index = true)
    public String pollId;

    public UserPollCrossRef(@NonNull String uid, @NonNull String pollId) {
        this.uid = uid;
        this.pollId = pollId;
    }
}

The alternative would be to utilise the indices parameter of the @Entity annotation eg

@Entity(primaryKeys = {"uid","pollId"},
        indices = {
        @Index(value = "pollId")
        }
)
public class UserPollCrossRef {
   @NonNull
   public String uid;
   @NonNull
   public String pollId;

   public UserPollCrossRef(@NonNull String uid, @NonNull String pollId) {
      this.uid = uid;
      this.pollId = pollId;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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