首先:查看柯南的博客
package wld.bawei.com.mygreendao;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wld.bawei.com.mygreendao.database.DaoSession;
import wld.bawei.com.mygreendao.database.MyBeanDao;
public class MainActivity extends AppCompatActivity {
private MyBeanDao myBeanDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
DaoSession daoSession = GreenDaoUtils.getDaoSession();
myBeanDao = daoSession.getMyBeanDao();
}
@OnClick({R.id.add,R.id.deletename,R.id.deleteid,R.id.update,R.id.updateid,R.id.updatemany,R.id.query,R.id.clear})
public void onViewClicked(View view){
switch (view.getId()){
case R.id.add:
MyBean skn = new MyBean(null,"宋克楠",20);
MyBean wld = new MyBean(null, "武立栋", 21);
myBeanDao.insertInTx(skn,wld);
break;
case R.id.deletename:
MyBean myBeandelete = myBeanDao.queryBuilder()
.where(MyBeanDao.Properties.Name.eq("宋克楠"),MyBeanDao.Properties.Age.eq(20))
.unique();
myBeanDao.delete(myBeandelete);
break;
case R.id.deleteid:
myBeanDao.deleteByKey(2l);
case R.id.update:
MyBean myBeanupdate=myBeanDao.queryBuilder()
.where(MyBeanDao.Properties.Name.eq("宋克楠"))
.unique();
myBeanupdate.setAge(50);
myBeanDao.update(myBeanupdate);
break;
case R.id.updateid:
MyBean load = myBeanDao.load(13l);
load.setAge(88);
myBeanDao.update(load);
break;
case R.id.updatemany:
Query<MyBean> buildtwo = myBeanDao.queryBuilder()
.orderAsc(MyBeanDao.Properties.Age)
.where(MyBeanDao.Properties.Name.eq("武立栋"))
.build();
List<MyBean> listtwo = buildtwo.list();
for (MyBean arr:listtwo){
arr.setName("武老师");
myBeanDao.update(arr);
}
break;
case R.id.query:
Query<MyBean> build = myBeanDao.queryBuilder().orderAsc(MyBeanDao.Properties.Id).build();
List<MyBean> list = build.list();
for (MyBean arr:list){
Log.e("aaa","序号:"+arr.getId()+"姓名:"+arr.getName()+"年龄"+arr.getAge());
}
break;
case R.id.clear:
myBeanDao.deleteAll();
break;
}
}
}