New Features of GreenDao3.0 (configuration, annotation, encryption) and new features of greendao3.0

Source: Internet
Author: User

New Features of GreenDao3.0 (configuration, annotation, encryption) and new features of greendao3.0

Greendao3.0release was released in July 6, with three major changes: 1. Package Name Change 2. entity annotation 3. encryption support Optimization

In this article, we will see some code examples, and I have extracted the official documents and demo examples, because their examples have been well written.

1. GreenDao3 Configuration

3.0 is more convenient than 2.0. You do not need to create a Module or a series of other operations. You can directly configure and create an object in build. gradle and generate it by adding annotations.

Step 1/2

Add these configurations under build. gradle (the three in the v7 package are greendao)

buildscript {    repositories {        mavenCentral()    }    dependencies {        classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'    }} apply plugin: 'org.greenrobot.greendao' dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.4.0'    compile 'org.greenrobot:greendao:3.0.1'    compile 'org.greenrobot:greendao-generator:3.0.0'    compile 'net.zetetic:android-database-sqlcipher:3.5.2'} greendao {    targetGenDir 'src/main/java'    daoPackage 'com.XXXX.dao.db'}
Step 2/2

Version 2.2 uses methods such as addEntity and addProperty in maingen. In version 3.0, you only need to manually create an object class and add annotations (as described below)

Build the project and automatically generate files such as DaoMaster, Daosession, and UserDao. Then, you can use them normally in the code.

 

Ii. entity Annotation

Most annotations can find the syntax corresponding to 2.0.

2.1 common annotations
@Entitypublic class User {    @Id(autoincrement = true)    private Long id;     @Property(nameInDb = "USERNAME")    private String name;     @NotNull    private int repos;     @Transient    private int tempUsageCount;     ...}

Where

@ Entity identifies a bean that requires Greendao to generate code for us.

@ Id indicates the primary key. You can specify whether auto-increment is equivalent to Version 2.2 in brackets.

Entity entity = schema.addEntity("User");entity.addLongProperty("id").primaryKey().autoincrement();

@ Property is used to set the name of the attribute column in the database (by default, if not written, it is consistent)

@ NotNull is not empty

@ Transient: this field is customized and will not be created in the database table. It is equivalent to Version 2.2.

Schema. enableKeepSectionsByDefault (); the following code is generated: // keep includes-put your custom includes here // keep includes end // keep fields-put your custom fields here // keep fields end // keep methods-put your custom methods here // KEEP METHODS END

The attributes you want to customize and the getset method need to be written in the annotation. Now this annotation can replace the function.

 

2.2 entity Annotation
@Entity(        schema = "myschema",        active = true,                nameInDb = "AWESOME_USERS",                indexes = {                @Index(value = "name DESC", unique = true)        },                createInDb = false)public class User {  ...}

Where

Schema indicates the schema to which the dao belongs when there are multiple schemas in a project.

Active indicates whether updates, refresh, and delete operations between entity classes are supported.

schema.enableActiveEntitiesByDefault();

NameInDb is used to write a table name that exists in the Database. (If this parameter is left blank, the name is consistent by default)

Indexes defines the index, which can span multiple columns

CreateInDb if multiple objects are associated with this table, you can set false in the excess objects to avoid repeated creation (true by default)

 

2.3 index annotation
@Entitypublic class User {    @Id private Long id;    @Index(unique = true)    private String name;}@Entitypublic class User {    @Id private Long id;    @Unique private String name;}

Where

@ Index create an Index using this field

@ Unique: Add a unique constraint. In the brackets above, Unique = true has the same effect.

 

2.4 link Annotation
@Entitypublic class Order {    @Id private Long id;     private long customerId;     @ToOne(joinProperty = "customerId")    private Customer customer;} @Entitypublic class Customer {    @Id private Long id;}

@ ToOne Associates one of its attributes with another table, which is equivalent to Version 2.2

Property property = entity.addLongProperty("customerId").getProperty(); 
entity.addToOne(Customer, property);

@ ToMany there are many application scenarios. The following code is collapsed by default.

@Entitypublic class User {    @Id private Long id;     @ToMany(referencedJoinProperty = "ownerId")    private List<Site> ownedSites;} @Entitypublic class Site {    @Id private Long id;    private long ownerId;}// ----------------------------@Entitypublic class User {    @Id private Long id;    @Unique private String authorTag;     @ToMany(joinProperties = {            @JoinProperty(name = "authorTag", referencedName = "ownerTag")    })    private List<Site> ownedSites;} @Entitypublic class Site {    @Id private Long id;    @NotNull private String ownerTag;}// ----------------------------@Entitypublic class Site {    @Id private Long id;     @ToMany    @JoinEntity(            entity = JoinSiteToUser.class,            sourceProperty = "siteId",            targetProperty = "userId"    )    private List<User> authors;} @Entitypublic class JoinSiteToUser {    @Id private Long id;    private Long siteId;    private Long userId;} @Entitypublic class User {    @Id private Long id;}

The attribute referencedJoinProperty of @ to is similar to the foreign key constraint.

@ JoinProperty for more complex relationships, you can use this annotation to indicate the source attribute of the Target attribute.

@ JoinEntity if you are dealing with many-to-many relationships with other tables or entities involved, you can add this additional annotation to the target attribute (it is not commonly used)

 

2.5 derivative Annotation

@ Generated: This is automatically Generated by greendao after the build. This annotation is interpreted as preventing duplication. After each piece of code is Generated, a hash is added as a mark. It is not officially recommended that you touch the code. changes will cause the code to be inconsistent with the hash value.

 

Iii. Database Encryption

In the iterative process of Greendao, we can see such a library

compile 'org.greenrobot:greendao-generator-encryption:3.0.0beta3'

Greendao3 works with the following encryption database. encryption: 3.0.0beta-3 is equivalent to an adaptation layer. Later, it is incorporated into the 3.0.1 version of The greendao master database in iteration to unify database-related APIs.

compile 'net.zetetic:android-database-sqlcipher:3.5.2'

The previous versions also support encryption, but it can be understood that there are various types of conversions when data is transmitted through each api. 3.0 unifies the data and makes it smoother to use.

You can use the Code directly.

User man1 = new User (); man1.setId (10001); man1.setName ("kobe"); DaoMaster. devOpenHelper a = new DaoMaster. devOpenHelper (this, "database_name", null); try {daoSession = new DaoMaster (. getEncryptedWritableDb (MY_PWD )). newSession (); daoSession. getUserDao (). insert (man1);} catch (Exception e) {Log. d ("e", String. valueOf (e);} // after several code logics... DaoSession normalSession = new DaoMaster (. getWritableDb ()). newSession (); Log. d ("unable to retrieve data", normalSession. getUserDao (). loadAll (). toString (); DaoSession encryptedSession = new DaoMaster (. getEncryptedWritableDb (MY_PWD )). newSession (); // Dong baoran blog Park Log. d ("data can be retrieved", encryptedSession. getUserDao (). loadAll (). toString ());

As shown in the code above, compared to the previous method getWriteableDb, the encryption method uses getEncryptedWritableDb. Enter the key when getting the DB and getSession. Other steps are similar to before.

The session used for data retrieval must also be new with the same key; otherwise, only empty data can be seen.

07-27/com. XXX. dsx. testgreendao3 D/cannot retrieve data: [] 07-27/com. XXX. dsx. testgreendao3 D/data can be retrieved: [com. XXX. dsx. testgreendao3.User @ 2ae5190]

The above MY_PWD is a static variable. We recommend that you use the unique identifier of the device as a field similar to UUID for encryption, so that the keys of each machine are different and will not change.

If the local files of the encrypted database are extracted, the contents cannot be found. You can only view the table structure and column name by using dump.

  

If you are not satisfied, you can encrypt the column name. When creating a table, it is difficult to encrypt the column name. We recommend that you encrypt some key tables, such as USER and ACCOUNT.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.