Green Dao 3.0 Basic Configuration and Multi-table Joint Survey

Keywords: Database Android Attribute Java

Advantages of Green Dao

  1. High performance, the fastest relational database known as Android
  2. Support database encryption greendao support SQLCipher database encryption
  3. Library files are smaller than 100K
  4. Small memory footprint

Changes in GreenDao 3.0

Before 3.0, Java data objects (entities) and DAO objects need to be generated through the new Green Dao Generator project, which is very tedious and increases the cost of use.

The biggest change in GreenDao 3.0 is to use annotations to generate Java data objects and DAO objects through compilation.

How to use GreenDao 3.0

Add the following configuration to the module gradle:

apply plugin: 'org.greenrobot.greendao'
greendao{
        //schemaVersion represents the version number of the database. We can modify the version number here every time the database is upgraded.
        schemaVersion 1
        //targetGenDir represents the location of DAOMaster and DaoSession generated by green DAO
        targetGenDir 'src/main/java'
    }


dependencies {
    compile 'org.greenrobot:greendao:3.1.0'
}

The Meaning of Content Configuration in greendao

  • schemaVersion: The database schema version, which can also be understood as the database version number
  • daoPackage: Set DaoMaster, DaoSession, Dao package name
  • targetGenDir: Set up DaoMaster, DaoSession, Dao directories
  • targetGenDirTest: Set up the generated unit test directory
  • GeneeTests: Setting up automatic generation of unit test cases

Add the following configuration to build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'
    }
}

New Entity Class

@Entity
public class Teacher {
    @Id
    private Long id;
    @Property(nameInDb = "NAME")
    private String username;
    @Property(nameInDb = "NICKNAME")
    private String nickname;

// Here's the auto-generated
    public String getNickname() {
        return this.nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    public String getUsername() {
        return this.username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    @Generated(hash = 407720401)
    public Teacher(Long id, String username, String nickname) {
        this.id = id;
        this.username = username;
        this.nickname = nickname;
    }
    @Generated(hash = 1630413260)
    public Teacher() {
    }
}

Meaning of annotations in entity classes

Entity @Entity annotation
- schema: Tell GreenDao which schema the current entity belongs to
- Active: Marks an entity as active, with new updates, deletions, and refreshes for the active entity
- nameInDb: Alias used in data, default class names of entities
- Index: Defines an index that can span multiple columns
- createInDb: Tags create database tables

Basic Attribute Annotation

  • @ Id: Primary key Long type, self-growth can be set by @Id(autoincrement = true)
  • @ Property: Set the column name corresponding to a non-default relational mapping. The default is to use the field name as an example: @Property (nameInDb="name").
  • @ NotNul: Set that the current column of the database table cannot be empty
  • @ Transient: Columns that do not generate database tables after adding secondary Tags

Index annotations

  • @ Index: Create an index using @Index as an attribute, set the index alias by name, or add constraints to the index by unique
  • @ Unique: Add a unique constraint to the database column

Annotation of Relations

  • @ ToOne: Define the relationship with another entity (an entity object)
  • @ ToMany: Define relationships with multiple entity objects
/**
     * Initialize Database Helper in application CAITON
     */
    private DaoMaster.DevOpenHelper getOpenHelper(@NonNull Context context, @Nullable String dataBaseName,String userId) {
        closeDbConnections();
        return new DaoMaster.DevOpenHelper(new GreenDaoContext(context,userId), dataBaseName, null);
    }

GreenDaoContext can specify the location where the database is generated

public class GreenDaoContext extends ContextWrapper {

    private String currentUserId = "default";
    private Context mContext;

    /**
     * Different databases can be created according to user names to prevent invocation errors
     * @param context System context
     * @param userId User's logo
     */
    public GreenDaoContext(Context context,String userId) {
        super(context);
        this.mContext = context;
        if(!TextUtils.isEmpty(userId)){
            this.currentUserId=userId;
        }
    }

    /**
     * Get the database path, if it does not exist, create the object
     *
     * @param dbName
     */
    @Override
    public File getDatabasePath(String dbName) {
        String path = SdCardUtils.getDatabaseDir(mContext);
        StringBuffer buffer = new StringBuffer();
        buffer.append(path);
        buffer.append(File.separator);
        buffer.append(currentUserId);
        buffer.append(File.separator);
        buffer.append(dbName);
        File file=new File(buffer.toString());
        if(!file.getParentFile().exists()){
            FileUtils.makeFolders(file.getParentFile().getAbsolutePath());
        }
        return new File(buffer.toString());
    }

    /**
     * The overload method is used to open the database on the SD card. android 2.3 and below will call this method.
     *
     * @param name
     * @param mode
     * @param factory
     */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode,
                                               SQLiteDatabase.CursorFactory factory) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
        return result;
    }

    /**
     * Android 4.0 This method is called to get the database.
     *
     * @param name
     * @param mode
     * @param factory
     * @param errorHandler
     * @see android.content.ContextWrapper#openOrCreateDatabase(java.lang.String, int,
     * android.database.sqlite.SQLiteDatabase.CursorFactory,
     * android.database.DatabaseErrorHandler)
     */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory,
                                               DatabaseErrorHandler errorHandler) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);

        return result;
    }

}
/**
     * Get Writable Database Objects
     */
    private SQLiteDatabase getWritableDatabase() {
        return mHelper.getWritableDatabase();
    }

    /**
     * Get Readable Database Objects
     */
    private SQLiteDatabase getReadableDatabase() {
        return mHelper.getReadableDatabase();
    }
 public DaoSession openWritableDb() throws SQLiteException {
        if (daoWriteSession == null) {
            daoWriteSession = new DaoMaster(getWritableDatabase()).newSession();
        }
        return daoWriteSession;
    }

After that, we can do all kinds of additions, deletions and alterations.

. . .

Multi-table Joint Survey

One-to-one relationship

Student
 @Id(autoincrement = true)
    private Long id;
    private String name;

    private Long tid;//This is the associated foreign key.
    @ToOne(joinProperty = "tid") //This is the comment binding tid, which is the TID of the line above.
    private Teacher teacher;
Teacher
    @Id
    private Long id;
    private String name;
Teacher t=new Teacher();
t.setId(110L);
t.setName("teacher");
Student s=new Student();
s.setId(null);
s.setTid(110L);
s.setName("name");
s.setTeacher(t);

One-to-many: For example, a teacher has more than one student

#In the teacher class
 @ToMany(referencedJoinProperty = "tid")//Specify the id of the other classes associated with it
 private List<Student> studnets;
#In the student class
  @Id
  private Long id;
  private Long tid;//This is the foreign key, which is teacher's id.

Many to many, one teacher has many students and one student has more than one teacher. At this time, we need to generate a middle table to establish the relationship between the two.

//Third table
@Entity
public class StudentToTeacher {
   @Id(autoincrement = true)
    private Long id;
    //id associated with person
    private Long tid;
    //id associated with student
    private Long sid;
}
@Entity
public class Student {
    @Id
    private Long id;
    private String name;
    // To many, @JoinEntity annotation: entity intermediate table; sourceProperty entity attribute; targetProperty outer chain entity attribute
    @ToMany
    @JoinEntity(
            entity = StudentToTeacher.class,
            sourceProperty = "sid",
            targetProperty = "tid"
    )
    private List<Teacher> teacher;
}
@Entity
Teacher{
    @Id(autoincrement = true)
    private Long id;
    private String name;
   // To many, @JoinEntity annotation: entity intermediate table; sourceProperty entity attribute; targetProperty outer chain entity attribute
    @ToMany
    @JoinEntity(
            entity = StudentToTeacher.class,
            sourceProperty = "tid",
            targetProperty = "sid"
    )
    private List<Student> students;
    }

Intermediate tables actually establish a link between the two and express their dependencies, so that the operation of multiple tables has not been a problem for a long time.

Posted by akdrmeb on Tue, 09 Jul 2019 12:34:44 -0700