问题描述
到目前为止,为了存储在房间数据库中,我一直在为每个类使用类型转换器.像这样:
So far for storing in Room Database I've been using type converter for each classes. Like this:
@SerializedName("sidebar")
@Expose
@TypeConverters(SidebarConverter.class)
private Sidebar sidebar;
@SerializedName("splash")
@Expose
@TypeConverters(SplashConverter.class)
private Splash splash;
@SerializedName("overview")
@Expose
@TypeConverters(OverviewConverter.class)
private Overview overview;
@SerializedName("home")
@Expose
@TypeConverters(HomeConverter.class)
private Home home;
@SerializedName("portfolio")
@Expose
@TypeConverters(PortfolioConverter.class)
private Portfolio portfolio;
@SerializedName("team")
@Expose
@TypeConverters(TeamConverter.class)
private Team team;
我想知道是否有更方便的方法在数据库中单手使用一个TypeConverter
.
I want to know if there's a more convenient way to use one TypeConverter
single handedly in Database.
推荐答案
您可以在单个类中定义所有转换器,如下所示:
You can define all your converter in a Single Class like this:
public class DateTypeConverter {
@TypeConverter
public static Date toDate(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long toLong(Date value) {
return value == null ? null : value.getTime();
}
}
然后在会议室数据库中使用类似这样的@TypeConverter
注释设置此转换器,该注释可在任何@Entity
类上全局运行.您无需在Entity类中单独定义@TypeConverter
And then set this converter on your Room Database with @TypeConverter
annotation like this which work globally on any @Entity
class.You don't need to define @TypeConverter
Individually in Entity class
@Database(entities = {Product.class}, version = 1)
@TypeConverters({DateTypeConverter.class})
public abstract class MyDatabase extends RoomDatabase {
public abstract ProductDao productDao();
}
请注意,我们在数据库定义中添加了一个名为@TypeConverters
的新注释,以引用我们可以拥有的不同转换器(您可以用逗号分隔并添加其他注释).
Note we’ve added a new annotation named @TypeConverters
in our database definition in order to reference the different converters that we can have (you can separate it by commas and add others).
这篇关于我可以将一个TypeConverter用于不同的对象类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!