List-Detail 案例中对 DAO 和 Repository 的优化:使用相同的数据表,但针对list-detail界面构建不同的数据模型(Returning subsets of columns)

Copied from https://codelabs.developers.google.com/codelabs/build-app-with-arch-components/index.html#14

WeatherEntry's are a bit inefficient - main list only shows date, weather condition, and high/low. None of the wind speed, pressure, etc are included.

You can have the same database table, but create model objects that just get the elements you need. These do NOT need to be entities, because they don't represent tables.

detail界面对应数据模型 WeatherEntry,它包含的数据很多是list界面用不到的,所以使用LiveData>有点低效。为了解决这个问题,需要构造一个list的数据模型 ListViewWeatherEntry,但不需要构造新的数据库表,只需要从数据库中选取需要的字段即可。

Returning subsets of columns

Room allows you to return any Java-based object from your queries as long as the set of result columns can be mapped into the returned object.

public class NameTuple {
    @ColumnInfo(name="first_name")
    public String firstName;

    @ColumnInfo(name="last_name")
    public String lastName;
}

@Dao
public interface UserDao {
    @Query("SELECT first_name, last_name FROM user")
    public List<NameTuple> loadFullName();
}

Room understands that the query returns values for the first_name and last_name columns and that these values can be mapped into the fields of the NameTuple class.

通过上述代码段就可以理解 Query 返回的数据是如何 map 到 class fields的:通过@ColumnInfo 标示数据库 column 名字;如果 class field name 和 database column name 一致,则可以省略定义@ColumnInfo