轻松玩转社区
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
Android GreenDAO3.0——entity建模
引言在项目中,为了使用GreenDAO的自动生成DAO class的功能,我们必须建立entity,该entity通过java注解标识。

Schema是数据库对象集合,我们可以通过gradle插件配置GreenDAO,除此之外,我们至少需要配置Schema的版本:
[Java] 纯文本查看 复制代码 // In the build.gradle file of your app project:
android {
...
}
greendao {
schemaVersion 2
}
我们不仅可以配置schemaVersion,还可以配置其他的属性:
daoPackage:DAOs、DAOMaster和DAOSession生成的目录,默认是entity所在的目录
targetGenDir:默认在build/generated/source/greendao
其他......(貌似不重要)
@Entity在Android项目中,GreenDAO通过注解表征entity:
[Java] 纯文本查看 复制代码 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还支持一些属性,对该对象进行描述,此时我们对上述代码进行扩展:
[Java] 纯文本查看 复制代码 @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 = "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[Java] 纯文本查看 复制代码
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。
[Java] 纯文本查看 复制代码 @Entity
public class User {
@Id private Long id;
@Index(unique = true)
private String name;
}
id是数据库的唯一索引,即主键。但我们可以通过unique = true,指定name索引也是唯一的。
|