### Complete Transaction Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Database.md Example demonstrating how to perform database transactions atomically. ```APIDOC ## Complete Transaction Example ```java Database db = daoSession.getDatabase(); db.beginTransaction(); try { // Execute multiple operations atomically DatabaseStatement insertStmt = db.compileStatement( "INSERT INTO orders (user_id, amount) VALUES (?, ?)" ); insertStmt.bindLong(1, 100); insertStmt.bindDouble(2, 99.99); insertStmt.executeInsert(); insertStmt.clearBindings(); insertStmt.bindLong(1, 101); insertStmt.bindDouble(2, 149.99); insertStmt.executeInsert(); // Mark transaction successful only if no exceptions db.setTransactionSuccessful(); } finally { // Always end transaction db.endTransaction(); } ``` ``` -------------------------------- ### Raw SQL Query Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Demonstrates how to use the Database instance to execute a raw SQL query. ```java DaoMaster daoMaster = new DaoMaster(database); Database db = daoMaster.getDatabase(); Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM users", null); ``` -------------------------------- ### Standard SQLite Database Initialization Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Example of initializing a standard SQLite database using DaoMaster.DevOpenHelper. ```java // 1. Create database helper DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper( context, "myapp-db", // Database filename null // No factory ); // 2. Get writable database SQLiteDatabase sqliteDb = helper.getWritableDatabase(); // 3. Create Database wrapper Database database = new StandardDatabase(sqliteDb); // 4. Create DaoMaster DaoMaster daoMaster = new DaoMaster(database); // 5. Create sessions as needed DaoSession session1 = daoMaster.newSession(); DaoSession session2 = daoMaster.newSession(IdentityScopeType.Session); ``` -------------------------------- ### Standard SQLite Database Initialization Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Example demonstrating how to initialize DaoMaster with a standard SQLite database. ```APIDOC ## Standard SQLite Database ### Description Initializes DaoMaster with a standard SQLite database. ### Steps 1. Create database helper using `DaoMaster.DevOpenHelper`. 2. Get a writable `SQLiteDatabase` instance. 3. Create a `Database` wrapper using `StandardDatabase`. 4. Instantiate `DaoMaster` with the `Database` object. 5. Create `DaoSession` objects as needed. ``` -------------------------------- ### Complete GreenDao Usage Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDaoSession.md Demonstrates initialization, insertion, querying, asynchronous operations, direct DAO usage, and cleanup. ```java // Initialize (typically done once at app startup) DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "mydb"); DaoMaster daoMaster = new DaoMaster(helper.getWritableDatabase()); DaoSession daoSession = daoMaster.newSession(); // Insert using session User user = new User(); user.setName("Alice"); daoSession.insert(user); // Query using session List users = daoSession.queryBuilder(User.class) .where(Properties.Active.eq(true)) .list(); // Async operations AsyncSession asyncSession = daoSession.startAsyncSession(); asyncSession.insert(newUser); asyncSession.waitForCompletion(); // Or use DAO directly for efficiency UserDao userDao = daoSession.getUserDao(); User loaded = userDao.load(user.getId()); // Cleanup daoSession.clear(); daoSession.getDatabase().close(); ``` -------------------------------- ### Encrypted SQLCipher Database Initialization Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Example demonstrating how to initialize DaoMaster with an encrypted SQLCipher database. ```APIDOC ## Encrypted SQLCipher Database ### Description Initializes DaoMaster with an encrypted SQLCipher database. ### Steps 1. Create an encrypted database using `SqlCipherEncryptedHelper.createEncryptedDatabase`. 2. Instantiate `DaoMaster` with the encrypted `Database` object. 3. Create `DaoSession` objects. ``` -------------------------------- ### Build and Execute a Complex Query Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Example demonstrating how to construct a query with multiple conditions, joins, ordering, and limits. ```java // Find active users named "John" in descending order by score, limit to 10 List users = userDao.queryBuilder() .where( Properties.FirstName.eq("John"), Properties.Active.eq(true) ) .join(Account.class, AccountDao.Properties.UserId) .where(AccountDao.Properties.Verified.eq(true)) .orderDesc(Properties.Score) .limit(10) .list(); ``` -------------------------------- ### Encrypted SQLCipher Database Initialization Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Example of initializing an encrypted SQLCipher database using DaoMaster. ```java // 1. Create encrypted database helper Database encryptedDb = SqlCipherEncryptedHelper.createEncryptedDatabase( context, "myapp-db", "password123" // Encryption password ); // 2. Create DaoMaster with encrypted database DaoMaster daoMaster = new DaoMaster(encryptedDb); // 3. Create sessions DaoSession session = daoMaster.newSession(); ``` -------------------------------- ### One-to-Many Join Setup Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Join.md Defines the User and Order entities with a one-to-many relationship using @ToOne and joinProperty. ```java package de.greenrobot.dao.example; import de.greenrobot.dao.annotation.Entity; import de.greenrobot.dao.annotation.Id; import de.greenrobot.dao.annotation.ToOne; @Entity public class User { @Id private Long id; } @Entity public class Order { @Id private Long id; private Long userId; @ToOne(joinProperty = "userId") private User user; } ``` -------------------------------- ### Three-Table Join Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Join.md Demonstrates joining LineItem with Order and Product entities, applying conditions on both joined tables. ```java @Entity public class LineItem { @Id private Long id; private Long orderId; private Long productId; @ToOne(joinProperty = "orderId") private Order order; @ToOne(joinProperty = "productId") private Product product; } List items = lineItemDao.queryBuilder() .join(Order.class, OrderDao.Properties.LineItemId) .where(OrderDao.Properties.Status.eq("shipped")) .join(Product.class, ProductDao.Properties.LineItemId) .where(ProductDao.Properties.Category.eq("Electronics")) .list(); ``` -------------------------------- ### RxJava Example with Scheduler Switching Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Demonstrates using `rx()` to load all users and subscribe on the IO scheduler, observing on the Android main thread for UI updates. ```java userDao.rx() .loadAll() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(users -> { // Update UI with users }); ``` -------------------------------- ### AsyncSession Usage Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Demonstrates how to use AsyncSession to queue multiple database operations, set up listeners for main thread callbacks, and wait for completion. ```APIDOC ## Complete Example ```java AsyncSession asyncSession = daoSession.startAsyncSession(); // Set up listener for main thread callbacks asyncSession.setListenerMainThread(new AsyncOperationListener() { @Override public void onAsyncOperationCompleted(AsyncOperation operation) { if (operation.getException() != null) { Log.e("AsyncDB", "Operation failed", operation.getException()); } else { // Update UI refreshUserList(); } } }); // Queue multiple inserts (returns immediately) for (User user : newUsers) { asyncSession.insert(user); } // Check if done if (asyncSession.isCompleted()) { Log.d("AsyncDB", "All done!"); } else { Log.d("AsyncDB", "Still processing..."); } // Wait for completion (blocks) try { boolean completed = asyncSession.waitForCompletion(5000); if (completed) { Log.d("AsyncDB", "All operations completed"); } else { Log.d("AsyncDB", "Timeout waiting for operations"); } } catch (Exception e) { Log.e("AsyncDB", "Error during async operations", e); } ``` ``` -------------------------------- ### Custom OpenHelper for Database Migrations Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Example of a custom OpenHelper class to manage database schema migrations in production environments. Implement `onUpgrade` to handle version changes. ```java public class MyOpenHelper extends DaoMaster.OpenHelper { @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 2) { db.execSQL("ALTER TABLE users ADD COLUMN email TEXT"); } if (oldVersion < 3) { db.execSQL("CREATE TABLE orders (...)"); } } } ``` -------------------------------- ### Custom OpenHelper for Production Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Implement a custom OpenHelper for production environments to define specific migration strategies for database upgrades. This example shows how to add a column and create a new table. ```java public class MyOpenHelper extends DaoMaster.OpenHelper { public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) { super(context, name, factory); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d("Upgrade", "Upgrading from " + oldVersion + " to " + newVersion); if (oldVersion == 1 && newVersion == 2) { // Add new column to users table db.execSQL("ALTER TABLE users ADD COLUMN phone TEXT"); } if (oldVersion <= 2 && newVersion >= 3) { // Create new table db.execSQL("CREATE TABLE orders (id INTEGER PRIMARY KEY, ...)"); } } @Override public void onCreate(SQLiteDatabase db) { super.onCreate(db); // Additional initialization if needed } } ``` ```java MyOpenHelper helper = new MyOpenHelper(context, "db.sqlite3", null); DaoMaster daoMaster = new DaoMaster(new StandardDatabase(helper.getWritableDatabase())); ``` -------------------------------- ### Complete AsyncSession Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Demonstrates how to use AsyncSession for performing multiple database inserts asynchronously. It includes setting up a listener for main thread callbacks, queuing operations, checking for completion, and waiting for operations to finish with a timeout. ```java AsyncSession asyncSession = daoSession.startAsyncSession(); // Set up listener for main thread callbacks asyncSession.setListenerMainThread(new AsyncOperationListener() { @Override public void onAsyncOperationCompleted(AsyncOperation operation) { if (operation.getException() != null) { Log.e("AsyncDB", "Operation failed", operation.getException()); } else { // Update UI refreshUserList(); } } }); // Queue multiple inserts (returns immediately) for (User user : newUsers) { asyncSession.insert(user); } // Check if done if (asyncSession.isCompleted()) { Log.d("AsyncDB", "All done!"); } else { Log.d("AsyncDB", "Still processing..."); } // Wait for completion (blocks) try { boolean completed = asyncSession.waitForCompletion(5000); if (completed) { Log.d("AsyncDB", "All operations completed"); } else { Log.d("AsyncDB", "Timeout waiting for operations"); } } catch (Exception e) { Log.e("AsyncDB", "Error during async operations", e); } ``` -------------------------------- ### Join Query Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Illustrates how to perform a cross-table query using the QueryBuilder's join functionality, specifying conditions on related entities. ```java List orders = orderDao.queryBuilder() .join(Customer.class, CustomerDao.Properties.OrderId) .where(CustomerDao.Properties.Status.eq("active")) .list(); ``` -------------------------------- ### Create AsyncSession Instance Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Obtain an AsyncSession instance from your DaoSession to start performing asynchronous database operations. This is typically accessed via the startAsyncSession() method. ```java AsyncSession asyncSession = daoSession.startAsyncSession(); ``` -------------------------------- ### Create a QueryBuilder Instance Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Instantiate a QueryBuilder using the queryBuilder() method from an AbstractDao or AbstractDaoSession. This is the starting point for building custom queries. ```java QueryBuilder qb = userDao.queryBuilder(); ``` -------------------------------- ### Example: Custom Queryable Operation Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Demonstrates using queryable to perform a custom database operation, such as counting active entities, within a background thread. ```java asyncSession.queryable(() -> { int count = userDao.queryBuilder() .where(Properties.Active.eq(true)) .buildCount() .count(); return count; }); ``` -------------------------------- ### Complete Transaction Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Database.md Demonstrates how to execute multiple database operations atomically within a transaction. Ensure to mark the transaction as successful and always end the transaction in a finally block. ```java Database db = daoSession.getDatabase(); db.beginTransaction(); try { // Execute multiple operations atomically DatabaseStatement insertStmt = db.compileStatement( "INSERT INTO orders (user_id, amount) VALUES (?, ?)" ); insertStmt.bindLong(1, 100); insertStmt.bindDouble(2, 99.99); insertStmt.executeInsert(); insertStmt.clearBindings(); insertStmt.bindLong(1, 101); insertStmt.bindDouble(2, 149.99); insertStmt.executeInsert(); // Mark transaction successful only if no exceptions db.setTransactionSuccessful(); } finally { // Always end transaction db.endTransaction(); } ``` -------------------------------- ### Get Database Instance Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDaoSession.md Retrieves the Database abstraction used by this session. This can be used for lower-level database operations if needed. ```java public Database getDatabase() ``` -------------------------------- ### Creating a Basic Join Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Join.md Demonstrates how to create a basic join between two entities using QueryBuilder. This is the starting point for building more complex queries involving related tables. ```java Join join = orderQueryBuilder .join(Customer.class, CustomerDao.Properties.OrderId); ``` -------------------------------- ### Get Properties Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Retrieves an array of Property objects describing all entity properties. ```java public Property[] getProperties() ``` -------------------------------- ### Complete Order Entity Annotation Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/configuration.md Defines an Order entity with annotations for its primary key, foreign key relationship to User, and properties like amount and date. ```java @Entity(active = true, nameInDb = "orders") public class Order { @Id(autoincrement = true) private Long id; private Long userId; // Foreign key @ToOne(joinProperty = "userId") private User user; @NotNull private BigDecimal amount; @Property(nameInDb = "order_date") private long date; } ``` -------------------------------- ### Start Asynchronous Session Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDaoSession.md Creates an AsyncSession for non-blocking database operations. Operations enqueued to an AsyncSession return immediately and execute in a background thread. ```java public AsyncSession startAsyncSession() ``` ```java AsyncSession asyncSession = daoSession.startAsyncSession(); asyncSession.insert(user); asyncSession.waitForCompletion(); // Optional: wait for completion ``` -------------------------------- ### Execute Query and Get All Results as List Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Use the `list()` method to execute a query and retrieve all matching entities as a Java List. Returns an empty list if no entities match the query criteria. ```java public List list() ``` ```java List activeUsers = userDao.queryBuilder() .where(Properties.Active.eq(true)) .list(); ``` -------------------------------- ### Query with Joins Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Retrieve related data by joining entities. This example finds orders associated with customers named 'Acme', ordered by amount and limited to 20 results. ```java // Find orders from customers named "Acme" List orders = orderDao.queryBuilder() .join(Customer.class, CustomerDao.Properties.OrderId) .where(CustomerDao.Properties.Name.eq("Acme")) .orderDesc(Properties.Amount) .limit(20) .list(); ``` -------------------------------- ### Identity Scope Caching Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Demonstrates how GreenDao's identity scope ensures that loading the same entity multiple times returns the identical Java object instance, maintaining cache consistency. ```java User user1 = userDao.load(1L); User user2 = userDao.load(1L); assert user1 == user2; // Same object instance ``` -------------------------------- ### Identity Scope Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDaoSession.md Demonstrates the behavior of the identity scope (session cache). Loading the same entity twice returns the same object instance, but clearing the cache results in different instances. ```java User user1 = userDao.load(1L); User user2 = userDao.load(1L); assert user1 == user2; // Same object instance, not just equal // Clear cache daoSession.clear(); User user3 = userDao.load(1L); assert user1 != user3; // Different instance after cache clear ``` -------------------------------- ### Complete User Entity Annotation Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/configuration.md Defines a User entity with various GreenDao annotations for database persistence, including primary keys, unique indexes, foreign keys, and custom type conversions. ```java @Entity(active = true, nameInDb = "users") public class User { @Id(autoincrement = true) private Long id; @NotNull @Property(nameInDb = "first_name") private String firstName; @NotNull @Index(unique = true) private String email; @Property(nameInDb = "created_at") @Convert(converter = DateConverter.class, columnType = Long.class) private Date createdAt; private int age; // No annotation = default persistent property @Transient private String tempData; // Not persisted @ToMany(referencedJoinProperty = "userId") private List orders; } ``` -------------------------------- ### Get RxJava Transaction Wrappers Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDaoSession.md Returns RxJava wrappers for transaction operations. Use rx() for operations on the IO scheduler, or rxPlain() for operations without a specific scheduler. ```java public RxTransaction rx() ``` ```java public RxTransaction rxPlain() ``` -------------------------------- ### Initialize greenDAO Database Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Set up the database helper and create a DaoMaster and DaoSession. Requires a context and a database name. ```java // Create database helper DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "mydb"); // Get database and create DaoMaster SQLiteDatabase db = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(new StandardDatabase(db)); // Create DaoSession DaoSession daoSession = daoMaster.newSession(); ``` -------------------------------- ### Get Lazy List Bypassing Cache Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Use `listLazyUncached()` to get a `LazyList` that bypasses the identity scope cache, ensuring fresh copies of entities are loaded directly from the database. ```java public LazyList listLazyUncached() ``` -------------------------------- ### Get Parent DaoSession Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Retrieves the parent DaoSession managing this DAO. ```java public AbstractDaoSession getSession() ``` -------------------------------- ### Get Primary Key Property Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Retrieves the Property object for the primary key. ```java public Property getPkProperty() ``` -------------------------------- ### Get Schema Version Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Retrieves the schema version of the database for migration tracking. ```java public int getSchemaVersion() ``` -------------------------------- ### Get Table Name Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Retrieves the name of the database table associated with this entity type. ```java public String getTablename() ``` -------------------------------- ### Typical DaoMaster and DaoSession Usage Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/configuration.md Illustrates the typical workflow for creating a GreenDao database, master, session, and accessing DAOs. ```java // Create database helper SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, "mydb").getWritableDatabase(); // Create master and session DaoMaster daoMaster = new DaoMaster(new StandardDatabase(db)); DaoSession daoSession = daoMaster.newSession(IdentityScopeType.Session); // Use DAOs UserDao userDao = daoSession.getUserDao(); ``` -------------------------------- ### Get Column Names Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Retrieves arrays of column names: all, primary key only, or non-primary key. ```java public String[] getAllColumns() public String[] getPkColumns() public String[] getNonPkColumns() ``` -------------------------------- ### DevOpenHelper for Development Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md The nested DevOpenHelper class simplifies database creation and upgrades during development by automatically creating tables and dropping/recreating them on schema version changes. Use this only for development or testing. ```java public static class DevOpenHelper extends DaoMaster.OpenHelper { public DevOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory); } ``` ```java DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "db.sqlite3", null); SQLiteDatabase db = helper.getWritableDatabase(); ``` -------------------------------- ### Get Merge Wait Time - getWaitForMergeMillis() Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Retrieve the current merge wait time in milliseconds using `getWaitForMergeMillis()`. ```java public int getWaitForMergeMillis() ``` -------------------------------- ### Get Main Thread Listener Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Retrieves the currently set listener for main thread operation completion events. ```java public AsyncOperationListener getListenerMainThread() ``` -------------------------------- ### AsyncSession Best Practices Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Provides recommendations for using AsyncSession effectively, focusing on thread safety, listener usage, error handling, and managing operation waiting. ```APIDOC ## Best Practices 1. **UI Thread Safety:** Always call from any thread; results are thread-safe 2. **Listeners:** Use main thread listener (`setListenerMainThread`) for UI updates 3. **Error Handling:** Check `getException()` on completed operations 4. **Waiting:** Use `waitForCompletion()` for critical sections, but avoid blocking UI thread 5. **Multiple Sessions:** You can start multiple AsyncSessions for concurrent execution ``` -------------------------------- ### Get Background Thread Listener Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Retrieves the currently set listener for background thread operation completion events. ```java public AsyncOperationListener getListener() ``` -------------------------------- ### AbstractDao Constructor with DaoConfig Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Creates a new DAO instance with the given configuration. The configuration object contains essential details like the database connection, entity metadata, and SQL statements required for DAO operations. ```APIDOC ## AbstractDao(DaoConfig config) ### Description Creates a new DAO instance with the given configuration. ### Method `public AbstractDao(DaoConfig config)` ### Parameters #### Path Parameters - **config** (DaoConfig) - Required - Configuration object containing database, entity metadata, and statements ### Throws - `NullPointerException` if config is null ``` -------------------------------- ### Get Max Operations to Merge - getMaxOperationCountToMerge() Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AsyncSession.md Retrieve the current maximum number of operations configured for merging or batching using `getMaxOperationCountToMerge()`. ```java public int getMaxOperationCountToMerge() ``` -------------------------------- ### Apply greenDAO Plugin and Add Library Source: https://github.com/greenrobot/greendao/blob/master/README.md Configure your app's build.gradle file to apply the greenDAO plugin and include the greenDAO library dependency. ```groovy apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao' // apply plugin dependencies { implementation 'org.greenrobot:greendao:3.3.0' // add library } ``` -------------------------------- ### Get Raw Statement Object Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Database.md Retrieves the underlying SQLiteStatement or its equivalent. This allows for direct interaction with the native statement object if needed. ```java Object getRawStatement() ``` -------------------------------- ### AbstractDao Constructor with DaoConfig Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Use this constructor to create a new DAO instance with the provided configuration. Ensure the DaoConfig is not null. ```java public AbstractDao(DaoConfig config) ``` -------------------------------- ### startAsyncSession Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDaoSession.md Creates an AsyncSession for non-blocking database operations. Operations enqueued to an AsyncSession return immediately and execute in a background thread. ```APIDOC ## startAsyncSession() ### Description Creates an AsyncSession for non-blocking database operations. Operations enqueued to an AsyncSession return immediately and execute in a background thread. ### Method ```java public AsyncSession startAsyncSession() ``` ### Returns AsyncSession instance ### Example ```java AsyncSession asyncSession = daoSession.startAsyncSession(); asyncSession.insert(user); asyncSession.waitForCompletion(); // Optional: wait for completion ``` ``` -------------------------------- ### Database Locked Exception Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/errors.md Illustrates a scenario where two threads attempting to write to the database simultaneously can cause a DaoException due to the database being locked. ```java // Thread 1 userDao.insert(user1); // Thread 2 simultaneously userDao.insert(user2); // Possible DaoException: database locked ``` -------------------------------- ### Query Builder Usage Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Illustrates type-safe query construction using Property constants for filtering, ordering, and limiting results. Requires importing Property constants. ```java List users = userDao.queryBuilder() .where( Properties.Active.eq(true), Properties.CreatedAt.gt(cutoffDate) ) .orderDesc(Properties.Score) .limit(10) .list(); ``` -------------------------------- ### Add greenDAO Gradle Plugin Source: https://github.com/greenrobot/greendao/blob/master/README.md Configure your root build.gradle file to include the greenDAO Gradle plugin and necessary repositories. ```groovy buildscript { repositories { jcenter() mavenCentral() // add repository } dependencies { classpath 'com.android.tools.build:gradle:' classpath 'org.greenrobot:greendao-gradle-plugin:3.3.1' // add plugin } } ``` -------------------------------- ### Generated Properties Inner Class Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Property.md This is an example of the `Properties` inner class generated by GreenDao for a `UserDao`. It contains static final `Property` objects for each entity field. ```java // Generated in UserDao public static class Properties { public static final Property Id = new Property(...); public static final Property FirstName = new Property(...); public static final Property LastName = new Property(...); public static final Property Email = new Property(...); public static final Property Status = new Property(...); } // Usage List users = userDao.queryBuilder() .where(Properties.FirstName.eq("John")) .list(); ``` -------------------------------- ### Production Schema Management with Safe Migrations Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Extend DaoMaster.OpenHelper to manage database schema upgrades in production environments. Implement safe migration strategies, avoiding table drops and handling version changes incrementally. ```java public class ProductionOpenHelper extends DaoMaster.OpenHelper { private static final int SCHEMA_VERSION = 3; public ProductionOpenHelper(Context context) { super(context, "myapp.db", null); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Implement safe migrations // Never drop tables in production switch (oldVersion) { case 1: // Migration from v1 to v2 db.execSQL("ALTER TABLE users ADD COLUMN email TEXT"); // Falls through to next migration case 2: // Migration from v2 to v3 db.execSQL("CREATE TABLE orders (...)"); } } } ``` -------------------------------- ### Custom PropertyConverter Failure Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/errors.md Demonstrates a bug in a custom PropertyConverter that returns null for a non-null Date, leading to a DaoException. This snippet shows the incorrect implementation. ```java public class DateConverter implements PropertyConverter { @Override public Long convertToDatabaseValue(Date value) { return null; // Bug: returns null for non-null Date } } @Entity public class Order { @Convert(converter = DateConverter.class, columnType = Long.class) private Date createdAt; } Order order = new Order(); order.setCreatedAt(new Date()); orderDao.insert(order); // DaoException due to null conversion ``` -------------------------------- ### Get Raw Database Object Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Database.md Retrieves the underlying SQLiteDatabase or SQLCipherDatabase object. Use this when you need to access database features not exposed by the GreenDao Database interface. ```java Object getRawDatabase() ``` ```java Database db = daoSession.getDatabase(); SQLiteDatabase rawDb = (SQLiteDatabase) db.getRawDatabase(); // Use raw SQLite features directly boolean isReadOnly = rawDb.isReadOnly(); ``` -------------------------------- ### Creating a QueryBuilder Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md QueryBuilders are not instantiated directly. Obtain an instance using `AbstractDao.queryBuilder()` or `AbstractDaoSession.queryBuilder(Class)`. ```APIDOC ## Creating a QueryBuilder QueryBuilders are not instantiated directly; use `AbstractDao.queryBuilder()` or `AbstractDaoSession.queryBuilder(Class)`: ```java QueryBuilder qb = userDao.queryBuilder(); ``` ``` -------------------------------- ### AbstractDao Constructor with DaoConfig and AbstractDaoSession Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Creates a new DAO instance with both configuration and a parent session. The parent session is utilized for managing the identity scope and transactions, providing a centralized control mechanism for related DAOs. ```APIDOC ## AbstractDao(DaoConfig config, AbstractDaoSession daoSession) ### Description Creates a new DAO instance with configuration and parent session. ### Method `public AbstractDao(DaoConfig config, AbstractDaoSession daoSession)` ### Parameters #### Path Parameters - **config** (DaoConfig) - Required - DAO configuration - **daoSession** (AbstractDaoSession) - Optional - Parent session managing this DAO; used for identity scope and transaction management ``` -------------------------------- ### Constructor Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDaoSession.md Creates a new DaoSession instance. This is typically called by the generated DaoMaster. ```APIDOC ## AbstractDaoSession(Database db) ### Description Creates a new DaoSession instance (typically called by generated DaoMaster). ### Parameters #### Path Parameters - **db** (Database) - Required - Database abstraction instance ``` -------------------------------- ### getDatabase() Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Provides access to the Database instance, allowing for raw SQL operations. ```APIDOC ## getDatabase() ### Description Returns the Database instance for raw SQL operations. ### Returns The Database abstraction ### Example ```java DaoMaster daoMaster = new DaoMaster(database); Database db = daoMaster.getDatabase(); Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM users", null); ``` ``` -------------------------------- ### Iterate Over Results with Resource Management Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Use `listIterator()` to get a `CloseableListIterator` for iterating over query results. It's crucial to close the iterator after use to release database resources. ```java public CloseableListIterator listIterator() ``` ```java try (CloseableListIterator iter = userDao.queryBuilder().listIterator()) { while (iter.hasNext()) { User user = iter.next(); // Process user } } ``` -------------------------------- ### AbstractDao Constructor with DaoConfig and DaoSession Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Use this constructor to create a new DAO instance with configuration and a parent session. The parent session is used for identity scope and transaction management. ```java public AbstractDao(DaoConfig config, AbstractDaoSession daoSession) ``` -------------------------------- ### DaoException Constructors Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/errors.md Illustrates the different ways to construct a DaoException, including with and without messages or causes. ```java public DaoException() public DaoException(String error) public DaoException(String error, Throwable cause) public DaoException(Throwable th) ``` -------------------------------- ### Order with Raw SQL Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Orders results using a raw SQL ORDER BY clause. ```java public QueryBuilder orderRaw(String rawOrder) ``` -------------------------------- ### loadAll() Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Loads all entities of this type from the database. Returns a list of all entities, or an empty list if none exist. ```APIDOC ## loadAll() ### Description Loads all entities of this type from the database. ### Method loadAll ### Response #### Success Response - **List** - List of all entities; empty list if no entities exist ### Example ```java List allUsers = userDao.loadAll(); ``` ``` -------------------------------- ### Creating DaoSession with IdentityScopeType Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/configuration.md Demonstrates how to create a DaoSession with different caching behaviors using IdentityScopeType. ```java DaoMaster daoMaster = new DaoMaster(db); // Session cache enabled (default) DaoSession session1 = daoMaster.newSession(); // Or explicitly DaoSession session2 = daoMaster.newSession(IdentityScopeType.Session); // No cache DaoSession session3 = daoMaster.newSession(IdentityScopeType.None); ``` -------------------------------- ### Null Entity Parameter Exception Example Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/errors.md Demonstrates the error that occurs when passing a null entity object to GreenDao's insert, update, or delete methods, which can result in a DaoException or NullPointerException. ```java userDao.insert(null); // DaoException or NPE ``` -------------------------------- ### Get Lazy-Loading List for Large Result Sets Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Use `listLazy()` to obtain a `LazyList` which loads entities from the database on-demand as they are accessed. This is beneficial for handling large result sets efficiently. ```java public LazyList listLazy() ``` -------------------------------- ### Build OR Conditions Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Property.md Use this to retrieve entities that satisfy at least one of the specified conditions. ```java List users = userDao.queryBuilder() .whereOr( Properties.Status.eq("admin"), Properties.Status.eq("moderator") ) .list(); ``` -------------------------------- ### Load All Entities Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Fetches all entities of a specific type from the database. Returns an empty list if no entities exist. ```java public List loadAll() ``` ```java List allUsers = userDao.loadAll(); ``` -------------------------------- ### build() Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Builds a reusable Query object that can be executed multiple times with the same conditions, optimizing repeated query execution. ```APIDOC ## build() ### Description Builds a reusable Query object for repeated execution. ### Method ```java public Query build() ``` ### Returns A Query that can be executed multiple times with the same WHERE conditions ``` -------------------------------- ### Execute Query and Get a Unique Result or Throw Exception Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Use the `uniqueOrThrow()` method to execute a query that must return exactly one result. If zero or more than one result is found, it throws a `DaoException`. ```java public T uniqueOrThrow() ``` -------------------------------- ### buildCursor() Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Builds a query that returns raw cursor results, designed for memory-efficient iteration over large datasets. ```APIDOC ## buildCursor() ### Description Builds a query returning raw cursor results for memory-efficient iteration over large datasets. ### Method ```java public CursorQuery buildCursor() ``` ### Returns A CursorQuery ``` -------------------------------- ### Execute Query and Get a Unique Result Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Use the `unique()` method to execute a query that is expected to return at most one result. If zero results are found, it returns null. If more than one result is found, it throws a `DaoException`. ```java public T unique() ``` -------------------------------- ### Execute Database Operations within a Transaction Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Database.md Starts a database transaction, executes operations, and ensures atomicity by committing or rolling back changes. Use this to group multiple database operations that should succeed or fail together. ```java Database db = daoSession.getDatabase(); if (!db.inTransaction()) { db.beginTransaction(); try { userDao.insert(user1); userDao.insert(user2); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } ``` -------------------------------- ### newSession() Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Creates a new DaoSession with default configuration (Session-level identity scope enabled). ```APIDOC ## newSession() ### Description Creates a new DaoSession with default caching behavior (session cache enabled). ### Method `public abstract AbstractDaoSession newSession()` ### Returns A new DaoSession instance ### Example ```java DaoMaster daoMaster = new DaoMaster(database); DaoSession session = daoMaster.newSession(); UserDao userDao = session.getUserDao(); ``` ``` -------------------------------- ### Chain Multiple Joins Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Join.md Chain multiple `join` calls to query across several entity relationships. Each `join` can have its own `where` clause to filter results at each level of the relationship. This example demonstrates joining an Order to Customer and then to Item, filtering each step. ```java List orders = orderDao.queryBuilder() .join(Customer.class, CustomerDao.Properties.OrderId) .where(CustomerDao.Properties.Status.eq("premium")) .join(Item.class, ItemDao.Properties.OrderId) .where(ItemDao.Properties.Price.gt(100.0)) .orderDesc(Properties.CreatedAt) .list(); ``` -------------------------------- ### RxJava Integration Methods for AbstractDao Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Provides RxJava wrappers for DAO operations. `rx()` uses the IO scheduler, while `rxPlain()` avoids scheduler switching. ```java public RxDao rx() public RxDao rxPlain() ``` -------------------------------- ### RxJava Query Wrappers Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Obtain RxJava Observable wrappers for queries. `rx()` uses the IO scheduler, while `rxPlain()` does not. ```java public RxQuery rx() public RxQuery rxPlain() ``` -------------------------------- ### list() Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Executes the query and returns all results as a List. Useful for retrieving all matching entities. ```APIDOC ## list() ### Description Executes the query and returns all results as a List. Useful for retrieving all matching entities. ### Method ```java public List list() ``` ### Returns List of entities (empty list if no matches) ### Example ```java List activeUsers = userDao.queryBuilder() .where(Properties.Active.eq(true)) .list(); ``` ``` -------------------------------- ### Debugging Join Queries with SQL Logging Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Join.md Enable SQL and value logging to inspect the generated JOIN queries and their parameters. This is useful for understanding how GreenDao translates your query builder operations into SQL. ```java QueryBuilder.LOG_SQL = true; QueryBuilder.LOG_VALUES = true; List orders = orderDao.queryBuilder() .join(Customer.class, CustomerDao.Properties.OrderId) .where(CustomerDao.Properties.Name.like("%Corp%")) .list(); // Logs something like: // SELECT T.* FROM orders T JOIN customers C ON T.customer_id = C.id // WHERE C.name LIKE ? ORDER BY ... // Parameter: %Corp% ``` -------------------------------- ### Insert and Query Data Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Perform basic CRUD operations like inserting a user and querying users by name pattern, ordering by email. Also shows how to retrieve a unique record by email. ```java // Get DAO UserDao userDao = daoSession.getUserDao(); // Insert User user = new User(); user.setEmail("john@example.com"); user.setName("John"); userDao.insert(user); // Query with conditions List results = userDao.queryBuilder() .where(Properties.Name.like("John%")) .orderAsc(Properties.Email) .list(); // Unique result User specific = userDao.queryBuilder() .where(Properties.Email.eq("john@example.com")) .build() .unique(); ``` -------------------------------- ### R8/ProGuard Rules for greenDAO Source: https://github.com/greenrobot/greendao/blob/master/README.md Add these rules to your R8 or ProGuard configuration to ensure proper class member retention. ```bash -keepclassmembers class * extends org.greenrobot.greendao.AbstractDao { public static java.lang.String TABLENAME; } -keep class **$Properties { *; } # If you DO use SQLCipher: -keep class org.greenrobot.greendao.database.SqlCipherEncryptedHelper { *; } # If you do NOT use SQLCipher: -dontwarn net.sqlcipher.database.** # If you do NOT use RxJava: -dontwarn rx.** ``` -------------------------------- ### StandardDatabase Implementation Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Database.md Wrapper around SQLiteDatabase for unencrypted databases. Instantiate with a SQLiteDatabase delegate. ```java public class StandardDatabase implements Database { public StandardDatabase(SQLiteDatabase delegate); // Implements Database interface } ``` ```java SQLiteDatabase sqliteDb = helper.getWritableDatabase(); Database db = new StandardDatabase(sqliteDb); DaoMaster daoMaster = new DaoMaster(db); ``` -------------------------------- ### R8/ProGuard Configuration for GreenDao Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Essential rules to include in your R8 or ProGuard configuration to ensure GreenDao classes are not stripped or obfuscated. ```proguard -keepclassmembers class * extends org.greenrobot.greendao.AbstractDao { public static java.lang.String TABLENAME; } -keep class **$Properties { *; } -keep class org.greenrobot.greendao.database.SqlCipherEncryptedHelper { *; } -dontwarn net.sqlcipher.database.** -dontwarn rx.** ``` -------------------------------- ### RxJava Integration Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Provides RxJava wrappers for DAO operations, allowing for reactive programming patterns. `rx()` operates on the IO scheduler, while `rxPlain()` avoids scheduler switching. ```APIDOC ## `rx()` / `rxPlain()` ### Description Returns an RxJava wrapper for this DAO. `rx()` operates on the IO scheduler, while `rxPlain()` operates without scheduler switching. ### Method Signature ```java public RxDao rx() public RxDao rxPlain() ``` ### Returns RxDao instance for reactive operations. ### Example ```java userDao.rx() .loadAll() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(users -> { // Update UI with users }); ``` ``` -------------------------------- ### load(K key) Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Loads an entity from the database using its primary key. Returns the entity if found, otherwise null. Throws DaoException if multiple rows match the key. ```APIDOC ## load(K key) ### Description Loads the entity with the given primary key from the database. ### Method load ### Parameters #### Path Parameters - **key** (K) - Optional - Primary key value; may be null ### Response #### Success Response - **T** - The entity or null if no entity matches the given key ### Throws - **DaoException** - if multiple rows match the key (should not happen with valid PKs) ### Example ```java User user = userDao.load(123L); if (user != null) { // Entity loaded successfully } ``` ``` -------------------------------- ### join(Join sourceJoin, Property sourceProperty, Class destinationEntityClass, Property destinationProperty) Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Creates a chained join from an existing join, enabling multi-table queries by linking subsequent entities based on previously established joins. ```APIDOC ## join(Join sourceJoin, Property sourceProperty, Class destinationEntityClass, Property destinationProperty) ### Description Creates a chained join from an existing join. Allows multi-table queries. ### Method Signature ```java public Join join(Join sourceJoin, Property sourceProperty, Class destinationEntityClass, Property destinationProperty) ``` ### Parameters #### Path Parameters * **sourceJoin** (Join) - Required - The preceding join in the chain * **sourceProperty** (Property) - Required - FK property in the source entity of this join * **destinationEntityClass** (Class) - Required - Target entity type for this join * **destinationProperty** (Property) - Required - PK property in the destination entity for this join ### Returns A Join object representing the chained join. ``` -------------------------------- ### Query with Join and Result Processing Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Join.md Find active orders from customers in California, ordered by amount descending, limited to the top 20. Then, process the results by logging customer details. ```java List topOrders = orderDao.queryBuilder() .where(Properties.Status.eq("active")) .join(Customer.class, CustomerDao.Properties.OrderId) .where( CustomerDao.Properties.State.eq("CA"), CustomerDao.Properties.Active.eq(true) ) .orderDesc(Properties.Amount) .limit(20) .list(); // Process results for (Order order : topOrders) { Customer customer = order.getCustomer(); Log.d("Orders", String.format( "%s: $%.2f on %s", customer.getName(), order.getAmount(), new Date(order.getCreatedAt()) )); } ``` -------------------------------- ### join(Property sourceProperty, Class destinationEntityClass, Property destinationProperty) Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Joins entities using a property reference, allowing explicit specification of both the source property (holding the FK) and the destination property (the primary key in the destination entity). ```APIDOC ## join(Property sourceProperty, Class destinationEntityClass, Property destinationProperty) ### Description Joins using a property reference. Useful when the source entity has the FK. ### Method Signature ```java public Join join(Property sourceProperty, Class destinationEntityClass, Property destinationProperty) ``` ### Parameters #### Path Parameters * **sourceProperty** (Property) - Required - FK property in the source entity * **destinationEntityClass** (Class) - Required - Target entity type * **destinationProperty** (Property) - Optional - Explicit PK property in destination (auto-detected if omitted) ### Returns A Join object for adding conditions on the joined entity. ``` -------------------------------- ### Build Cursor Query for Memory Efficiency Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Builds a query that returns raw cursor results, optimized for memory-efficient iteration over large datasets. ```java public CursorQuery buildCursor() ``` -------------------------------- ### Enable SQL and Value Logging Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Set LOG_SQL to true to log generated SQL statements. Set LOG_VALUES to true to also log parameter values. These flags are useful for debugging. ```java public static boolean LOG_SQL; public static boolean LOG_VALUES; ``` -------------------------------- ### Async Operation Insertion Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/README.md Demonstrates initiating a non-blocking database insert operation using AsyncSession. The operation is queued for background processing, allowing the UI thread to continue immediately. ```java asyncSession.insert(user); // Returns immediately // ... UI thread continues asyncSession.waitForCompletion(); // Optional: wait for completion ``` -------------------------------- ### Create QueryBuilder for Complex Queries Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDao.md Instantiate a QueryBuilder to construct sophisticated queries with conditions, ordering, and limits. The returned QueryBuilder can then be used to build and execute a Query. ```java public QueryBuilder queryBuilder() ``` ```java List results = userDao.queryBuilder() .where(Properties.FirstName.eq("John")) .orderAsc(Properties.LastName) .build() .list(); ``` -------------------------------- ### StandardDatabase Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Database.md Wrapper around SQLiteDatabase for unencrypted databases. ```APIDOC ## StandardDatabase Wrapper around SQLiteDatabase (for unencrypted databases). ```java public class StandardDatabase implements Database { public StandardDatabase(SQLiteDatabase delegate); // Implements Database interface } ``` **Usage:** ```java SQLiteDatabase sqliteDb = helper.getWritableDatabase(); Database db = new StandardDatabase(sqliteDb); DaoMaster daoMaster = new DaoMaster(db); ``` ``` -------------------------------- ### rx / rxPlain Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/AbstractDaoSession.md Returns RxJava wrappers for transaction operations. `rx()` operates on the IO scheduler, while `rxPlain()` does not use a scheduler. ```APIDOC ## rx() / rxPlain() ### Description Returns RxJava wrappers for transaction operations. - `rx()`: Operates on the IO scheduler - `rxPlain()`: No scheduler ### Methods ```java public RxTransaction rx() public RxTransaction rxPlain() ``` ``` -------------------------------- ### Initialize DaoMaster with SQLiteDatabase Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/DaoMaster.md Ensures the SQLiteDatabase is not null before initializing DaoMaster to prevent NullPointerExceptions. ```java SQLiteDatabase db = helper.getWritableDatabase(); if (db != null) { DaoMaster daoMaster = new DaoMaster(new StandardDatabase(db)); } ``` -------------------------------- ### join(Class destinationEntityClass, Property destinationProperty) Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/QueryBuilder.md Joins the current entity to another entity using a foreign key relationship. This is useful when the foreign key is in the destination entity and points back to the source entity. ```APIDOC ## join(Class destinationEntityClass, Property destinationProperty) ### Description Joins this entity to another using a foreign key relationship. ### Method Signature ```java public Join join(Class destinationEntityClass, Property destinationProperty) ``` ### Parameters #### Path Parameters * **destinationEntityClass** (Class) - Required - Target entity type to join * **destinationProperty** (Property) - Required - FK property in the destination entity pointing back to this entity ### Returns A Join object for adding conditions on the joined entity. ### Example ```java List orders = orderDao.queryBuilder() .join(Customer.class, CustomerDao.Properties.OrderId) .where(CustomerDao.Properties.Name.eq("Acme Corp")) .list(); ``` ``` -------------------------------- ### Join with Ordering and Limit Source: https://github.com/greenrobot/greendao/blob/master/_autodocs/api-reference/Join.md Retrieves orders by joining with the Customer table, filtering by country, and then ordering the results by amount in descending order with a limit of 20. ```java List orders = orderDao.queryBuilder() .join(Customer.class, CustomerDao.Properties.OrderId) .where(CustomerDao.Properties.Country.eq("USA")) .orderDesc(Properties.Amount) .limit(20) .list(); ```