LiteOrm Android Documentation

repository·master·Indexed 23 days ago

https://github.com/litesuits/android-lite-orm

A lightweight, high-performance ORM framework for Android designed to simplify SQLite CRUD operations. LiteOrm features automatic schema management, entity relationship mapping, and a streamlined API for saving, querying, and deleting records. It supports complex queries via QueryBuilder and WhereBuilder, automatic Java-to-SQLite type mapping, and provides specific configuration guidance for ProGuard obfuscation.

Tokens
2.7K
Snippets
6
Records
12
Agent score
80%

What's inside LiteOrm

  1. Overview of LiteOrm

    master

    LiteOrm is a lightweight, high-performance, and powerful ORM (Object-Relational Mapping) framework for Android. It is designed to allow developers to perform CRUD (Create, Read, Update, Delete) operations, manage entity relationships, and handle automatic data mapping with minimal code.

    Key characteristics include:

    • Performance: Optimized to be significantly faster than standard SQLiteDatabase#insert methods.
    • Simplicity: Follows a "convention over configuration" approach, requiring minimal annotations and often working without needing no-argument constructors.
    • Automatic Schema Management: Supports automatic table creation and intelligent column detection (automatically adding new fields to the database when models change).
    • Relationship Mapping: Supports persisting and recovering entity relationships (one-to-one, one-to-many, etc.) by marking relationship types on entity properties.
    • Type Support: Automatically maps Java types to SQLite types (TEXT, REAL, INTEGER, BLOB) and handles serialized containers like Date, ArrayList, and Vector.
  2. Basic CRUD API Patterns

    master

    LiteOrm follows a principle of extreme simplicity for common database operations. While the full API surface is extensive, the core interaction pattern follows these conventions:

    • Saving/Replacing: db.save(object)
    • Querying: db.query(Class)
    • Deleting All: db.deleteAll(Class)

    Other supported operations include insert, update, and delete.

  3. Core Features of LiteOrm

    master

    LiteOrm provides several advanced features for managing Android data:

    • Multi-database Support: Each database file is managed by a separate LiteOrm management class instance.
    • Flexible Storage: Supports storing database files in custom locations, including SD cards.
    • Automatic Type Identification: Automatically maps Java types to SQLite types (TEXT, REAL, INTEGER, BLOB).
    • Advanced Object Construction: Uses reflection and constructor parameter techniques, meaning you often do not need to provide a no-argument constructor for your entities.
    • Complex Data Support: Can automatically store sequences and containers like Date, ArrayList, and Vector.
    • Flexible Querying: Supports complex queries including where, order, limit, having, and group clauses.
    • Binding Syntax: Supports standard SQLite constraints such as NOT NULL, UNIQUE, DEFAULT, COLLATE, CHECK, and PRIMARY KEY, including conflict algorithms.
  4. Initialize LiteOrm as a singleton

    master

    To prevent database errors and ensure stability, you should maintain a single instance of LiteOrm for each database file used in your application. If your app uses only one database, LiteOrm should be a global singleton.

    Use LiteOrm.newSingleInstance(context, databaseName) to initialize it.

    static LiteOrm liteOrm;
    
    if (liteOrm == null) {
        liteOrm = LiteOrm.newSingleInstance(this, "liteorm.db");
    }
    liteOrm.setDebugged(true); // open the log
  5. Perform CRUD operations with LiteOrm

    master

    LiteOrm provides a high-level API for common database operations. Most operations can be performed with a single line of code.

    Save and Insert

    • save(object): Performs an upsert (inserts if new, updates if exists).
    • insert(object, ConflictAlgorithm): Inserts a new record with a specific conflict resolution strategy.

    Update

    • update(object): Updates the record matching the object's primary key.
    • update(list, ColumnsValue, ConflictAlgorithm): Performs a batch update on specific columns for a list of objects.

    Query

    • query(Class): Retrieves all records of a specific type.
    • queryById(id, Class): Retrieves a single record by its primary key.
    • query(QueryBuilder): Uses a QueryBuilder for complex queries including where, limit, order, and distinct.

    Delete

    • delete(object): Deletes a specific entity.
    • delete(Class, start, end, orderColumn): Deletes a range of records based on an ordered column.
    • delete(WhereBuilder): Deletes records matching specific criteria.
    • deleteAll(Class): Deletes all records of a type (including related objects if using a cascade instance).
    // Save
    School school = new School("hello");
    liteOrm.save(school);
    
    // Insert
    Book book = new Book("good");
    liteOrm.insert(book, ConflictAlgorithm.Abort);
    
    // Update
    book.setIndex(1988);
    book.setAuthor("hehe");
    liteOrm.update(book);
    
    // Update specific columns
    HashMap<String, Object> bookIdMap = new HashMap<String, Object>();
    bookIdMap.put(Book.COL_AUTHOR, "liter");
    liteOrm.update(bookList, new ColumnsValue(bookIdMap), ConflictAlgorithm.Fail);
    
    // Query all
    List list = liteOrm.query(Book.class);
    
    // Query by ID
    Student student = liteOrm.queryById(student1.getId(), Student.class);
    
    // Delete entity
    liteOrm.delete(student0);
    
    // Delete all
    liteOrm.deleteAll(School.class);
  6. Configure ProGuard to allow obfuscation of Model classes

    master

    To allow LiteOrm Model classes and their fields to be safely obfuscated by ProGuard, you must explicitly map them to database names using annotations. If you do not use these annotations, you must instead use ProGuard -keep rules to prevent the classes and fields from being renamed.

    Recommended approach (using annotations):

    1. Add @Table("table_name") to every Java Model class to define its table name.
    2. Add @Column("column_name") to every persistent property (member variable) to define its column name.

    If both annotations are present, the classes and properties can be safely obfuscated.

  7. Configure ProGuard rules for LiteOrm

    master

    Add the following ProGuard rules to ensure that annotations, signatures, and exceptions are preserved, and that enumeration members are kept correctly. This is required for LiteOrm to function properly after obfuscation.

    # Keep annotations, signatures, and exceptions
    -keepattributes *Annotation*,Signature,Exceptions
    
    # Keep enumeration members
    -keepclassmembers enum * {
        **[] $VALUES;
        public *;
    }
  8. Handle Enum changes in LiteOrm v1.5.3 and later

    master

    In LiteOrm version 1.5.3 and newer, internal enumeration classes were moved out of inner classes to become independent classes to avoid issues with obfuscation and compression.

    If your code references the following enums, ensure you update your import statements to use the correct package names:

    • PrimaryKey.AssignType
    • Mapping.Relation
    • Conflict.Strategy
  9. Use QueryBuilder for complex queries

    master

    For advanced filtering, use QueryBuilder. It allows you to chain conditions like where, whereAppendAnd, limit, distinct, and order.

    Example of a complex query with multiple conditions and limits:

    List<Book> books = liteOrm.query(new QueryBuilder<Book>(Book.class)
            .columns(new String[]{"id", "author", Book.COL_INDEX})
            .distinct(true)
            .whereGreaterThan("id", 0)
            .whereAppendAnd()
            .whereLessThan("id", 10000)
            .limit(6, 9)
            .appendOrderAscBy(Book.COL_INDEX));
  10. Use WhereBuilder for deletions

    master

    You can delete records matching specific criteria using WhereBuilder.

    liteOrm.delete(new WhereBuilder(Student.class)
            .where(Person.COL_NAME + " LIKE ?", new String[]{"%1%"})
            .and()
            .greaterThan("id", 0)
            .and()
            .lessThan("id", 10000));
  11. Define models using LiteOrm annotations

    master

    LiteOrm uses annotations to map Java classes to SQLite tables. You can define table names, primary keys, non-null constraints, and column names. It also supports ignoring specific fields so they are not persisted.

    Key annotations:

    • @Table(name): Specifies the database table name.
    • @PrimaryKey(AssignType): Marks a field as the primary key. Use AssignType.AUTO_INCREMENT for auto-incrementing IDs.
    • @NotNull: Ensures the column is NOT NULL.
    • @Ignore: Prevents the field from being stored in the database.
    • @Column(name): Specifies a custom column name.
    • @Default(value): Sets a default value for the column.
    @Table("test_model")
    public class TestModel {
    
        // 指定自增,每个对象需要有一个主键
        @PrimaryKey(AssignType.AUTO_INCREMENT)
        private int id;
    
        // 非空字段
        @NotNull
        private String name;
    
        //忽略字段,将不存储到数据库
        @Ignore
        private String password;
    
        @Default("true")
        @Column("login")
        private Boolean isLogin;
    }
  12. Core API Capabilities of LiteOrm

    master

    LiteOrm provides a streamlined API for common database operations. The framework emphasizes a minimalist syntax to reduce boilerplate code.

    Common Operations:

    • db.save(object): Persists an object (supports replace logic).
    • db.insert(object): Inserts a new record.
    • db.update(object): Updates an existing record.
    • db.delete(object): Deletes a record.
    • db.query(Class): Queries the database for entities of a specific class.
    • db.deleteAll(Class): Deletes all records of a specific type.

    Advanced Features:

    • Flexible Querying: Supports columns, where, order, limit, having, and group clauses.
    • Constraint Support: Supports SQL constraints such as NOT NULL, UNIQUE, DEFAULT, COLLATE, CHECK, and PRIMARY KEY, including conflict resolution algorithms.
    • Relationship Modes: Supports both Independent operations (high performance, saves only the object itself) and Cascading operations (saves the object along with its associated related objects).