Andy introduces ORMLite, an ORM library for Android. He demonstrates how to define data models with annotations, create database helpers to manage the underlying SQLite database, and implement DAO classes to perform CRUD operations and transactions on the data models. The code examples show how to define one-to-many relationships between User and Group data tables, and use the ORMLite API to easily insert, query, update, and delete records while handling transactions and relationships between the tables.
11. Data Table User
@DatabaseTable(tableName = "User")
public class User {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String name;
@DatabaseField
private int sort;
@ForeignCollectionField
private ForeignCollection<Group> groups;
public User() {}
}
12. Data Table Group
@DatabaseTable(tableName = "Group")
public class Group {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String name;
@DatabaseField
private String description;
@DatabaseField(foreign = true, foreignAutoRefresh =
true, canBeNull = false, columnName = "user_id")
private User user;
public Group() {}
}
13. public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Demo";
private static DatabaseHelper instance;
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DatabaseHelper getHelper(Context context) {
context = context.getApplicationContext();
if (instance == null) {
synchronized (DatabaseHelper.class) {
if (instance == null)
instance = new DatabaseHelper(context);
}
}
return instance;
}
}
DatabaseHelper