首页 > 代码库 > GreenDao数据库框架的配置与增删改查

GreenDao数据库框架的配置与增删改查

并非原创,原创地址http://blog.csdn.net/njweiyukun/article/details/51893092

配置----------------------------------

  项目的gradle里的配置

apply plugin: ‘org.greenrobot.greendao‘

buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath ‘org.greenrobot:greendao-gradle-plugin:3.0.0‘
}
}
 在gradle的根模块中加入上述代码后,sync project的时候,gradle会自动去maven仓库下载一个gradle的插件,当然了,这个插件就是为greenDAO服务的,用来生成数据库相关的代码。

greendao {
schemaVersion 1
daoPackage ‘com.greendao.demo.gen‘
targetGenDir ‘src/main/java‘
}

 schemaVersion---->指定数据库schema版本号,迁移等操作会用到

    daoPackage-------->通过gradle插件生成的数据库相关文件的包名,默认为你的entity所在的包名

    targetGenDir-------->这就是我们上面说到的自定义生成数据库文件的目录了,可以将生成的文件放到我们的java目录中,而不是build中,这样就不用额外的设置资源目录了

导包

  1. compile ‘org.greenrobot:greendao:3.0.1‘  
  2. compile ‘org.greenrobot:greendao-generator:3.0.0‘

在根目录创建entity包名 定义实体数据库类

 


@Entity:将我们的java普通类变为一个能够被greenDAO识别的数据库类型的实体类

 

@Id:通过这个注解标记的字段必须是Long类型的,这个字段在数据库中表示它就是主键,并且它默认就是自增的

@Transient:表明这个字段不会被写入数据库,只是作为一个普通的java类字段,用来临时存储数据的,不会被持久化

重新编译后会生成一些代码以及gen目录

@Entity
public class User {
@Id
private Long id;
private String name;
@Transient
private int tempUsageCount; // not persisted
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Generated(hash = 873297011)
public User(Long id, String name) {
this.id = id;
this.name = name;
}
@Generated(hash = 586692638)
public User() {
}
}


初始化数据库
public class GreenDaoManager {
private static GreenDaoManager mGreenDaoManager;
private DaoMaster mMaster;
private DaoSession mDaosession;

public GreenDaoManager() {
DaoMaster.DevOpenHelper devOpenHelper=new DaoMaster.DevOpenHelper(MyLication.getContext(),"user-db",null);
mMaster=new DaoMaster(devOpenHelper.getWritableDatabase());
mDaosession=mMaster.newSession();
}
public static GreenDaoManager getInstance(){
if(mGreenDaoManager==null){
mGreenDaoManager=new GreenDaoManager();
}
return mGreenDaoManager;
}
public DaoMaster getMaster(){
return mMaster;
}
public DaoSession getDaosession(){
return mDaosession;
}
public DaoSession getNewDasession(){
mDaosession=mMaster.newSession();
return mDaosession;
}
}
出数据库中用的APPlication
public class MyLication extends Application {
private static Context mContext;

@Override
public void onCreate() {
super.onCreate();
mContext=getApplicationContext();
GreenDaoManager.getInstance();
}
public static Context getContext(){
return mContext;
}
}
自动生成的3个类

activity代码  包涵增删改查

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText mNameET;
private Button mAddBtn;
private ListView mUserLV;
private UserAdapter mUserAdapter;
private List<User> mUserList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}

private void initData() {
mUserList= GreenDaoManager.getInstance().getDaosession().getUserDao().queryBuilder().build().list();
mUserAdapter = new UserAdapter(this, mUserList);
mUserLV.setAdapter(mUserAdapter);
}

private void initView() {
mNameET = (EditText) findViewById(R.id.et_name);
mAddBtn = (Button) findViewById(R.id.btn_add);
mUserLV = (ListView) findViewById(R.id.lv_user);
findViewById(R.id.btn_delete).setOnClickListener(this);
findViewById(R.id.btn_update).setOnClickListener(this);

mAddBtn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
int viewId = v.getId();
switch (viewId){
case R.id.btn_add:
insertUser(null, mNameET.getText().toString());
break;
case R.id.btn_delete:
deleteUser("li");
break;
case R.id.btn_update:
updateUser("y","li");
break;
}
}
private void updateUser(String name,String newName){
UserDao userDao= GreenDaoManager.getInstance().getDaosession().getUserDao();
User findUser=userDao.queryBuilder()
.where(UserDao.Properties.Name.eq(name)).build().unique();
if(findUser!=null){
findUser.setName(newName);
GreenDaoManager.getInstance().getDaosession().getUserDao().update(findUser);
ToaskUtil.showToast(this,"修改成功");
updateAdapter(userDao.queryBuilder().list());
mUserAdapter.notifyDataSetChanged();
}else{
ToaskUtil.showToast(this,"没有找到该用户信息");
}
}
private void deleteUser(String name){
UserDao userDao=GreenDaoManager.getInstance().getDaosession().getUserDao();
User findUser=userDao .queryBuilder().where(UserDao.Properties.Name.eq(name)).build().unique();
if(findUser!=null){
userDao.deleteByKey(findUser.getId());
ToaskUtil.showToast(this,"删除成功");
updateAdapter(userDao.queryBuilder().list());
}else{
ToaskUtil.showToast(this,"没有找到该用户");
}
}
private void insertUser(Long id,String name){
UserDao userDao= GreenDaoManager.getInstance().getDaosession().getUserDao();
User user=new User(id,name);
userDao.insert(user);
mNameET.setText("");
updateAdapter(userDao.queryBuilder().list());

}
private void updateAdapter(List<User> list){
mUserList.clear();
mUserList.addAll(list);
mUserAdapter.notifyDataSetChanged();
}
}
activity的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add one" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete one" />
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="update one" />

<ListView
android:id="@+id/lv_user"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>


ListView的Adapter
package com.greendao.demo.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.greendao.demo.R;
import com.greendao.demo.entity.User;

import java.util.List;

/**
* Created by Administrator on 2016/10/10.
*/
public class UserAdapter extends BaseAdapter {
private List<User> mUserList;
private Context mContext;

public UserAdapter(Context mContext, List<User> mUserList) {
this.mUserList = mUserList;
this.mContext = mContext;
}

@Override
public int getCount() {
return mUserList == null ? 0 : mUserList.size();
}

@Override
public Object getItem(int position) {
return position;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user, null);
viewHolder = new ViewHolder();
viewHolder.tv_id = (TextView) convertView.findViewById(R.id.tv_id);
viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}

User user = mUserList.get(position);
viewHolder.tv_id.setText(String.valueOf(user.getId()));
viewHolder.tv_name.setText(user.getName());

return convertView;
}

class ViewHolder {
TextView tv_id;
TextView tv_name;
}
}
Adapter的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="30dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1"
android:layout_marginLeft="15dp"
android:textSize="25dp"/>
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="zhangsan"
android:textSize="25dp"/>
</LinearLayout>
<View
android:layout_marginTop="3dp"
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@android:color/holo_blue_bright"/>
</LinearLayout>

 

GreenDao数据库框架的配置与增删改查