After adding the GreenDao library dependency and Gradle plugin, we need to first create an entity object.
Entity
An entity is a Plain Old Java Object (POJO) that models some data in the database. GreenDao will use this class to create a table in the SQLite database and automatically generate helper classes we can use to access and store data without having to write SQL statements.
@Entity
public class Users {
@Id(autoincrement = true)
private Long id;
private String firstname;
private String lastname;
@Unique
private String email;
// Getters and setters for the fields...
}
One-time GreenDao setup
Each time an application is launched GreenDao needs to be initialized. GreenDao suggests keeping this code in an Application class or somewhere it will only be run once.
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "mydatabase", null);
db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();
GreenDao Helper Classes
After the entity object is created, GreenDao automatically creates the helper classes used to interact with the database. These are named similarly to the name of the entity object that was created, followed by Dao
and are retrieved from the daoSession
object.
UsersDao usersDao = daoSession.getUsersDao();
Many typical database actions can now be performed using this Dao object with the entity object.
Query
String email = "[email protected]";
String firstname = "John";
// Single user query WHERE email matches "[email protected]"
Users user = userDao.queryBuilder()
.where(UsersDao.Properties.Email.eq(email)).build().unique();
// Multiple user query WHERE firstname = "John"
List<Users> user = userDao.queryBuilder()
.where(UsersDao.Properties.Firstname.eq(firstname)).build().list();
Insert
Users newUser = new User("John","Doe","[email protected]");
usersDao.insert(newUser);
Update
// Modify a previously retrieved user object and update
user.setLastname("Dole");
usersDao.update(user);
Delete
// Delete a previously retrieved user object
usersDao.delete(user);