如何使用IDroid ORM框架访问SQLite数据库及实现增删改查与建表
Alright, let's dive into using the IDroid ORM framework for SQLite database interactions—covering table creation and all CRUD operations. I’ve worked with this framework on a couple of Android projects, so I’ll walk you through practical, easy-to-follow steps.
First, add the IDroid dependency to your app-level build.gradle file (use the latest stable version available):
implementation 'com.github.yuweiguocn:IDroid:v1.0.1'
Then initialize IDroid in your Application class (this ensures it's ready to use across your app):
public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); IDroid.init(this); } }
Don’t forget to declare your Application class in AndroidManifest.xml.
IDroid uses annotation-based entity classes to map to SQLite tables. Let’s create a User entity for example:
@Table(name = "user") // Maps to a table named "user" in SQLite public class User { @PrimaryKey(autoGenerate = true) // Auto-incrementing primary key private long id; @Column(name = "username") // Maps to a column named "username" private String username; @Column(name = "age") private int age; @Column(name = "email") private String email; // *Critical*: IDroid requires a no-arg constructor for reflection public User() {} // Overloaded constructor for convenience (optional) public User(String username, int age, String email) { this.username = username; this.age = age; this.email = email; } // Getters and Setters (required for IDroid to access fields) public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
IDroid will automatically create the table when you first interact with it. If you need to manually trigger table creation (for edge cases), use:
IDroid.getDb().createTable(User.class);
Single Record Insert
Use the save() method to insert a single entity. It returns the auto-generated primary key ID:
User newUser = new User("john_doe", 28, "john@example.com"); long insertedId = IDroid.getDb().save(newUser);
Batch Insert
For inserting multiple records at once, use saveBatch()—it returns the number of successfully inserted records:
List<User> userList = new ArrayList<>(); userList.add(new User("jane_smith", 25, "jane@example.com")); userList.add(new User("bob_brown", 30, "bob@example.com")); int insertedCount = IDroid.getDb().saveBatch(userList);
Update by Primary Key
To update an existing record, set the primary key (so IDroid knows which row to target) and call update():
User updatedUser = new User(); updatedUser.setId(1); // Target the user with ID 1 updatedUser.setAge(29); // Update only the age field updatedUser.setEmail("john_new@example.com"); // Update email too int updatedCount = IDroid.getDb().update(updatedUser);
Conditional Update
Use the UpdateBuilder to update rows based on a condition (e.g., update all users over 25 with a new email):
int updatedCount = IDroid.getDb().update(User.class) .set("email", "updated@example.com") .where("age > ?", 25) .execute();
Delete by Primary Key
Similar to updates, set the primary key on an entity and call delete():
User userToDelete = new User(); userToDelete.setId(1); // Delete the user with ID 1 int deletedCount = IDroid.getDb().delete(userToDelete);
Conditional Delete
Delete rows matching a condition (e.g., delete all users under 18):
int deletedCount = IDroid.getDb().delete(User.class) .where("age < ?", 18) .execute();
Delete All Records
To wipe an entire table:
IDroid.getDb().deleteAll(User.class);
IDroid’s QueryBuilder makes building complex queries straightforward.
Query Single Record by ID
User user = IDroid.getDb().findById(User.class, 1);
Query Single Record by Condition
User user = IDroid.getDb().findFirst(User.class) .where("username = ?", "john_doe") .execute();
Query All Records
List<User> allUsers = IDroid.getDb().findAll(User.class);
Conditional Query with Sorting
Get all users over 25, sorted by age in descending order:
List<User> userList = IDroid.getDb().findList(User.class) .where("age > ?", 25) .orderBy("age DESC") .execute();
Paged Query
Fetch the second page of results (10 records per page):
List<User> userList = IDroid.getDb().findList(User.class) .limit(10) // Records per page .offset(10) // Skip first 10 records (for page 2) .execute();
Query Specific Fields
Only fetch username and age columns (reduces data transfer):
List<User> userList = IDroid.getDb().findList(User.class) .select("username", "age") .execute();
- Always include a no-arg constructor in your entity classes—IDroid uses reflection to create instances, and this is non-negotiable.
- Use
@Column(name = "column_name")if you want to map a field to a different column name than the field itself; if omitted, it uses the field name by default. - Avoid running database operations on the main thread (Android will throw a NetworkOnMainThreadException for long operations). Use Kotlin Coroutines, AsyncTask, or RxJava to offload work to background threads.
- Primary keys should preferably be
long(notint) to avoid overflow with large datasets.
内容的提问来源于stack exchange,提问作者user12240680

