GreenDao is a lightweight database framework, which is faster and more efficient than Xutils etc.
Here is how to use GreenDao
①Establish
compile 'org.greenrobot:greendao:3.2.0'
The integration based on Android Studio is very simple, you need to rely on this GreenDao library in Build Gradle now
In addition, you also need to use the plugin form declaration in Build Gradle
// use greendao apply plugin: 'org.greenrobot.greendao'
The package, targetGenDir and version of dao should also be configured in build.gradle. This configuration should be declared in android{ }
//greendao configuration greendao { //version number, configurable when upgrading schema version 1 daoPackage 'arcturis.greendao' targetGenDir 'src/main/java' }
In addition, the use of the database requires the read and write permissions of the SD card, so don't forget to add permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
②Code automatic generation mechanism
GreenDao's data base class generation method is different from that of xutils. In Xutils, you need to manually write the bean class, and then use some of his get Set methods. Although Green also needs you to write, his more highlight is to automatically generate these related methods, including his database declarations and control files
For example, we need a list file for list shopping. We need to save this product in the database
Similar to this is the starting bean base class
@Entity public class Shop { //represented as a shopping cart list public static final int TYPE_CART = 0x01; //represented as a favorite list public static final int TYPE_LOVE = 0x02; // can't use int @Id(autoincrement = true) private Long id; //Commodity name Unique The attribute value must be unique in the database @Unique private String name; //Commodity price Property can customize the field name, note that foreign keys cannot use this property @Property(nameInDb = "price") private String price; // quantity sold private int sell_num; //icon url private String image_url; //business address private String address; //Item list type private int type; }
Here is a basic bean base class, we need annotations, so that GreenDao will know that this is our bean base class, and there will be a part of automatically generating code later, and then we will look at the meaning of each annotation
@Entity This is a Bean base class Entity
@Id(autoincrement = true) ID can be set whether to auto-increase or not. After enabling auto-increment, it doesn't matter if you pass in null for initialization, the type is Long
@Unique This identifier identifies this field as unique in the database
@Property: Set a column name corresponding to a non-default relational mapping, the default is to use the field name, for example: @Property(nameInDb = "name")
and then click the compile button, Then if all the settings are accurately set successfully, GreenDao will help us generate the following files
It's the three files marked in red.
DaoMaster
DaoSession
ShopDao (this name is defined according to the bean class name we defined)
Then we can initialize the application in the application
private void steupDataBase(){ DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"shop.db",null); //Get writable DataBase SQLiteDatabase db = helper.getWritableDatabase(); //get database object DaoMaster daoMaster = new DaoMaster(db); //Get the Dao object manager daoSession = daoMaster.newSession(); }
DaoMaster:
Use greenDAO's entry point. DaoMaster is responsible for managing database objects (SQLiteDatabase) and DAO classes (objects). We can create SQLite databases with different schemas through its internal classes OpenHelper and DevOpenHelper SQLiteOpenHelper.
DaoSession :
To manage all DAO objects in the specified mode, DaoSession provides some common persistence methods such as insert, load, update, update and delete entities.
XxxDAO :
Each entity class greenDAO will generate a corresponding DAO object, such as: User entity, will generate a UserDao class
In this way, we will complete the establishment of GreenDao
You also need to get an instance of daoSession
private static DaoSession daoSession; public static DaoSession getDaoinstan(){ return daoSession; }
By using the static method to obtain the instance of DaoSession, the database can be added, deleted, modified and searched.
③How to generate GreenDao in a specific CD card location
Sometimes we need to claim GreenDao at a specific location, what do we do at this time, GreenDao also provides us with the opportunity to customize, just write it according to the following classes
This class inherits from contextWrapper and needs to override the getDatabasePath method
public class GreenDaoContext extends ContextWrapper { private Context mContext; public GreenDaoContext(){ super(MyApplication.getContext()); this.mContext = MyApplication.getContext(); } @Override public File getDatabasePath(String dbName) { String dbBasePath = AppPathUtils.getDbCacheBaseDir(mContext); File dbDir = new File(dbBasePath); if(!dbDir.exists()){ dbDir.mkdirs (); } StringBuffer buffer = new StringBuffer(); buffer.append(dbBasePath); buffer.append(File.separator); buffer.append(dbName); String dbPath = buffer.toString(); File dbFile = new File(dbPath); if(!dbFile.exists()){ try { dbFile.createNewFile(); // Create file } catch (IOException e) { e.printStackTrace (); } return dbFile; }else{ return super.getDatabasePath(dbName); } } /*** * Override this method, which is used to open the database on the SD card. This method will be called by android 2.3 and below. * @param name * @param mode * @param factory * @return */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) { SQLiteDatabase result =SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory); return result; } /** * Android 4.0 calls this method to get the database * @param name * @param mode * @param factory * @param errorHandler * @return */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory); return result; }
Then you can change the incoming value in one place when initializing in the application.
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(new GreenDaoContext(),"shop.db",null); // Get the writable DataBase SQLiteDatabase db = helper.getWritableDatabase(); // Get the database object DaoMaster daoMaster = new DaoMaster(db); // Get the Dao object manager daoSession = daoMaster.newSession();