ONE Goal , ONE Passion !
To use greenDAO in a project you create an entity model representing the persistent data in your application. Then, based on this model greenDAO generates Java code for the DAO classes.
在你的项目中使用greenDao去创建一个实体模型代表持久化数据.基于这个模型greenDao能够为DAO类产生java代码.
greenDAO 3 uses annotations to define schemas and entities. Here is a quick example:
greenDAO 3使用注解去定义一个实体.下面是一个快速入门
@Entity
public class User {
@Id
private Long id;
private String name;
@Transient
private int tempUsageCount; // not persisted
// getters and setters for id and user ...
}
The @Entity annotation turns the Java class User into a database-backed entity. This will also instruct greenDAO to generate the necessary code (for example DAOs).
Note: only Java classes are supported. If you prefer another language like Kotlin, your entity classes must still be Java.
注意:greenDao只支持java代码.
@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类型作为实体类id. 在数据库关系中,它是主键,autoincrement参数代表是一个自增主键.
使用这个属性去映射一个列名,如果缺少的话.greenDao会自动帮生成列名.生成的列名不是我们小驼峰命名规则.而是大写字母加下划线.例如:
customName 将会被命名为 CUSTOM_NAME.
注意:通常建议使用一个常量来定义列名.即:
MyContant.name = "USERNAME"; // 将列名定义为常量
@Property(nameInDb = MyContant.name)
标示数据库中某一列不为空,通常他去标记基本数据类型(long, int, short, byte)不为空,而不是可为空的包装数据类型(Long, Integer, Short, Byte).
标记这个属性不映射到数据库中.或者,能够用为java的关键字.
Currently, entities must have a long or Long property as their primary key. This is recommended practice for Android and SQLite.
To work around this, define your key property as an additional property, but create a unique index for it:
@Id
private Long id;
@Index(unique = true)
private String key;
Use @Index at a property to create a database index for the corresponding database column. Use the following parameters to customize:
name: If you do not like the default name greenDAO generates for the index, you can specify yours here.
unique: Adds a UNIQUE constraint to the index, forcing all values to be unique.
@Entity
public class User {
@Id private Long id;
@Index(unique = true)
private String name;
}
@Unique adds a UNIQUE constraint to the database column. Note, that SQLite also implicitly creates an index for it.
@Entity
public class User {
@Id private Long id;
@Unique private String name;
}
greenDAO tries to work with reasonable defaults, so developers don’t have to configure each and every bit.
greenDao会以一些合理的默认配置工作,因此开发者不必完全配置每一个地方.
For example, a property called creationDate will become a database column CREATION_DATE.
例如: 一个叫creationDate的属性变成数据库的列时,列名会变成CREATION_DATE.
Build—-> Make project.
注意: 生成相关代码后,不要更改任何代码.否则运行会报错:
Error:Execution failed for task ':app:greendao'.
> Constructor (see ExampleEntity:21) has been changed after generation.
Please either mark it with @Keep annotation instead of @Generated to keep it untouched,
or use @Generated (without hash) to allow to replace it.