GreenDao集成与使用

GreenDao是一款开源的轻便快捷的数据库框架,无需编写复杂的SQL语句,在性能方面,GreenDao针对 Android 进行了高度优化, 最小的内存开销 、依赖体积小 同时还是支持数据库加密。

一、GreenDao集成
首先在项目的build.gradle中添加:

dependencies {     
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }

然后在module的build.gradle中添加:

apply plugin: 'org.greenrobot.greendao'
...
greendao {
        schemaVersion 1
        daoPackage 'com.huzhuwei.greendao.gen'//这个是生成代码保存的包名
        targetGenDir 'src/main/java'//保存到java代码路径
    }
dependencies {
    compile 'org.greenrobot:greendao:3.2.0'
    compile 'org.greenrobot:greendao-generator:3.2.0'
}

二、GreenDao的使用
创建实体类

@Entity
public class User {

    @Id(autoincrement = true)
    private Long id;

    private String text;
    private String comment;
    private Date date;
}

然后Make Project(Ctrl + F9),就可以自动生成如下代码:
在这里插入图片描述
在Application中添加如下代码:

public class MyApp extends Application {

    public static final boolean ENCRYPTED = true;

    private DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
       ...
        DaoMaster.DevOpenHelper helper = new  DaoMaster.DevOpenHelper(this, ENCRYPTED ? "users-db-encrypted" : "users-db");
        Database db =  helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
        ...
    }
    ...
    public DaoSession getDaoSession() {
        return daoSession;
    }
}

使用GreenDao进行增删改查操作

/**
 * greenDao的官方地址http://greenrobot.org/greendao/
 * github地址https://github.com/greenrobot/greenDAO
 */

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private UserDao userDao;
    private AutoCompleteTextView text;
    private AutoCompleteTextView comment;
    private Button butAddData;
    private Button butShowData;
    private Button butDelData;
    private Button butModifyData;
    private TextView tShow;
    private EditText num;
    private Query<User> userQuery;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        userDao = daoSession.getUserDao();
        initView();
    }

    private void initView() {
        text = (AutoCompleteTextView) findViewById(R.id.edit_text);
        comment = (AutoCompleteTextView) findViewById(R.id.edit_comment);
        tShow = (TextView) findViewById(R.id.text_show_data);
        num = (EditText) findViewById(R.id.exit_id);
        butAddData = (Button) findViewById(R.id.but_add_data);
        butShowData  = (Button) findViewById(R.id.but_show_data);
        butDelData = (Button) findViewById(R.id.but_del_data);
        butModifyData = (Button) findViewById(R.id.but_modify_data);

        butAddData.setOnClickListener(this);
        butShowData.setOnClickListener(this);
        butDelData.setOnClickListener(this);
        butModifyData.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
                //增
            case R.id.but_add_data:
                String test = text.getText().toString();
                String con = comment.getText().toString();
                User user = new User();
                user.setComment(con);
                user.setDate(new Date());
                user.setText(test);
                userDao.insert(user);
                text.setText("");
                comment.setText("");
                break;
                
                //查
            case R.id.but_show_data:
                //按找id z-a排序查询
                // userQuery = userDao.queryBuilder().orderDesc(UserDao.Properties.Id).build();
                //按找id a-a排序查询
                userQuery = userDao.queryBuilder().orderAsc(UserDao.Properties.Id).build();
                //查询满足指定属性值的结果
                //userQuery = userDao.queryBuilder().where(UserDao.Properties.Text.eq(33),UserDao.Properties.Comment.eq(22)).build();
                List<User> datalist= userQuery.list();
                StringBuffer res = new StringBuffer();
                for (User user1 : datalist) {
                    res.append("id= "+user1.getId());
                    res.append("  text="+user1.getText());
                    res.append("  comment="+user1.getComment()+"\n");
                    //res.append(" date="+user1.getDate()+"\n");
                }
                tShow.setText(res.toString());
                break;
                
                //删
            case R.id.but_del_data:
                String index = num.getText().toString();
                userDao.deleteByKey(Long.valueOf(index));
                num.setText("");
                break;
                
                //改
            case R.id.but_modify_data:
                String www = num.getText().toString();
                String test2 = text.getText().toString();
                String con2 = comment.getText().toString();
                User user2 = new User();
                user2.setId(Long.valueOf(www));
                user2.setComment(con2);
                user2.setDate(new Date());
                user2.setText(test2);
                userDao.update(user2);
                text.setText("");
                comment.setText("");
                num.setText("");
                break;
        }
    }
}

三、GreenDao常用注解

@Entity 用于标识这是一个需要Greendao帮我们生成代码的bean

@Id 标明主键,括号里可以指定是否自增

@Property 用于设置属性在数据库中的列名(默认不写就是保持一致)

@NotNull 非空

@Transient 标识这个字段是自定义的不会创建到数据库表里

@Unique 添加唯一约束

@ToOne 是将自己的一个属性与另一个表建立关联(外键)

@ToMany的属性referencedJoinProperty,类似于外键约束。

@JoinProperty 对于更复杂的关系,可以使用这个注解标明目标属性的源属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值