GreenDao基本实现

Student类:

@Entity(nameInDb = "student_tb",createInDb = true)
public class Student {
@Id
private Long id;
@Property(nameInDb = "NAME")
private String name;
@Transient
private int temp;
@Generated(hash = 1097502469)
public Student(Long id, String name) {
this.id = id;
this.name = name;
}
@Generated(hash = 1556870573)
public Student() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}


Student1类:

@Entity(nameInDb = "student_tb",createInDb = true)
public class Student {
    @Id(autoincrement = true)
    private Long id;
    @Property(nameInDb = "name")
    private String name;
    @Transient
    private int temp;
    @Property(nameInDb = "hobby")
    @NotNull@Index(name = "NO",unique = true)
    private String hobby;
    @Property(nameInDb = "number")
    @Unique
    private int number;
    private int age;
    @Generated(hash = 586419876)
    public Student(Long id, String name, @NotNull String hobby, int number,
            int age) {
        this.id = id;
        this.name = name;
        this.hobby = hobby;
        this.number = number;
        this.age = age;
    }
    @Generated(hash = 1556870573)
    public Student() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getHobby() {
        return this.hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public int getNumber() {
        return this.number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", temp=" + temp +
                ", hobby='" + hobby + '\'' +
                ", number=" + number +
                ", age=" + age +
                '}';
    }
    public int getAge() {
        return this.age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}


Picture类:

@Entity
public class Picture {
    @Id(autoincrement = true)
    private Long pictureId;
    @NotNull
    @Unique
    private String url;
    @Generated(hash = 2145315602)
    public Picture(Long pictureId, @NotNull String url) {
        this.pictureId = pictureId;
        this.url = url;
    }
    @Generated(hash = 1602548376)
    public Picture() {
    }
    public Long getPictureId() {
        return this.pictureId;
    }
    public String getUrl() {
        return this.url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public void setPictureId(Long pictureId) {
        this.pictureId = pictureId;
    }
    @Override
    public String toString() {
        return "Picture{" +
                "pictureId=" + pictureId +
                ", url='" + url + '\'' +
                '}';
    }
}



Application类:

public class MyApplication extends Application {
    private static MyApplication mApp;
    private SQLiteDatabase database;
    private DaoSession daoSession;
    private StudentDao studentDao;
    public StudentDao getStudentDao() {
        return studentDao;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        initDB();
    }
    private void initDB() {
        DaoMaster.DevOpenHelper devOpenHelper
                = new DaoMaster.DevOpenHelper(this, "student-db", null);
        database = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(database);
        daoSession = daoMaster.newSession();
        studentDao = daoSession.getStudentDao();
        //自定义DBHelper的方式,进行初始化.
//        MyDBHelper dbHelper = new MyDBHelper(this);
//        DaoMaster master = new DaoMaster(dbHelper.getWritableDatabase());
//        StudentDao dao = master.newSession().getStudentDao();
    }
    public SQLiteDatabase getDatabase() {
        return database;
    }
    public DaoSession getDaoSession() {
        return daoSession;
    }
    public static MyApplication getInstance(){
        return mApp;
    }
}


Teacher类:

@Entity(
        // 如果有一个以上的模式,可以告诉greendao实体属于哪个模式。
        //默认schema = "default",
        //schema = "default",
        // 标志允许实体类可有更新,删除,刷新方法
        active = true,
        //指定数据库中表的名称,默认情况下,该表的名称是实体类名。
        nameInDb = "teacher_tb",
        // true表示greenDAO创建数据库表(默认为true),如果不用greenDAO创建表,将此设置为false。
        createInDb = true,
        // 是否应该生成所有的属性构造函数。无参构造函数总是要生成的
        generateConstructors = true,
        // 是否生成属性的getter和setter
        generateGettersSetters = true
)
public class Teacher {
    @Id
    private Long id;
    private String name;
    private Long pictureId;
    @ToOne(joinProperty = "pictureId")
    private Picture picture;
    @NotNull
    private int age;
    @ToMany(referencedJoinProperty = "ownerId")
    private List<Car> cars;
    /**
     * Used to resolve relations
     */
    @Generated(hash = 2040040024)
    private transient DaoSession daoSession;
    /**
     * Used for active entity operations.
     */
    @Generated(hash = 648119699)
    private transient TeacherDao myDao;
    @Generated(hash = 1986840853)
    private transient Long picture__resolvedKey;
    @Generated(hash = 589179490)
    public Teacher(Long id, String name, Long pictureId, int age) {
        this.id = id;
        this.name = name;
        this.pictureId = pictureId;
        this.age = age;
    }
    @Generated(hash = 1630413260)
    public Teacher() {
    }
    public int getAge() {
        return this.age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 128553479)
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }
    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 1942392019)
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }
    /**
     * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}.
     * Entity must attached to an entity context.
     */
    @Generated(hash = 713229351)
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }
    /**
     * called by internal mechanisms, do not call yourself.
     */
    @Generated(hash = 1349174479)
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getTeacherDao() : null;
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Long getPictureId() {
        return this.pictureId;
    }
    public void setPictureId(Long pictureId) {
        this.pictureId = pictureId;
    }
    /**
     * To-one relationship, resolved on first access.
     */
    @Generated(hash = 1937024467)
    public Picture getPicture() {
        Long __key = this.pictureId;
        if (picture__resolvedKey == null || !picture__resolvedKey.equals(__key)) {
            final DaoSession daoSession = this.daoSession;
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            PictureDao targetDao = daoSession.getPictureDao();
            Picture pictureNew = targetDao.load(__key);
            synchronized (this) {
                picture = pictureNew;
                picture__resolvedKey = __key;
            }
        }
        return picture;
    }
    /**
     * called by internal mechanisms, do not call yourself.
     */
    @Generated(hash = 1412118702)
    public void setPicture(Picture picture) {
        synchronized (this) {
            this.picture = picture;
            pictureId = picture == null ? null : picture.getPictureId();
            picture__resolvedKey = pictureId;
        }
    }
    /**
     * To-many relationship, resolved on first access (and after reset).
     * Changes to to-many relations are not persisted, make changes to the target entity.
     */
    @Generated(hash = 1867445117)
    public List<Car> getCars() {
        if (cars == null) {
            final DaoSession daoSession = this.daoSession;
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            CarDao targetDao = daoSession.getCarDao();
            List<Car> carsNew = targetDao._queryTeacher_Cars(id);
            synchronized (this) {
                if (cars == null) {
                    cars = carsNew;
                }
            }
        }
        return cars;
    }
    /** Resets a to-many relationship, making the next get call to query for a fresh result. */
    @Generated(hash = 1055213807)
    public synchronized void resetCars() {
        cars = null;
    }
    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pictureId=" + pictureId +
                ", picture=" + picture +
                ", age=" + age +
                ", cars=" + cars +
                ", daoSession=" + daoSession +
                ", myDao=" + myDao +
                ", picture__resolvedKey=" + picture__resolvedKey +
                '}';
    }
}


Main类:

public class MainActivity extends Activity {
    private StudentDao studentDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        studentDao = MyApplication
                .getInstance()
                .getStudentDao();
    }

    public void MyClick(View view) {
        switch (view.getId()){
            case R.id.btn1:
                studentDao.insert(new Student(){
                    {
                        this.setId(1l);
                        this.setName("李逵");
                    }
                });
                break;
            case R.id.btn2:
                break;
        }
    }
}

Main1类:

@BindView(R.id.btn_greendao)
    Button btnGreendao;
    @BindView(R.id.tv_show)
    TextView tvShow;
    @BindView(R.id.btn2)
    Button btn2;
    private StudentDao studentDao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        studentDao = MyApplication
                .getInstance()
                .getStudentDao();
    }
    @OnClick(R.id.btn_greendao)
    public void onViewClicked() {
        DialogUtil.showListDialog(this, "greendao的操作使用!", new String[]{
                "0增加一条数据",
                "1删除一条数据",
                "2修改一条数据",
                "3查询一条数据",
                "4增加List集合数据",
                "5查询所有的数据",
                "6查询指定字段的数据",
                "7查询指定字段的数据降序排列",
                "8查询指定字段的数据升序排列",
                "9组合查询数据",
                "10查询所有的数据,只取指定条数",
                "11查询所有,取指定条数,跳过某条",
                "12查询数据总条数",
                "13修改指定字段的数据",
                "14删除指定数据方式1",
                "15删除指定数据方式2",
                "16删除全部数据",
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        //添加一条数据.
                        insert();
                        break;
                    case 1:
                        //删除一条数据
                        studentDao.deleteByKey(1l);
                        break;
                    case 2:
                        //修改一条数据
                        update();
                        break;
                    case 3:
                        //查询一条数据
                        load();
                        break;
                    case 4:
                        //插入一个集合的数据,insertList
                        insertList();
                        break;
                    case 5:
                        //查询所有的数据
                        list();
                        break;
                    case 6:
                        //查询指定姓名为张非3的数据
                        nameList();
                        break;
                    case 7:
                        //查询指定姓名为李四的信息并按照年龄排序-降序
                        ageOrderList();
                        break;
                    case 8:
                        //查询指定姓名为李四的信息并按照年龄排序-升序
                        //agaOrderAsc
                        agaOrderAsc();
                        break;
                    case 9:
                        // 查询姓名为"李四" 并且成绩小于等于60的信息
                        nameAgeList();
                        break;
                    case 10:
                        //查询所有数据,只取前3条
                        limtList();
                        break;
                    case 11:
                        //查询所有,只要前3条,从指定条数索引处的下一条开始查询
                        limtOffsetList();
                        break;
                    case 12:
                        //查询数据总条数
                        listSize();
                        break;
                    case 13:
                        //修改姓名张非1的姓名
                        updateName();
                        break;
                    case 14:
                        //删除指定姓名为张非2的数据
                        executeDeleteWithoutDetachingEntities();
                        break;
                    case 15:
                        //通过指定对象删除数据,删除张非4
                        delStu();
                        break;
                    case 16:
                        //删除全部数据!
                        studentDao.deleteAll();
                        break;
                }
            }
        });
    }
    private void delStu() {
        Student student = studentDao.
                queryBuilder()
                .where(StudentDao.Properties.Name.eq("张非4"))
                .unique();
        studentDao.delete(student);
        DemonstrateUtil.showLogResult("删除,张非4");
    }
    private void executeDeleteWithoutDetachingEntities() {
        studentDao.
                queryBuilder()
                .where(StudentDao.Properties.Name.eq("张非2"))
                .buildDelete()
                .executeDeleteWithoutDetachingEntities();
        DemonstrateUtil.showLogResult("删除成功!");
    }
    private void updateName() {
        Student student = studentDao.
                queryBuilder()
                .where(StudentDao.Properties.Name.eq("张非1"))
                .unique();
        if (null != student) {
            student.setName("张三");
            studentDao.update(student);
            DemonstrateUtil.showToastResult(this, "修改成功!");
            Student student1 = studentDao.
                    queryBuilder()
                    .where(StudentDao.Properties.Name.eq("张三"))
                    .unique();
            DemonstrateUtil.showLogResult(student1.toString());
        } else {
            DemonstrateUtil.showToastResult(this, "要修改的数据不存在!!");
        }
    }
    private void listSize() {
        tvShow.setText("总条数:" + studentDao.queryBuilder()
                .list().size());
    }
    private void limtOffsetList() {
        List<Student> students = studentDao.queryBuilder()
                .limit(3)
                .offset(2)
                .list();
        tvShow.setText(students.toString());
        for (Student student : students) {
            DemonstrateUtil.showLogResult(student.toString());
        }
    }
    private void limtList() {
        List<Student> students = studentDao.queryBuilder()
                .limit(3)
                .list();
        tvShow.setText(students.toString());
        for (Student student : students) {
            DemonstrateUtil.showLogResult(student.toString());
        }
    }
    private void nameAgeList() {
        List<Student> students = studentDao
                .queryBuilder()
                .where(StudentDao.Properties.Name.eq("李四"), StudentDao.Properties.Age.le(17))
                .list();
        tvShow.setText(students.toString());
        for (Student stu : students) {
            DemonstrateUtil.showLogResult(stu.toString());
        }
    }
    private void agaOrderAsc() {
        List<Student> students = studentDao
                .queryBuilder()
                .where(StudentDao.Properties.Name.eq("李四"))
                .orderAsc(StudentDao.Properties.Age)
                .list();
        tvShow.setText(students.toString());
        for (Student stu : students) {
            DemonstrateUtil.showLogResult(stu.toString());
        }
    }
    private void ageOrderList() {
        List<Student> students = studentDao
                .queryBuilder()
                .where(StudentDao.Properties.Name.eq("李四"))
                .orderDesc(StudentDao.Properties.Age)
                .list();
        tvShow.setText(students.toString());
        for (Student student : students) {
            //DemonstrateUtil.showLogResult(student.toString());
        }
    }
    private void insertList() {
        studentDao.insertInTx(new ArrayList<Student>() {
            {
                for (int i = 1; i <= 5; i++) {
                    int num = i + 1;
                    num++;
                    add(new Student(null, "张非" + i, "吃饭" + i, num, 20));
                }
                add(new Student(null, "李四", "吃饭", 10, 15));
                add(new Student(null, "李四", "睡觉", 11, 16));
                add(new Student(null, "李四", "敲码", 12, 17));
                add(new Student(null, "李四", "爱说话", 13, 18));
            }
        });
    }
    private void update() {
        studentDao.update(new Student() {
            {
                setNumber(1);
                setName("王小明");
                setId(1l);
                setHobby("吃饭睡觉敲码");
            }
        });
        DemonstrateUtil.showToastResult(this, "数据修改!");
    }
    private void nameList() {
        List<Student> students = studentDao.queryBuilder().where(StudentDao.Properties.Name.eq("张非3")).list();
        tvShow.setText(students.toString());
        for (Student student : students) {
            DemonstrateUtil.showLogResult(student.toString());
        }
    }
    private void list() {
        List<Student> studentList = studentDao.queryBuilder().list();
        tvShow.setText(studentList.toString());
        for (Student student : studentList) {
            DemonstrateUtil.showLogResult(student.toString());
        }
    }
    private void load() {
        Student student = studentDao.load(1l);
        if (null != student) {
            tvShow.setText(student.toString());
        } else {
            tvShow.setText("查询的数据不存在!!");
            DemonstrateUtil.showToastResult(MyApplication.getInstance(), "数据不存在哦!!");
        }
    }
    private void insert() {
        //返回插入数据实体的id
        long insert = studentDao.insert(new Student() {
            {
                this.setHobby("写代码");
                this.setName("王小明");
                this.setNumber(1);
                this.setAge(22);
            }
        });
        if (insert > 0) {
            DemonstrateUtil.showToastResult(this, "成功,实体id" + insert);
        } else {
            DemonstrateUtil.showToastResult(this, "失败,实体id" + insert);
        }
    }
    @OnClick(R.id.btn2)
    public void onViewClicked2() {
        startActivity(new Intent(this,GreenDaoDemo1Activity.class));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值