greendao3 使用和源码分析

来源:互联网 发布:mac的终端文件路径 编辑:程序博客网 时间:2024/05/29 17:46

一、引入

为何选择greendao
看了这个图:一般人都会立刻采纳,去使用,
图片来自:http://greendao-orm.com/features/
这里写图片描述
它也是基于orm的,但是不用反射,说,用反射比较慢。
你信吗,那就做一个时间试试嘛,这里看一个哥们写的:
实现基于注解(Annotation)的数据库框架(六)亲自验证反射的效率及解决办法

github链接
greenDao所有的api
@Entity 标识实体类,GreenDao会映射成sqlite中的一个表
@Id 标识主键
@Property 标识该属性在表中对应的列名称
@Transient 标识该属性将不会映射到表中,也就是没有这列
还有很多的注释,大家可以参考注解的api

1.在as中引入

怎么使用,:
大家看看:Android实战——GreenDao3.2的使用,爱不释手

1.1查看博主代码的后,引入报错

在as中,引用推荐链接的工程后,总是报错,不能产生dao文件,
解决:
查找资料,都是自己按照java工程,运行,自动生成dao文件,其实就是按照javabean 来解析生成对应的数据库文件,
但是,发现github上,早就有大神,将此打成引用包
GreenDaoGenerator
源码,

package com.jtristan.greendaogenerator;import de.greenrobot.daogenerator.DaoGenerator;import de.greenrobot.daogenerator.Entity;import de.greenrobot.daogenerator.Property;import de.greenrobot.daogenerator.Schema;import de.greenrobot.daogenerator.ToMany;public class Pedido {    public static void main(String[] args) throws Exception {        Schema esquema = new Schema(4, "com.jtristan.greendao.dao");        esquema.enableKeepSectionsByDefault();        addCabeceraPedido(esquema);             new DaoGenerator().generateAll(esquema, "../GreenDao/src-gen");    }    /**     * @param esquema     */    private static void addCabeceraPedido(Schema esquema) {            Entity cabeceraPedido = esquema.addEntity("Pedido");            //Activa la sección para nuestro propio código en el dao.            cabeceraPedido.setHasKeepSections(true);            cabeceraPedido.addIdProperty();            cabeceraPedido.addLongProperty("numeroPedido").unique();            cabeceraPedido.addStringProperty("cliente").notNull();            cabeceraPedido.addLongProperty("direccion").notNull();            cabeceraPedido.addLongProperty("idCondicionPago").notNull().getProperty();            cabeceraPedido.addBooleanProperty("finalizado");            cabeceraPedido.addDateProperty("fechaCreacion");                                    Entity lineaPedido = esquema.addEntity("Linea");            //Prueba de como crear un id. el addIdProperty todavía no está resuelto totalmente.                     Property idLineaPedido = lineaPedido.addLongProperty("_id").primaryKey().getProperty();            Property idPedido = lineaPedido.addLongProperty("idPedido").notNull().getProperty();            lineaPedido.addStringProperty("material");            lineaPedido.addIntProperty("cantidad");            lineaPedido.addDoubleProperty("precio");            lineaPedido.addDateProperty("fechaCreacion");            //Relaciones: Una línea va a pertenecer a un único pedido. 1:1.            lineaPedido.addToOne(cabeceraPedido, idPedido);            //Un pedido puede tener varias líneas. Para ello creamos un objeto ToMany.            ToMany lineasDeUnPedido = cabeceraPedido.addToMany(lineaPedido, idPedido);            lineasDeUnPedido.setName("Lineas");            lineasDeUnPedido.orderAsc(idLineaPedido);            Entity condicionPago = esquema.addEntity("CondicionPago");            condicionPago.addIdProperty();            condicionPago.addStringProperty("condicion");            condicionPago.addDoubleProperty("porcentaje");            condicionPago.addDoubleProperty("valor");                       // Tabla para n:m relaciones.            // Le decimos de que tábla y campo van a venir  cada campo.            Entity condicionesPagoDeUnPedido = esquema.addEntity("CondicionPagoDeUnPedido");            Property idPedidoEnCondiciones = condicionesPagoDeUnPedido.addLongProperty("idPedido").notNull().getProperty();            Property idCondicion = condicionesPagoDeUnPedido.addLongProperty("idCondicion").notNull().getProperty();            condicionesPagoDeUnPedido.addToOne(condicionPago, idCondicion);            ToMany condicionesDePagoDeUnPedido = cabeceraPedido.addToMany(condicionesPagoDeUnPedido, idPedidoEnCondiciones);            condicionesDePagoDeUnPedido.setName("CondicionesPago");    }}

2.在android studio中引入greendao 真正步骤

2.1在projoct的build.gradle里

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    }

2.2在app build.gradle里

apply plugin: 'com.android.application'apply plugin: 'org.greenrobot.greendao'android {    compileSdkVersion 23    buildToolsVersion "25.0.2"    defaultConfig {        applicationId "com.hensen.greendaodemo"        minSdkVersion 16        targetSdkVersion 23        versionCode 1        versionName "1.0"    }    //greendao配置    greendao {        //版本号,升级时可配置        schemaVersion 1        //生成dao的路径        daoPackage 'com.hensen.greendaodemo'        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:23.4.0'    //ORM数据库    compile 'org.greenrobot:greendao:3.2.2'    //这是一步很关键呀    compile'org.greenrobot:greendao-generator:3.0.0'    compile files('libs/xUtils-2.6.14.jar')}

3.使用方法

a 在bean里生成bean

b build工程

c 在设计路径发现,生成的dao

d 自己简洁设计数据库,操作类,增删改查

这里写图片描述

使用效果:
这里写图片描述

demo项目源码下载

二、源码分析

重点来看,框架源码

原创粉丝点击