Greendao3.2使用

一、配置,添加红色部分


apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'

android {
    compileSdkVersion 22
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.hensen.greendaodemo"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    //greendao配置
    greendao {
        //版本号,升级时可配置
        schemaVersion 1
        daoPackage 'com.hensen.greendaodemo.gen'//自己包名
        targetGenDir 'src/main/java'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.1'
    //ORM数据库
    compile 'org.greenrobot:greendao:3.2.0'
    compile files('libs/xUtils-2.6.14.jar')
    compile 'org.xutils:xutils:3.3.40'
}
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        //GreenDao3
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
二、启动配置

public class BaseApplication extends Application{

    private static DaoSession daoSession;
    private  static DaoSession daoSessionuser;

    @Override
    public void onCreate() {
        super.onCreate();
        //配置数据库,自己命名
        setupDatabase("shop.db");
    }

    /**
     * 配置数据库
     */
    private  void setupDatabase(String str) {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, str, null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoInstant() {
        return daoSession;
    }

}
第三.新建实体

public class User {

    public static final int TYPE_CART = 0x01;
    public static final int TYPE_LOVE = 0x02;

    //不能用int
    @Id(autoincrement = true)
    private Long id;
//    @Unique
    private String name;
    @Property(nameInDb = "price")
    private String price;
    private int sell_num;
    private String image_url;
    private String address;
    private int type;}
第四.按ctrl+f9自动将实体生成get和set,同时gen包下自动生成相应数据库文件:
 BaseApplication.getDaoInstant().getShopDao()返回生成对应gen下的实体Dao对象 ,此对象即操作数据库
三个文件:ShopDao shao=
BaseApplication.getDaoInstant().getShopDao();

Greendao3.2使用_第1张图片

package com.hensen.greendaodemo.Dao;

import android.util.Log;
import android.widget.TextView;

import com.hensen.greendaodemo.Base.BaseApplication;
import com.hensen.greendaodemo.Bean.Shop;
import com.hensen.greendaodemo.Bean.User;
import com.hensen.greendaodemo.gen.ShopDao;
import com.hensen.greendaodemo.gen.UserDao;


import org.greenrobot.greendao.query.Query;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by handsome on 2016/4/19.
 */
public class LoveDao {

    /**
     * 添加数据
     *
     * @param shop
     */
    public static void insertLove(Shop shop) {//shop通过set方法把数据传上去,最后把对象插入数据库,即可生成对应的表
        BaseApplication.getDaoInstant().getShopDao().insert(shop);

    }
    /**
     * 删除数据
     *
     * @param id
     */
    public static void deleteLove(long id) {
        BaseApplication.getDaoInstant().getShopDao().deleteByKey(id);//根据id删除
    }
    /**
     * 更新数据
     *
     * @param
     */
    public static void updateLove() {
        updatadata();
//        BaseApplication.getDaoInstant().getShopDao().update(shop);
    }
    /**
     * 查询条件为Type=TYPE_LOVE的数据
     *
     * @return
     */
    public static List queryLove() {
//        return BaseApplication.getDaoInstant().getShopDao().queryBuilder().where(ShopDao.Properties.Type.eq(Shop.TYPE_LOVE)).list();//根据条件查询,返回一个集合
        Shop user =BaseApplication.getDaoInstant().getShopDao().load(2L);//根据id查询返回一个实体对象
        System.out.println("查询结果"+user);
        return  BaseApplication.getDaoInstant().getShopDao().loadAll();//查询所有数据
    }
    private static void updatadata() {
        //可以修改指定对应的数据,必须从数据库查询返回后才能更改对应的数据
//        List userss = BaseApplication.getDaoInstant().getShopDao().loadAll();
        List userss = BaseApplication.getDaoInstant().getShopDao().queryBuilder().where(ShopDao.Properties.Address.eq("广东深圳")).list();//根据条件查询,返回一个集合
        System.out.println("==="+userss);
        if(userss.size()>0){
         Shop shop= userss.get(1);//更改查询后,第二个对象的数据。
        shop.setSell_num(2);
            shop.setAddress("NBA湖人队");
        shop.setName("科比-布莱恩特");
        BaseApplication.getDaoInstant().getShopDao().update(shop);
        }
    }
    public static void querydataBy(TextView textView) {
        Query nQuery = BaseApplication.getDaoInstant().getShopDao().queryBuilder()
                .where(ShopDao.Properties.Name.eq("科比-布莱恩特")).where(ShopDao.Properties.Id.between(1,1000))//条件查询
//               .orderAsc(ShopDao.Properties.Id).limit(2)//orderDesc//降序和升序查询,限制查两条
                .build();
        List users = nQuery.list();
        textView.setText(users.toString());


    }
    public   static void saveNLists(final List list,TextView textview){
        final ArrayList userslsitw = new ArrayList<>();
        //可以批量修改,配合查询条件,修改满足某一条件下的数据
        Query nQuery = BaseApplication.getDaoInstant().getShopDao().queryBuilder()
                .where(ShopDao.Properties.Name.eq("科比-布莱恩特")).where(ShopDao.Properties.Id.between(1,1000))
//               .orderAsc(ShopDao.Properties.Id).limit(2)//orderDesc//降序和升序查询,限制查两条
                .build();
        final List users = nQuery.list();
//        if(list == null || list.isEmpty()){
//            return;
//        }
        System.out.println("批量数据可"+list);
        BaseApplication.getDaoInstant().getShopDao().getSession().runInTx(new Runnable() {//可以批量修改和插入
            @Override
            public void run() {
                for(int i=0; i<users.size(); i++){
                 Shop shop = users.get(i);
                    shop.setName("大神");
                 // BaseApplication.getDaoInstant().getShopDao().inserte(shop);//批量插入
BaseApplication. getDaoInstant ().getShopDao().insertOrReplace(shop) ;//批量修改,修改必须先从数据库拿出数据,然后取出对象,重新set值,在调用此方法即可修改了 } } }) ; List userss = BaseApplication. getDaoInstant ().getShopDao().loadAll() ; textview.setText(userss.toString()) ; } public static void deleteAllNote (TextView textview){//删除所有数据 BaseApplication. getDaoInstant ().getShopDao().deleteAll() ; List userss = BaseApplication. getDaoInstant ().getShopDao().loadAll() ; textview.setText(userss.toString()) ; } public static void deleteNote (){ Shop shop1 = new Shop() ; shop1.setId( 164L ) ; //根据指定Id删除 BaseApplication. getDaoInstant ().getShopDao().delete(shop1) ; }}

数据库操作只有多才能更好的理解


下面为一些常用的注解使用方式:

@Entity
public  class  User {
     @Id (autoincrement =  true )
     private  Long id;
  
     @Property (nameInDb =  "USERNAME" )
     private  String name;
  
     @NotNull
     private  int  repos;
  
     @Transient
     private  int  tempUsageCount;
  
     ...
}

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

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

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

@NotNull 非空

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

@Unique  添加唯一约束


你可能感兴趣的:(Greendao3.2使用)