Android GreenDAO3.0——entity建模

弓背霞明剑照霜,秋风走马出咸阳。这篇文章主要讲述Android GreenDAO3.0——entity建模相关的知识,希望能为你提供帮助。
引言
在项目中,为了使用GreenDAO的自动生成DAO class的功能,我们必须建立entity,该entity通过java注解标识。
                                                           

Android GreenDAO3.0——entity建模

文章图片

 
Schema是数据库对象集合,我们可以通过gradle插件配置GreenDAO,除此之外,我们至少需要配置Schema的版本:
// In the build.gradle file of your app project: android { ... }greendao { schemaVersion 2 }

我们不仅可以配置schemaVersion,还可以配置其他的属性:
daoPackage:DAOs、DAOMaster和DAOSession生成的目录,默认是entity所在的目录
【Android GreenDAO3.0——entity建模】targetGenDir:默认在build/generated/source/greendao
其他......(貌似不重要)
@Entity
在Android项目中,GreenDAO通过注解表征entity:
public class User { @Id private Long id; private String name; @Transient private int tempUsageCount; // not persisted // getters and setters for id and user ... }

我们通过@Entity对User进行注解,GreenDAO通过识别@Entity在编译期生成支持数据库的对象。                 
@Entity还支持一些属性,对该对象进行描述,此时我们对上述代码进行扩展:
@Entity( // If you have more than one schema, you can tell greenDAO // to which schema an entity belongs (pick any string as a name). schema = "myschema",// Flag to make an entity "active": Active entities have update, // delete, and refresh methods. active = true,// Specifies the name of the table in the database. // By default, the name is based on the entities class name. nameInDb = "AWESOME_USERS",// Define indexes spanning multiple columns here. indexes = { @Index(value = "https://www.songbingjia.com/android/name DESC", unique = true) },// Flag if the DAO should create the database table (default is true). // Set this to false, if you have multiple entities mapping to one table, // or the table creation is done outside of greenDAO. createInDb = false, // Whether an all properties constructor should be generated. // A no-args constructor is always required. generateConstructors = true, // Whether getters and setters for properties should be generated if missing. generateGettersSetters = true ) public class User { ... }

基本属性
@Entity public class User { @Id(autoincrement = true) private Long id; @Property(nameInDb = "USERNAME") private String name; @NotNull private int repos; @Transient private int tempUsageCount; ... }

  @Id:对于数据库来说,在数据表中作为主键,类型默认为long型,autoincrement =true使得id自增。
@Property  :将java class中的字段名映射为Property  提供的名字,在上述代码中就是将name映射为USERNAME,默认情况下,如果字段是驼峰命名转为下划线命名,如customName 转换为                                 CUSTOM_NAME。
@NotNull: 标记基本类型为非空。
@Transient    :表示java class中的该字段不会存储在数据库中,是一个缓存值。
索引
如果我们不喜欢,GreenDAO定制的默认索引,我们可以自行设置新的索引,这是需要属性@index。
@Entity public class User { @Id private Long id; @Index(unique = true) private String name; }

id是数据库的唯一索引,即主键。但我们可以通过unique = true,指定name索引也是唯一的。
 
 

    推荐阅读