greendao入门案例(crud)

greendao入门案例(crud)


一、gradle配置

二、初始化数据库

三、编写crud操作

四、效果图


一、gradle配置

  • 项目级gradle中做如下配置
buildscript {
    ext{
        greendao_version = '3.2.2'
        schema_version=1
    }
   
    dependencies {
        classpath "org.greenrobot:greendao-gradle-plugin:$greendao_version"
    }
}
  • app的gralde中做如下配置
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
   ....
}

greendao {
    //数据库的版本号
    schemaVersion schema_version
    //设置DaoMaster、DaoSession、Dao包名,也就是要放置这些类的包的全路径。
    daoPackage 'com.itplus.greendaodemo.entity.greendao'
    //设置DaoMaster、DaoSession、Dao目录
    targetGenDir 'src/main/java'
}
dependencies {
    ...
    api "org.greenrobot:greendao:$greendao_version"
}
  • 点击 “”按钮重新编译gradle , 自动生成以下文件
    greendao入门案例(crud)_第1张图片

二、初始化数据库

public class MyApp extends Application {
    public static final String DB_NAME = "itplus.db";
    private DaoSession mDaoSession;
    private static MyApp appInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        appInstance = this;
        initGreenDao();
    }

    private void initGreenDao() {
        // 初始化数据库信息
        DaoMaster.DevOpenHelper devdOpenHelper = new DaoMaster.DevOpenHelper(this, DB_NAME);
        Database db = devdOpenHelper.getWritableDb();
        mDaoSession = new DaoMaster(db).newSession();
    }

    public static MyApp getAppInstance() {
        return appInstance;
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }
}
  • 创建数据库的操作接口及实现
    greendao入门案例(crud)_第2张图片
public interface StudentDaoService {
    /**
     * 新增一条学生数据
     *
     * @param student
     * @return
     */
    boolean addStudentInfo(Student student);

    /**
     * 通过id查询一条记录
     *
     * @param id
     * @return
     */
    Student findStudentById(Long id);

    /**
     * 查询所有记录
     *
     * @return
     */
    List<Student> findAll();

    /**
     * 修改一条信息
     *
     * @param student
     * @return
     */
    boolean modifyStudentInfo(Student student);

    /**
     * 删除一条信息
     *
     * @param id
     * @return
     */
    boolean deleteStudentInfo(Long id);
}
public class StudentDaoServiceImpl implements StudentDaoService {

    private final StudentDao mStudentDao;

    public StudentDaoServiceImpl() {
        mStudentDao = MyApp.getAppInstance().getDaoSession().getStudentDao();
    }

    @Override
    public boolean addStudentInfo(Student student) {
        long result = mStudentDao.insert(student);
        return result > 0;
    }

    @Override
    public Student findStudentById(Long id) {
        return mStudentDao.loadByRowId(id);
    }

    @Override
    public List<Student> findAll() {
        return mStudentDao.loadAll();
    }

    @Override
    public boolean modifyStudentInfo(Student student) {
        try {
            mStudentDao.update(student);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean deleteStudentInfo(Long id) {
        try {
            mStudentDao.deleteByKey(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}


三、编写crud操作

  • 布局
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="addStudentInfo"
            android:text="插入一条数据" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="findStudentById"
            android:text="查询一条数据" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="findAll"
            android:text="查询所有数据" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="modifyStudentInfo"
            android:text="修改一条数据" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="deleteStudentInfo"
            android:text="删除一条数据" />
    </LinearLayout>
</ScrollView>
  • 测试界面
public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();
    private StudentDaoService mStudentDaoService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mStudentDaoService = new StudentDaoServiceImpl();
    }

    public void addStudentInfo(View view) {
        boolean isOk = mStudentDaoService.addStudentInfo(new Student("李小龙", 20));
        Toast.makeText(this, "新增数据" + (isOk ? "成功" : "失败"), Toast.LENGTH_SHORT).show();
        Log.d(TAG, "新增数据" + (isOk ? "成功" : "失败"));
    }

    public void findStudentById(View view) {
        Student student = mStudentDaoService.findStudentById(1L);
        if (student != null) {
            Log.d(TAG, "查询结果: " + student.toString());
        } else {
            Toast.makeText(this, "没有查询到相关记录", Toast.LENGTH_SHORT).show();
        }
    }

    public void findAll(View view) {
        List<Student> studentList = mStudentDaoService.findAll();
        if (studentList!=null&&studentList.size()>0){
            for (Student student : studentList) {
                Log.d(TAG, "查询结果: " + student.toString());
            }
        }else {
            Toast.makeText(this, "没有查询到相关记录", Toast.LENGTH_SHORT).show();
        }
    }

    public void modifyStudentInfo(View view) {
        Student student = new Student(1L,"鲁班", 18);
        boolean updateResult = mStudentDaoService.modifyStudentInfo(student);
        Toast.makeText(this, "修改数据" + (updateResult ? "成功" : "失败"), Toast.LENGTH_SHORT).show();
        Log.d(TAG, "修改数据" + (updateResult ? "成功" : "失败"));
    }

    public void deleteStudentInfo(View view) {
        boolean deleteResult = mStudentDaoService.deleteStudentInfo(1L);
        Toast.makeText(this, "删除数据" + (deleteResult ? "成功" : "失败"), Toast.LENGTH_SHORT).show();
        Log.d(TAG, "删除数据" + (deleteResult ? "成功" : "失败"));
    }
}


四、效果图

greendao入门案例(crud)_第3张图片

greendao入门案例(crud)_第4张图片


你可能感兴趣的:(android)