### Initialize greenDAO Database Source: https://greenrobot.org/greendao/documentation/how-to-get-started Use DevOpenHelper for development to create and get a writable database. Remember to use a custom OpenHelper subclass for production environments to manage schema upgrades safely. ```java // note: DevOpenHelper is for dev only, use a OpenHelper subclass instead DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db"); Database db = helper.getWritableDb(); daoSession = new DaoMaster(db).newSession(); ``` -------------------------------- ### Self-Join Query Example in GreenDao Source: https://greenrobot.org/greendao/documentation/custom-types This example demonstrates how to perform a self-join query to find descendants based on a grandfather's name. It correctly sets up the joins and applies a filter on the grandfather's name. ```java QueryBuilder qb = personDao.queryBuilder(); Join father = qb.join(Properties.FatherId,Person.class); Join grandfather = qb.join(father, Properties.FatherId, Person.class, Properties.Id); grandfather.where(Properties.Name.eq("Lincoln")); List lincolnDescendants = qb.list(); ``` -------------------------------- ### Query Cities in Europe with Population > 1 Million Source: https://greenrobot.org/greendao/documentation/joins Example demonstrating chained joins to query cities in a specific continent with a minimum population. It joins City to Country, then Country to Continent. ```java QueryBuilder qb = cityDao.queryBuilder().where(Properties.Population.ge(1000000)); Join country = qb.join(Properties.CountryId, Country.class); Join continent = qb.join(country, CountryDao.Properties.ContinentId, Continent.class, ContinentDao.Properties.Id); continent.where(ContinentDao.Properties.Name.eq("Europe")); List bigEuropeanCities = qb.list(); ``` -------------------------------- ### Get Note DAO Instance Source: https://greenrobot.org/greendao/documentation/how-to-get-started Retrieves the greenDAO session and the specific DAO object for the 'Note' entity within the application's onCreate method. ```java // get the note DAO DaoSession daoSession = ((App) getApplication()).getDaoSession(); noteDao = daoSession.getNoteDao(); ``` -------------------------------- ### Define Bi-Directional 1:N Relations in GreenDao Entities Source: https://greenrobot.org/greendao/documentation/relations This example shows how to model bi-directional 1:N relations using @ToMany and @ToOne annotations with join properties. ```java @Entity public class Customer { @Id private Long id; @ToMany(referencedJoinProperty = "customerId") @OrderBy("date ASC") private List orders; } @Entity public class Order { @Id private Long id; private Date date; private long customerId; @ToOne(joinProperty = "customerId") private Customer customer; } ``` -------------------------------- ### Query Persons with Grandfather Named Lincoln (Self Join) Source: https://greenrobot.org/greendao/documentation/joins Example of a self-join to find descendants based on an ancestral relationship. It joins Person to its father, and then again to the father's father (grandfather). ```java QueryBuilder qb = personDao.queryBuilder(); Join father = qb.join(Person.class, Properties.FatherId); Join grandfather = qb.join(father, Properties.FatherId, Person.class, Properties.Id); grandfather.where(Properties.Name.eq("Lincoln")); List lincolnDescendants = qb.list(); ``` -------------------------------- ### Access Bi-Directional Relations in GreenDao Source: https://greenrobot.org/greendao/documentation/generator Navigate through bi-directional relations to access related entities from either side. This example shows accessing all orders for a customer from an order entity. ```java List allOrdersOfCustomer = order.getCustomer().getOrders(); ``` -------------------------------- ### greenDAO Generation Error Example Source: https://greenrobot.org/greendao/documentation/modelling-entities This error occurs when generated code is modified. Resolve by reverting changes, deleting the code, or using @Keep. ```java Error:Execution failed for task ':app:greendao'. > Constructor (see ExampleEntity:21) has been changed after generation. Please either mark it with @Keep annotation instead of @Generated to keep it untouched, or use @Generated (without hash) to allow to replace it. ``` ```java 1234 | Error:Execution failed for task ':app:greendao'.> Constructor (see ExampleEntity:21) has been changed after generation.Please either mark it with @Keep annotation instead of @Generated to keep it untouched,or use @Generated (without hash) to allow to replace it. ``` -------------------------------- ### Querying with Custom Enum Types in GreenDao Source: https://greenrobot.org/greendao/documentation/custom-types When querying, use the primitive type that the custom type converter maps to. This example shows how to query users based on a Role enum, converting the enum to its database representation. ```java RoleConverter converter = new RoleConverter(); List authors = userDao.queryBuilder() .where(Properties.Role.eq(converter.convertToDatabaseValue(Role.AUTHOR))) .list(); ``` -------------------------------- ### Enum to Integer Property Converter Source: https://greenrobot.org/greendao/documentation/custom-types Example of mapping a custom enum 'Role' to an Integer type in the database using @Convert and a PropertyConverter. Ensure converter classes are static if defined within the entity. ```Java import org.greenrobot.greendao.converter.PropertyConverter; import javax.persistence.Convert; @Entity public class User { @Id private Long id; @Convert(converter = RoleConverter.class, columnType = Integer.class) private Role role; public enum Role { DEFAULT(0), AUTHOR(1), ADMIN(2); final int id; Role(int id) { this.id = id; } } public static class RoleConverter implements PropertyConverter { @Override public Role convertToEntityProperty(Integer databaseValue) { if (databaseValue == null) { return null; } for (Role role : Role.values()) { if (role.id == databaseValue) { return role; } } return Role.DEFAULT; } @Override public Integer convertToDatabaseValue(Role entityProperty) { return entityProperty == null ? null : entityProperty.id; } } } ``` -------------------------------- ### Demonstrate To-Many Relation Caching Behavior Source: https://greenrobot.org/greendao/documentation/relations To-many relations are lazily resolved and cached. This example shows that adding a new related entity to the database does not update the cached list. ```java List orders1 = customer.getOrders(); Order order = new Order(); order.setCustomerId(customer.getId()); daoSession.insert(order); List orders2 = customer.getOrders(); assert(orders1.size() == orders2.size); assert(orders1.equals(orders2)); ``` -------------------------------- ### Model Tree Relations in GreenDao Source: https://greenrobot.org/greendao/documentation/generator Defines an entity with a self-referencing parent-child relationship to model tree structures. This setup allows for navigation between parent and children entities. ```java Entity treeEntity = schema.addEntity("TreeEntity"); treeEntity.addIdProperty(); Property parentIdProperty = treeEntity.addLongProperty("parentId").getProperty(); treeEntity.addToOne(treeEntity, parentIdProperty).setName("parent"); treeEntity.addToMany(treeEntity, parentIdProperty).setName("children"); ``` -------------------------------- ### Clear Cached To-Many List with reset() Source: https://greenrobot.org/greendao/documentation/relations Use the reset method to clear the cached list of related entities. The next call to the get method will requery the database. ```java customer.resetOrders(); List orders = customer.getOrders(); ``` -------------------------------- ### Initialize BoxStore and DaoCompat Session Source: https://greenrobot.org/greendao/documentation/objectbox-compat Set up the BoxStore and create a DaoCompat DaoSession. This is typically done in an Android Application class. ```java boxStore = MyObjectBox.builder().androidContext(this).build(); daoCompatSession = new DaoSession(boxStore); ``` -------------------------------- ### Initialize greenDAO Core Classes Source: https://greenrobot.org/greendao/documentation/introduction This code demonstrates the one-time initialization of the database and core greenDAO classes, typically done in an Application class. It also shows how to obtain a DAO object for a specific entity in activities or fragments. ```java // do this once, for example in your Application class DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null); SQLiteDatabase db = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(db); DaoSession daoSession = daoMaster.newSession(); // do this in your activities/fragments to get hold of a DAO NoteDao noteDao = daoSession.getNoteDao(); ``` -------------------------------- ### Initialize Schema Source: https://greenrobot.org/greendao/documentation/generator Create a new Schema object with the version number and default Java package. ```java Schema schema = new Schema(1, "de.greenrobot.daoexample"); ``` -------------------------------- ### Initialize Encrypted Database with SQLCipher Source: https://greenrobot.org/greendao/documentation/database-encryption Use this method to create an encrypted database instance with a password. Ensure you are using a subclass of OpenHelper provided in DaoMaster. ```java DevOpenHelper helper = new DevOpenHelper(this, "notes-db-encrypted.db"); Database db = helper.getEncryptedWritableDb(""); daoSession = new DaoMaster(db).newSession(); ``` -------------------------------- ### Reusing a Query with Changed Parameters Source: https://greenrobot.org/greendao/documentation/queries Demonstrates how to build a query once and then reuse the Query object by changing its parameters for subsequent executions. This is more efficient than creating new query objects repeatedly. ```Java Query query = userDao.queryBuilder().where( Properties.FirstName.eq("Joe"), Properties.YearOfBirth.eq(1970) ).build(); List joesOf1970 = query.list(); // using the same Query object, we can change the parameters // to search for Marias born in 1977 later: query.setParameter(0, "Maria"); query.setParameter(1, 1977); List mariasOf1977 = query.list(); ``` -------------------------------- ### Enable SQL and Parameter Logging Source: https://greenrobot.org/greendao/documentation/queries Set these static flags to true to log the generated SQL and passed values for queries. This is useful for debugging query results. ```java QueryBuilder.LOG_SQL = true; QueryBuilder.LOG_VALUES = true; ``` -------------------------------- ### Create DaoSession Source: https://greenrobot.org/greendao/documentation/sessions Instantiate a DaoMaster and then create a DaoSession from it. Multiple sessions share the same database connection. ```java daoMaster = new DaoMaster(db); daoSession = daoMaster.newSession(); ``` -------------------------------- ### Enable ObjectBox DaoCompat Annotation Processor (Kotlin) Source: https://greenrobot.org/greendao/documentation/objectbox-compat Configure the annotation processor in your Kotlin project's build.gradle file to enable DaoCompat mode. ```gradle kapt { arguments { arg("objectbox.daoCompat", true) } } ``` -------------------------------- ### Configure Gradle for Generator Main Class Source: https://greenrobot.org/greendao/documentation/generator Sets up the Gradle build file to specify the main class for running the GreenDao generator. This is useful for resolving NoClassDefFoundError, ClassNotFoundException, or TemplateNotFoundException when running from Android Studio. ```gradle apply plugin: 'application' mainClassName = "com.example.YourGeneratorClass" ``` -------------------------------- ### Set Default Java Packages for DAO and Test Classes Source: https://greenrobot.org/greendao/documentation/generator Configure separate default Java packages for DAO and test classes if needed. ```java // DAO classes go into the "dao" packageschema.setDefaultJavaPackageDao("de.greenrobot.daoexample.dao");// test classes go into the "test" packageschema.setDefaultJavaPackageTest("de.greenrobot.daoexample.test"); ``` -------------------------------- ### Insert a New Note Source: https://greenrobot.org/greendao/documentation/how-to-get-started Creates a new 'Note' object, sets its properties, and inserts it into the database using the 'insert' method of the NoteDao. ```java Note note = new Note(); note.setText(noteText); note.setComment(comment); note.setDate(new Date()); note.setType(NoteType.TEXT); noteDao.insert(note); Log.d("DaoExample", "Inserted new note, ID: " + note.getId()); ``` -------------------------------- ### Migrate greenDAO Data to ObjectBox Source: https://greenrobot.org/greendao/documentation/objectbox-compat Load entities using a greenDAO session, convert them to ObjectBox entities, and insert them using the DaoCompat session. This is useful for migrating existing data. ```java // note example List notes = daoSession.getNoteDao().loadAll(); List convertedNotes = convertToObjectBoxNotes(notes); daoCompatSession.getNoteDao().insertInTx(convertedNotes); ``` -------------------------------- ### User Entity with Property Customization Source: https://greenrobot.org/greendao/documentation/modelling-entities Shows how to customize entity properties using @Id with autoincrement, @Property for custom column names, @NotNull for non-null constraints, and @Transient for non-persisted fields. ```Java @Entity public class User { @Id(autoincrement = true) private Long id; @Property(nameInDb = "USERNAME") private String name; @NotNull private int repos; @Transient private int tempUsageCount; ... } ``` -------------------------------- ### Accessing and Updating To-One Relations Source: https://greenrobot.org/greendao/documentation/relations Demonstrates lazy loading of a to-one relation and how changes to the foreign key or the related entity are handled. ```Java Customer customerA = user.getCustomer(); // change the customer id user.setCustomerId(customerIdB); // or set a customer with a different id user.setCustomer(customerB); customerB = user.getCustomer(); assert(customerA.getId() != customerB.getId()); ``` -------------------------------- ### Configurable @Entity Annotation Source: https://greenrobot.org/greendao/documentation/modelling-entities Demonstrates advanced @Entity configuration options including schema, active status, custom table name, indexes, and constructor/getter/setter generation. ```Java @Entity( // If you have more than one schema, you can tell greenDAO // to which schema an entity belongs (pick any string as a name). schema = "myschema", // Flag to make an entity "active": Active entities have update, // delete, and refresh methods. active = true, // Specifies the name of the table in the database. // By default, the name is based on the entities class name. nameInDb = "AWESOME_USERS", // Define indexes spanning multiple columns here. indexes = { @Index(value = "name DESC", unique = true) }, // Flag if the DAO should create the database table (default is true). // Set this to false, if you have multiple entities mapping to one table, // or the table creation is done outside of greenDAO. createInDb = false, // Whether an all properties constructor should be generated. // A no-args constructor is always required. generateConstructors = true, // Whether getters and setters for properties should be generated if missing. generateGettersSetters = true ) public class User { ... } ``` -------------------------------- ### Simple Query: Filter by First Name and Order by Last Name Source: https://greenrobot.org/greendao/documentation/queries Use this snippet to query for entities matching a specific first name and sort the results by last name. ```Java List joes = userDao.queryBuilder() .where(Properties.FirstName.eq("Joe")) .orderAsc(Properties.LastName) .list(); ``` -------------------------------- ### Execute Raw SQL with queryRawCreate Source: https://greenrobot.org/greendao/documentation/queries Use queryRawCreate to append custom WHERE and ORDER BY clauses to a raw SQL query. The entity table can be referred to using the alias T. This method is suitable for queries involving joins or specific ordering. ```Java Query query = userDao.queryRawCreate( ", GROUP G WHERE G.NAME=? AND T.GROUP_ID=G._ID", "admin" ); ``` -------------------------------- ### Configure ProGuard for greenDAO 3 Source: https://greenrobot.org/greendao/documentation/updating-to-greendao-3-and-annotations Adjust your ProGuard rules to ensure greenDAO classes and properties are not removed during obfuscation. Exclude RxJava and SQLCipher if not used. ```proguard -keepclassmembers class * extends org.greenrobot.greendao.AbstractDao { public static java.lang.String TABLENAME; } -keep class **$Properties # If you do not use SQLCipher: -dontwarn org.greenrobot.greendao.database.* # If you do not use Rx: -dontwarn rx.** ``` -------------------------------- ### Add Annotation and Javadoc to Property Source: https://greenrobot.org/greendao/documentation/generator Add annotations and Javadoc specifically for the field, getter, or setter of a property. ```java myEntity.addIntProperty("counter") .codeBeforeField("@SerializedName(\"the-number-of-things\")") .javaDocGetterAndSetter("The total count"); ``` -------------------------------- ### Add ObjectBox DaoCompat Dependency Source: https://greenrobot.org/greendao/documentation/objectbox-compat Add the ObjectBox DaoCompat library to your module's build.gradle file. Ensure you use the latest version available on Maven Central. ```gradle // In your (app) module build.gradle file: dependencies { compile "org.greenrobot:objectbox-daocompat:" } ``` -------------------------------- ### Update greenDAO Package Imports Source: https://greenrobot.org/greendao/documentation/updating-to-greendao-3-and-annotations Change your import statements from the old package 'de.greenrobot.dao' to the new package 'org.greenrobot.greendao' for classes like Database. ```java // old package name import de.greenrobot.dao.database.Database; // new package name import org.greenrobot.greendao.database.Database; ``` -------------------------------- ### Enable ObjectBox DaoCompat Annotation Processor (Java) Source: https://greenrobot.org/greendao/documentation/objectbox-compat Configure the annotation processor in your Android project's build.gradle file to enable DaoCompat mode for Java-only projects. ```gradle android { defaultConfig { javaCompileOptions { annotationProcessorOptions { arguments = [ 'objectbox.daoCompat' : 'true' ] } } } } ``` -------------------------------- ### Enable Optional Schema Features Source: https://greenrobot.org/greendao/documentation/generator Enable optional features such as active entities and support for keep sections by default. ```java // optional: make entities activeschema.enableActiveEntitiesByDefault();// optional: enable KEEP section supportschema.enableKeepSectionsByDefault(); ``` -------------------------------- ### Update Property Indexes from greenDAO to ObjectBox Source: https://greenrobot.org/greendao/documentation/objectbox-compat Adapt your entity property index definitions. ObjectBox supports a simpler index syntax and does not support unique or multi-property indexes as greenDAO does. ```java // greenDAO @Entity(indexes = { ... }) @Index(name = "idx1", unique = true) private String name; @Unique private String name; // ObjectBox @Index private String name; ``` -------------------------------- ### Generate Entities and DAOs with GreenDAO Generator Source: https://greenrobot.org/greendao/documentation/generator Use this code to define your database schema, add entities and properties, and then generate the corresponding Java files for entities and DAOs. This is useful for advanced features not yet supported by the Gradle plugin. ```java Schema schema = new Schema(1, "de.greenrobot.daoexample"); Entity note= schema.addEntity("Note"); note.addIdProperty(); note.addStringProperty("text").notNull(); note.addStringProperty("comment"); note.addDateProperty("date"); new DaoGenerator().generateAll(schema, "../DaoExample/src/main/java"); ``` -------------------------------- ### Navigate Tree Relations Source: https://greenrobot.org/greendao/documentation/generator Demonstrates how to access the parent and children of a tree entity once generated. This code is used after the entity schema has been processed by the generator. ```java TreeEntity parent = child.getParent(); List grandChildren = child.getChildren(); ``` -------------------------------- ### Add Javadoc and Annotation to Entity Source: https://greenrobot.org/greendao/documentation/generator Add Javadoc documentation and a custom annotation string to an entity. Newlines in Javadoc are automatically handled. ```java myEntity.setJavaDoc("This is an hell of an entity.\nIt represents foos and bars.");// add an annotation, though you can supply any stringmyEntity.setCodeBeforeClass("@Awesome"); ``` -------------------------------- ### Order Query Results Source: https://greenrobot.org/greendao/documentation/queries Order query results by last name in ascending or descending order. You can also combine multiple ordering criteria. ```java queryBuilder.orderAsc(Properties.LastName); queryBuilder.orderDesc(Properties.LastName); queryBuilder.orderAsc(Properties.LastName).orderDesc(Properties.YearOfBirth); ``` -------------------------------- ### Access Related Entities in Bi-Directional 1:N Relation Source: https://greenrobot.org/greendao/documentation/relations Demonstrates accessing the customer and all their orders through the bi-directional relation from an order entity. ```java List allOrdersOfCustomer = order.getCustomer().getOrders(); ``` -------------------------------- ### Implement Interface for Entity Source: https://greenrobot.org/greendao/documentation/generator Make an entity implement a specified interface. This is useful for sharing properties and behavior. ```java // entity class A implements CentityA.implementsInterface("C");// entity class B implements CentityB.implementsInterface("C"); ``` -------------------------------- ### Configure greenDAO Schema Version Source: https://greenrobot.org/greendao/documentation/modelling-entities Set the schema version in your app's build.gradle file. This version is used by OpenHelper classes for database migrations. Increase this value when your schema changes. ```gradle android { ... } greendao { schemaVersion 2 // daoPackage "com.example.model" // set package of generated classes } ``` -------------------------------- ### Add Properties to Entity Source: https://greenrobot.org/greendao/documentation/generator Define properties for an entity, including an ID, string, password, and integer. ```java user.addIdProperty();user.addStringProperty("name");user.addStringProperty("password");user.addIntProperty("yearOfBirth"); ``` -------------------------------- ### Querying Users by Street via Joined Addresses Source: https://greenrobot.org/greendao/documentation/joins This snippet demonstrates joining the User and Address entities to filter users based on their street name. It uses the QueryBuilder to specify the join condition and the WHERE clause. ```Java QueryBuilder queryBuilder = userDao.queryBuilder(); queryBuilder.join(Address.class, AddressDao.Properties.userId) .where(AddressDao.Properties.Street.eq("Sesame Street")); List users = queryBuilder.list(); ``` -------------------------------- ### Model To-One Relation with @ToOne Source: https://greenrobot.org/greendao/documentation/relations Defines a to-one relation between Order and Customer entities. The joinProperty specifies the foreign key. ```Java @Entity public class Order { @Id private Long id; private long customerId; @ToOne(joinProperty = "customerId") private Customer customer; } @Entity public class Customer { @Id private Long id; } ``` -------------------------------- ### Update greenDAO Imports for ObjectBox Compatibility Source: https://greenrobot.org/greendao/documentation/objectbox-compat Change imports from greenDAO packages to the corresponding ObjectBox compatibility packages (e.g., org.greenrobot.daocompat). This is necessary for using ObjectBox features with greenDAO code. ```java // greenDAO import org.greenrobot.greendao.query.Query; import org.greenrobot.greendao... // ObjectBox import org.greenrobot.daocompat.query.Query; import org.greenrobot.daocompat... ``` -------------------------------- ### Implement Serializable for Entity Source: https://greenrobot.org/greendao/documentation/generator Convenience method to make an entity implement the Serializable interface. ```java // class ExampleEntity implements SerializableexampleEntity.implementsSerializable(); ``` -------------------------------- ### Offset Query Results Source: https://greenrobot.org/greendao/documentation/queries Set an offset for query results to skip a certain number of records before applying the limit. Requires limit() to be used. ```java queryBuilder.offset(int); ``` -------------------------------- ### Set Superclass for Entity Source: https://greenrobot.org/greendao/documentation/generator Configure an entity to inherit from a specified superclass. Note: Entities cannot inherit from other entities. ```java // class ExampleEntity extends BaseClassexampleEntity.setSuperclass("BaseClass"); ``` -------------------------------- ### Update Relations from greenDAO to ObjectBox Source: https://greenrobot.org/greendao/documentation/objectbox-compat Replace greenDAO's @ToOne and @ToMany annotations with ObjectBox's ToOne and ToMany types in your entity classes. ```java // Example demonstrating the concept, actual syntax depends on entity structure // greenDAO: @ToOne(oneToMany = true) private EntityA relationA; // ObjectBox: @ToOne ToOne relationA; ``` -------------------------------- ### Set Java Compilation Encoding Source: https://greenrobot.org/greendao/documentation/generator Configure the encoding for Java compilation tasks in Gradle to handle non-US-ASCII characters. ```gradle tasks.withType(JavaCompile) { options.encoding = 'UTF-8' } ``` -------------------------------- ### Create Unique Index on String Property Source: https://greenrobot.org/greendao/documentation/modelling-entities Use the @Index annotation with the 'unique = true' parameter to enforce uniqueness for a string property, creating a unique database index. ```java @Entity public class User { @Id private Long id; @Index(unique = true) private String name; } ``` -------------------------------- ### Replace greenDAO DaoSession with DaoCompat Session Source: https://greenrobot.org/greendao/documentation/objectbox-compat Update your application to return the DaoCompat session instead of the greenDAO session. This allows existing greenDAO code to work with ObjectBox. ```java public DaoSession getDaoSession() { // greenDAO // return daoSession; // ObjectBox return daoCompatSession; } ``` -------------------------------- ### Enable and Use Keep Sections Source: https://greenrobot.org/greendao/documentation/generator Enable keep sections for entities to safely add custom code that persists across generator runs. Do not modify the KEEP comments themselves. ```java // KEEP INCLUDES - put your custom includes hereimport com.example.ExampleClass;// KEEP INCLUDES END ... // KEEP FIELDS - put your custom fields hereprivate void ExampleClass someCustomField;// KEEP FIELDS END ... // KEEP METHODS - put your custom methods herepublic ExampleClass getCustomStuff() { ...}// KEEP METHODS END ``` -------------------------------- ### Update Custom Type Converter Imports Source: https://greenrobot.org/greendao/documentation/objectbox-compat Change the import statement for your custom property converters from greenDAO's package to ObjectBox's package. ```java // greenDAO import org.greenrobot.greendao.converter.PropertyConverter; // ObjectBox import io.objectbox.converter.PropertyConverter; ``` -------------------------------- ### Chained Join API Method Signature Source: https://greenrobot.org/greendao/documentation/joins This method signature defines how to expand a query to another entity type using a JOIN, chaining from a source join. ```java /** * Expands the query to another entity type by using a JOIN. * The given sourceJoin's property is used to match the * given destinationProperty of the given destinationEntity. * Note that destination entity of the given join is used * as the source for the new join to add. In this way, * it is possible to compose complex "join of joins" across * several entities if required. */ public Join join(Join sourceJoin, Property sourceProperty, Class destinationEntityClass, Property destinationProperty) ``` -------------------------------- ### Update Entity Annotations from greenDAO to ObjectBox Source: https://greenrobot.org/greendao/documentation/objectbox-compat Change the imports for your entity annotations from the greenDAO package to the ObjectBox package. This is a crucial step for enabling ObjectBox's features. ```java // From the greenDao package name... import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation... // ...to the ObjectBox package name import io.objectbox.annotation.Entity; import io.objectbox.annotation... ``` -------------------------------- ### Update greenDAO Android Dependency to V3 Source: https://greenrobot.org/greendao/documentation/updating-to-greendao-3-and-annotations Update your Android project's build file to use the greenDAO library version 3. Remember to update your Java imports from de.greenrobot.dao to org.greenrobot.greendao. ```gradle compile 'org.greenrobot:greendao:3.3.0' ``` -------------------------------- ### Accessing To-Many Relations via Getter Source: https://greenrobot.org/greendao/documentation/relations After running the GreenDao plugin, a getter method is generated to retrieve the list of referenced entities. This getter allows easy access to related objects based on the defined relation mapping. ```Java // return all orders where customerId == customer.getId() List orders = customer.getOrders(); ``` -------------------------------- ### Nested Query: Filter by First Name and Date Range Source: https://greenrobot.org/greendao/documentation/queries Use this snippet to query for entities matching a first name and a complex date range condition. This demonstrates combining OR and AND conditions. ```Java QueryBuilder qb = userDao.queryBuilder(); qb.where(Properties.FirstName.eq("Joe"), qb.or(Properties.YearOfBirth.gt(1970), qb.and(Properties.YearOfBirth.eq(1970), Properties.MonthOfBirth.ge(10)))); List youngJoes = qb.list(); ``` -------------------------------- ### Define To-Many Relation in GreenDao Source: https://greenrobot.org/greendao/documentation/generator To establish a to-many relationship, add a foreign key property to the 'many' side entity and then configure the relation from the 'one' side entity. Relations can be named and ordered. ```java Property customerId = order.addLongProperty("customerId").notNull().getProperty(); ToMany customerToOrders = customer.addToMany(order, customerId); customerToOrders.setName("orders"); customerToOrders.orderAsc(orderDate); ``` -------------------------------- ### Define Bi-Directional 1:N Relation in GreenDao Source: https://greenrobot.org/greendao/documentation/generator Implement bi-directional navigation for 1:N relations by defining both a to-one and a to-many relationship between the entities. This allows traversal in both directions. ```java Entity customer = schema.addEntity("Customer"); customer.addIdProperty(); customer.addStringProperty("name").notNull(); Entity order = schema.addEntity("Order"); order.setTableName("ORDERS"); // "ORDER" is a reserved keyword order.addIdProperty(); Property orderDate = order.addDateProperty("date").getProperty(); Property customerId = order.addLongProperty("customerId").notNull().getProperty(); order.addToOne(customer, customerId); ToMany customerToOrders = customer.addToMany(order, customerId); customerToOrders.setName("orders"); customerToOrders.orderAsc(orderDate); ``` -------------------------------- ### Define Unique Index for String Primary Key Source: https://greenrobot.org/greendao/documentation/modelling-entities When a 'long' or 'Long' property is not suitable as a primary key, define it as an additional property and create a unique index for it. ```java @Id private Long id; @Index(unique = true) private String key; ``` -------------------------------- ### Trigger GreenDao Code Generation Source: https://greenrobot.org/greendao/documentation/generator Initiates the GreenDao code generation process. Requires a schema object and a target directory for the generated code. ```java DaoGenerator daoGenerator = new DaoGenerator(); daoGenerator.generateAll(schema, "../DaoExample/src/main/java"); ``` -------------------------------- ### QueryBuilder Join API Overloads Source: https://greenrobot.org/greendao/documentation/joins These are the overloaded join methods available in GreenDao's QueryBuilder for defining join conditions between entities. They allow flexibility in specifying which properties to use for matching primary keys. ```Java /** * Expands the query to another entity type by using a JOIN. * The primary key property of the primary entity for * this QueryBuilder is used to match the given destinationProperty. */ public Join join(Class destinationEntityClass, Property destinationProperty) ``` ```Java /** * Expands the query to another entity type by using a JOIN. * The given sourceProperty is used to match the primary * key property of the given destinationEntity. */ public Join join(Property sourceProperty, Class destinationEntityClass) ``` ```Java /** * Expands the query to another entity type by using a JOIN. * The given sourceProperty is used to match the given * destinationProperty of the given destinationEntity. */ public Join join(Property sourceProperty, Class destinationEntityClass, Property destinationProperty) ``` -------------------------------- ### Define To-One Relation in GreenDao Source: https://greenrobot.org/greendao/documentation/generator Add a foreign key property to an entity and then set up a to-one relation to another entity. The generated entity will have properties for accessing the related object. ```java Property pictureIdProperty = user.addLongProperty("pictureId").getProperty(); user.addToOne(picture, pictureIdProperty); ``` -------------------------------- ### Execute Raw SQL with StringCondition Source: https://greenrobot.org/greendao/documentation/queries Use StringCondition to pass raw SQL fragments as a WHERE clause to the QueryBuilder. This is useful for subqueries or complex conditions not directly supported by QueryBuilder. ```Java Query query = userDao.queryBuilder().where( new StringCondition("_ID IN " + "(SELECT USER_ID FROM USER_MESSAGE WHERE READ_FLAG = 0)") ).build(); ``` -------------------------------- ### Access Parent and Children in Java Source: https://greenrobot.org/greendao/documentation/relations Retrieve the parent and children of a TreeNode entity using the generated getter methods. Ensure the entity has been loaded or queried. ```java TreeNode parent = entity.getParent(); List children = entity.getChildren(); ``` -------------------------------- ### Add Entity to Schema Source: https://greenrobot.org/greendao/documentation/generator Use this to add a new entity to your GreenDao schema. ```java Entity user = schema.addEntity("User"); ``` -------------------------------- ### Update greenDAO Generator Dependency to V3 Source: https://greenrobot.org/greendao/documentation/updating-to-greendao-3-and-annotations Modify your generator project's build file to use the greenDAO generator version 3. Ensure imports are updated from de.greenrobot.daogenerator to org.greenrobot.greendao.generator. ```gradle compile 'org.greenrobot:greendao-generator:3.3.0' ``` -------------------------------- ### Note Entity Definition Source: https://greenrobot.org/greendao/documentation/how-to-get-started Defines the 'Note' entity with properties like id, text, and date, including database indexing and uniqueness constraints. ```java @Entity(indexes = { @Index(value = "text, date DESC", unique = true) }) public class Note { @Id private Long id; @NotNull private String text; private Date date; ... ``` -------------------------------- ### Add Custom Type Property Source: https://greenrobot.org/greendao/documentation/generator Map a custom Java type to a GreenDao property and specify a converter class. ```java user.addLongProperty("creationTime") .customType("com.example.UserTimestamp", "com.example.UserTimestampConverter"); ``` -------------------------------- ### To-Many Relation with joinProperties Source: https://greenrobot.org/greendao/documentation/relations Employ joinProperties for more complex relations, allowing specification of multiple @JoinProperty annotations. Each @JoinProperty maps a source property in the owning entity to a referenced property in the target entity. ```Java @Entity public class Customer { @Id private Long id; @Unique private String tag; @ToMany(joinProperties = { @JoinProperty(name = "tag", referencedName = "customerTag") }) @OrderBy("date ASC") private List orders; } @Entity public class Order { @Id private Long id; private Date date; @NotNull private String customerTag; } ``` -------------------------------- ### Update an Existing Note Source: https://greenrobot.org/greendao/documentation/how-to-get-started Modifies properties of an existing 'Note' object and then persists the changes to the database using the 'update' method of the NoteDao. ```java note.setText("This note has changed."); noteDao.update(note); ``` -------------------------------- ### Limit Query Results Source: https://greenrobot.org/greendao/documentation/queries Limit the number of results returned by a query. This is useful for pagination or displaying a subset of data. ```java queryBuilder.limit(int); ``` -------------------------------- ### Define Named To-One Relations in GreenDao Source: https://greenrobot.org/greendao/documentation/generator When adding multiple to-one relations to the same entity, each relation must be explicitly named to avoid conflicts. This is done by providing a name as the third argument to the addToOne method. ```java Property pictureIdProperty = user.addLongProperty("pictureId").getProperty(); user.addToOne(picture, pictureIdProperty); Property thumbnailIdProperty = user.addLongProperty("thumbnailId").getProperty(); user.addToOne(picture, thumbnailIdProperty, "thumbnail"); ``` -------------------------------- ### Define a greenDAO Entity with Annotations Source: https://greenrobot.org/greendao/documentation/updating-to-greendao-3-and-annotations Use the @Entity annotation to mark a Java class as a database entity. Transient fields are not persisted. Getters and setters are required. ```java @Entity public class User { @Id private Long id; private String name; @Transient private int tempUsageCount; // not persisted // getters and setters for id and user ... } ``` -------------------------------- ### Delete a Note by Key Source: https://greenrobot.org/greendao/documentation/how-to-get-started Removes a note from the database using its unique identifier by calling the 'deleteByKey' method on the NoteDao. ```java noteDao.deleteByKey(id); ``` -------------------------------- ### Model Tree Relations in Java Source: https://greenrobot.org/greendao/documentation/relations Define a TreeNode entity with self-referencing parent and children relationships. The 'parentId' property links a node to its parent. ```java @Entity public class TreeNode { @Id private Long id; private Long parentId; @ToOne(joinProperty = "parentId") private TreeNode parent; @ToMany(referencedJoinProperty = "parentId") private List children; } ``` -------------------------------- ### Manually Add New Related Entities to To-Many List Source: https://greenrobot.org/greendao/documentation/relations To add new related entities to a cached to-many list, first retrieve the list, then persist the new entity, and finally add it to the list. ```java List orders = customer.getOrders(); Order newOrder = ...; newOrder.setCustomerId(customer.getId()); daoSession.insert(newOrder); orders.add(newOrder); ``` -------------------------------- ### Add Unique Constraint to String Property Source: https://greenrobot.org/greendao/documentation/modelling-entities Apply the @Unique annotation to a property to enforce a UNIQUE constraint at the database level. SQLite implicitly creates an index for unique properties. ```java @Entity public class User { @Id private Long id; @Unique private String name; } ``` -------------------------------- ### Rename @Convert Annotation Property Source: https://greenrobot.org/greendao/documentation/objectbox-compat Update the 'columnType' property within the @Convert annotation to 'dbType' when migrating from greenDAO to ObjectBox. ```java // greenDAO @Convert(converter = NoteTypeConverter.class, columnType = String.class) // ObjectBox @Convert(converter = NoteTypeConverter.class, dbType = String.class) ``` -------------------------------- ### Many-to-Many Relation with @JoinEntity Source: https://greenrobot.org/greendao/documentation/relations Utilize the @JoinEntity annotation for many-to-many relationships. This involves an intermediate join entity/table, specified by the entity parameter, along with source and target properties for the mapping. ```Java @Entity public class Product { @Id private Long id; @ToMany @JoinEntity( entity = JoinProductsWithOrders.class, sourceProperty = "productId", targetProperty = "orderId" ) private List ordersWithThisProduct; } @Entity public class JoinProductsWithOrders { @Id private Long id; private Long productId; private Long orderId; } @Entity public class Order { @Id private Long id; } ``` -------------------------------- ### Access To-One Relation in GreenDao Source: https://greenrobot.org/greendao/documentation/generator Access the related object through the generated property in the entity. This allows for easy retrieval and setting of the related entity. ```java Picture picA = user.getPicture(); user.setPicture(picB); ``` -------------------------------- ### Clear Session Identity Scope Source: https://greenrobot.org/greendao/documentation/sessions Clears the identity scope for the entire session, preventing any 'cached' objects from being returned. ```java daoSession.clear(); ``` -------------------------------- ### To-Many Relation with referencedJoinProperty Source: https://greenrobot.org/greendao/documentation/relations Use referencedJoinProperty to specify the foreign key property in the target entity that points to the ID of the owning entity. This is suitable for one-to-many relationships. ```Java @Entity public class Customer { @Id private Long id; @ToMany(referencedJoinProperty = "customerId") @OrderBy("date ASC") private List orders; } @Entity public class Order { @Id private Long id; private Date date; private long customerId; } ``` -------------------------------- ### Change Entity ID Type from Long to long Source: https://greenrobot.org/greendao/documentation/objectbox-compat Modify your entity ID fields from the wrapper type Long to the primitive type long. ObjectBox handles IDs differently than greenDAO. ```java // greenDAO @Id private Long id; // ObjectBox @Id private long id; ``` -------------------------------- ### Manually Remove Related Entities from To-Many List Source: https://greenrobot.org/greendao/documentation/relations To remove related entities, delete the entity from the database and then manually remove it from the cached to-many list. ```java List orders = customer.getOrders(); daoSession.delete(someOrder); orders.remove(someOrder); ``` -------------------------------- ### Clear Single DAO Identity Scope Source: https://greenrobot.org/greendao/documentation/sessions Clears the identity scope for a specific DAO, detaching all entities managed by that DAO. ```java noteDao = daoSession.getNoteDao(); noteDao.detachAll(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.