ORMLite使用

一、ORM概念

       ORM(全称Object Relation Mapping)叫做对象关系映射,是一种程序设计技术,用于实现面向对象编程语言中不同类型系统的数据之间的转换。

      目前比较流行的ORM框架有OrmLite、greendao、Active Android、XUtils3等。

二、OrmLite原理

原理:基于反射和注解的原理,效率较低

三、OrmLite的基本使用步骤

1. 导包

2. 自定义实体类

3. 创建数据库辅助类OrmLiteSqliteOpenHelper

4. 创建DAO类,具体管理表

5. 执行CRUD操作

四、导包

      将下载的ormlite-core-5.0.jar

五、自定义实体类

通过注解的方式创建实体类


@DatabaseTable 设置表名

@DatabaseField 设置字段


举例:

@DatabaseTable(tableName = "student")

public class Student {        

    @DatabaseField(columnName = "_id", dataType = DataType.INTEGER, generatedId = true)         

                private int id;         

    @DatabaseField(columnName = "name", dataType = DataType.STRING, canBeNull = false)         

                private String name;         

    @DatabaseField(columnName = "age", dataType = DataType.INTEGER, canBeNull = true)         

                private int age;          //get、set方法 }



常用参数一览:

columnName 字段名

dataType 数据类型

defaultValue 字符串默认值

canBeNull 可否为空

id 主键

generatedId 自增主键

foreign 外联

unique 唯一


dataType 常用数据类型

STRING(StringType.getSingleton()),

BOOLEAN(BooleanType.getSingleton()),

DATE(DateType.getSingleton()),

DATE_LONG(DateLongType.getSingleton()),

CHAR(CharType.getSingleton()),

BYTE(ByteType.getSingleton()),

SHORT(ShortType.getSingleton()),

INTEGER(IntType.getSingleton()),

LONG(LongType.getSingleton()),

FLOAT(FloatType.getSingleton()),

DOUBLE(DoubleType.getSingleton()),

SERIALIZABLE(SerializableType.getSingleton()),

TIME_STAMP(TimeStampType.getSingleton())


六、 创建数据库辅助类OrmLiteSqliteOpenHelper

1. 重写构造方法

OrmLiteSqliteOpenHelper(Context context,String databaseName,CursorFactory factory, intdatabaseVersion)

2. 实现抽象方法

    2.1. 创建数据库,一般在方法内部创建表,可以直接使用TableUtils.createTable(connectionSource, User.class);进行创建

    onCreate(SQLiteDatabase database,ConnectionSource connectionSource)

    2.2. 更新数据库

    onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)

3. 使用TableUtils进行创建表、删除表、清空数据等操作

createTable

dropTable

clearTable

4. 实现单例模式

        整个DatabaseHelper使用单例只对外公布出一个对象,保证app中只存在一个SQLite Connection。

public static DBHeloer dbHeloer;

public synchronized  static DBHeloer newInstance(Context context){

         if (dbHeloer == null) {

                  dbHeloer = new DBHeloer(context);

         }

        return dbHeloer;

}

七、创建DAO辅助类

1. 创建DAO对象       

Dao包含两个泛型,第一个泛型表DAO操作的类,第二个表示被操作类的主键类型       

getDao为一个泛型方法,会根据传入Class对象进行创建Dao,并且使用一个Map来保持所有的Dao对象,只有第一次调用时才会去调用底层的getDao()

2. DAO主要方法

2.1 添加数据

int create(T t) throws SQLException;   

int create(Collectionvar1) throws SQLException;

T createIfNotExists(T t) throws SQLException;

2.2 删除数据

int delete(T t) throws SQLException;   

int deleteById(Intenger id) throws SQLException;   

int delete(Collectionvar1) throws SQLException;   

int deleteIds(Collectionids) throws SQLException; 

2.3 更新数据

int update(T var1) throws SQLException;

int updateId(T var1, ID var2) throws SQLException;

2.4 查询数据

T queryForId(ID var1) throws SQLException;   

ListqueryForAll() throws SQLException;

八、Builder       

DAO中提供了几个相关的Builder方法,可以进行按条件操作,使用方式相似,

以最常用的QueryBuilde为例进行说明。

QueryBuilderqueryBuilder();  

UpdateBuilderupdateBuilder();   

 DeleteBuilderdeleteBuilder();

QueryBuilder

对象常用方法

QueryBuild  erqueryBuilder = stuDao.queryBuilder();          

queryBuilder       

    .distinct()// 排重                           

    .groupBy("columnName")  //分组       

    .limit(1000L).offset(10L) //分页                                           

    .orderBy("", true)  //排序                          

    .where().like("name", "%张三%");         

   List stus = queryBuilder.query();

九、事物管理

DatabaseConnection connection =

      new    AndroidDatabaseConnection(dbHelper.getReadableDatabase(), true);

connection.setAutoCommit(false); //设置不自动提交

Savepoint savepoint = connection.setSavePoint("point name"); //设置回滚点

try {

       //....很多数据库操作

       connection.commit(savepoint); //提交事物

} catch (Exception e) {

       e.printStackTrace();

      connection.rollback(savepoint); //回滚事物

}

你可能感兴趣的:(ORMLite使用)