Android数据库操作--greenDAO的入门使用

目前android经常用的orm框架主要有greenDAO、OrmLite、AndrORM。其中greenDAO的运行效率最高,内存消耗最少,性能最佳。
Android数据库操作--greenDAO的入门使用_第1张图片

greenDAO是一个可以快速将Java对象映射到SQLite数据库的表单中的ORM解决方案。设计的主要目标:一个精简的库;性能最大化;内存开销最小化;易于使用的APIs;对Android进行高度优化。
GreenDAO3.0之前需要通过新建GreenDaoGenerator工程生成java数据对象(实体)和DAO对象,非常的繁琐而且也加大了使用成本。GreenDAO3.0最大的变化就是采用注解的方式通过编译生成java数据对象和DAO对象。
下面是使用步骤:

第一步,在build.gradle添加设置

buildscript { repositories { mavenCentral() } dependencies { classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0' } } apply plugin: 'org.greenrobot.greendao' greendao { schemaVersion 1000 targetGenDir 'src/main/java' daoPackage 'com.chinaso.greendaodemo' } dependencies { compile 'org.greenrobot:greendao:3.2.0 ' } 

第二步,新建实体类,例如user:

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    private int age;

   //下面省去了 setter/getter
}

此时编译自动生成DAOMaster\DaoSession\Dao,默认位置build->generated->source->greenDao.如果第一步设置了greendao{}则在定义的包下生成。

第三步,第三步:通过上面使用的方式获取DAOMaster、DAOSession、DAO类,然后数据库管理者类

package com.chinaso.dagger_demo.db;

import android.content.Context;

import com.chinaso.dagger_demo.App;
import com.chinaso.greendaodemo.DaoMaster;
import com.chinaso.greendaodemo.DaoSession;
import com.chinaso.greendaodemo.UserDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

public class DBManager {
    private static DBManager mInstance;
    private static DaoMaster.DevOpenHelper openHelper;
    private static Context mContext;
    private UserDao userDao;
    private DBManager() {
    }

    public static DBManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized ((DBManager.class)) {
                mContext = context;
                mInstance = new DBManager();
                DaoSession daoSession = App.getDaoSession(mContext);
                mInstance.userDao = daoSession.getUserDao();
            }
        }
        return mInstance;
    }

    public void insertUser(User user) {
        userDao.insert(user);
    }

    public void insertUserList(List users) {
        if (users == null || users.isEmpty()) {
            return;
        }
        userDao.insertInTx(users);
    }

    public void deleteUser(User user) {
        userDao.delete(user);
    }

    public void deleteAll() {
        userDao.deleteAll();
    }

    public void updateUser(User user) {
        userDao.update(user);
    }

    public List queryUserList() {
        QueryBuilder qb = userDao.queryBuilder();
        List list = qb.list();
        return list;
    }

    public List queryUserList(int age) {
        QueryBuilder qb = userDao.queryBuilder();
        qb.where(UserDao.Properties.Age.gt(age)).orderAsc(UserDao.Properties.Age);
        List list = qb.list();
        return list;
    }

}

其中App:

public class App extends Application {
    public final static String dbName = "test_db";
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;

    public static DaoMaster getDaoMaster(Context context)
    {
        if (daoMaster == null)
        {
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context, dbName, null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    public static DaoSession getDaoSession(Context context)
    {
        if (daoSession == null)
        {
            if (daoMaster == null)
            {
                daoMaster = getDaoMaster(context);
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }
}

第四步,使用

 userList = dbManager.queryUserList();
        int len = userList.size();
        User user = new User();
        user.setId(new Long((long) len));
        user.setAge(len * 3);
        user.setName("第" + len + "人");
        dbManager.insertUser(user);
        userList = dbManager.queryUserList();
        int leng = userList.size();
        for (int i = 0; i
    
      userList = dbManager.queryUserList(); for (User user : userList) { Log.e("db", "insertDB:name=" + user.getName() + "; age=" + user.getAge()); result.append("insertDB:name="+user.getName()+"; age="+user.getAge() + "\n"); } dbResultTV.setText(result.toString()); } @OnClick(R.id.deleteBtn) public void deleteBtn() { result.delete(0,result.length()); DBManager dbManager = DBManager.getInstance(FullscreenActivity.this); List
     
       userList = dbManager.queryUserList(); for (User user : userList) { Log.e("db", "insertDB:name=" + user.getName() + "; age=" + user.getAge()); if (user.getId() == 0) { dbManager.deleteUser(user); } } userList = dbManager.queryUserList(); for (User user : userList) { Log.e("db", "insertDB:name=" + user.getName() + "; age=" + user.getAge()); result.append("insertDB:name="+user.getName()+"; age="+user.getAge() + "\n"); } dbResultTV.setText(result.toString()); } @OnClick(R.id.updateBtn) public void updateBtn() { result.delete(0,result.length()); DBManager dbManager = DBManager.getInstance(FullscreenActivity.this); List
      
        userList = dbManager.queryUserList(); for (User user:userList) { if (user.getId() == 3) { user.setAge(10); user.setName("张三"); dbManager.updateUser(user); } } userList = dbManager.queryUserList(); for (User user : userList) { Log.e("db", "insertDB:name=" + user.getName() + "; age=" + user.getAge()); result.append("insertDB:name="+user.getName()+"; age="+user.getAge() + "\n"); } dbResultTV.setText(result.toString()); } } " data-snippet-id="ext.4d23e3032f50bf4d49c22159ef1437ef" data-snippet-saved="false" data-codota-status="done">
       package com.chinaso.dagger_demo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Button; import android.widget.TextView; import com.chinaso.dagger_demo.db.DBManager; import com.chinaso.dagger_demo.db.User; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class FullscreenActivity extends AppCompatActivity { @BindView(R.id.insertBtn) Button insertBtn; @BindView(R.id.queryListBtn) Button queryListBtn; @BindView(R.id.deleteBtn) Button deleteBtn; @BindView(R.id.updateBtn) Button updateBtn; @BindView(R.id.dbResultTV) TextView dbResultTV; StringBuilder result = new StringBuilder(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen); ButterKnife.bind(this); initDB(); } private void initDB() { result.delete(0,result.length()); DBManager dbManager = DBManager.getInstance(FullscreenActivity.this); dbManager.deleteAll(); for (int i = 0; i < 5; i++){ User user = new User(); user.setId(new Long((long) i)); user.setAge(i * 10); user.setName("第" + i + "人"); dbManager.insertUser(user); result.append("insertDB:name="+user.getName()+"; age="+user.getAge() + "\n"); } dbResultTV.setText(result.toString()); } @OnClick(R.id.insertBtn) public void insertDB() { result.setLength(0); DBManager dbManager = DBManager.getInstance(FullscreenActivity.this); List userList = dbManager.queryUserList(); int len = userList.size(); User user = new User(); user.setId(new Long((long) len)); user.setAge(len * 3); user.setName("第" + len + "人"); dbManager.insertUser(user); userList = dbManager.queryUserList(); int leng = userList.size(); for (int i = 0; i User u = userList.get(i); Log.e("db", "insertDB:name="+u.getName()+"; age="+u.getAge()); result.append("insertDB:name="+u.getName()+"; age="+u.getAge() + "\n"); } dbResultTV.setText(result.toString()); } @OnClick(R.id.queryListBtn) public void queryListDB() { result.delete(0,result.length()); DBManager dbManager = DBManager.getInstance(FullscreenActivity.this); List userList = dbManager.queryUserList(); for (User user : userList) { Log.e("db", "insertDB:name=" + user.getName() + "; age=" + user.getAge()); result.append("insertDB:name="+user.getName()+"; age="+user.getAge() + "\n"); } dbResultTV.setText(result.toString()); } @OnClick(R.id.deleteBtn) public void deleteBtn() { result.delete(0,result.length()); DBManager dbManager = DBManager.getInstance(FullscreenActivity.this); List userList = dbManager.queryUserList(); for (User user : userList) { Log.e("db", "insertDB:name=" + user.getName() + "; age=" + user.getAge()); if (user.getId() == 0) { dbManager.deleteUser(user); } } userList = dbManager.queryUserList(); for (User user : userList) { Log.e("db", "insertDB:name=" + user.getName() + "; age=" + user.getAge()); result.append("insertDB:name="+user.getName()+"; age="+user.getAge() + "\n"); } dbResultTV.setText(result.toString()); } @OnClick(R.id.updateBtn) public void updateBtn() { result.delete(0,result.length()); DBManager dbManager = DBManager.getInstance(FullscreenActivity.this); List userList = dbManager.queryUserList(); for (User user:userList) { if (user.getId() == 3) { user.setAge(10); user.setName("张三"); dbManager.updateUser(user); } } userList = dbManager.queryUserList(); for (User user : userList) { Log.e("db", "insertDB:name=" + user.getName() + "; age=" + user.getAge()); result.append("insertDB:name="+user.getName()+"; age="+user.getAge() + "\n"); } dbResultTV.setText(result.toString()); } } 
      
     
    

参考:

1、官方地址:http://greenrobot.org/greendao/
2、官方demo:https://github.com/greenrobot/greenDAO 和
http://greenrobot.org/greendao/documentation/introduction/
3、Android数据存储之GreenDao 3.0 详解:http://www.cnblogs.com/whoislcj/p/5651396.html

你可能感兴趣的:(Android开发)