3.31
所花时间(包括上课):2
打码量(行):350
博客量(篇):1
了解到知识点:学习Room
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "users")
public class User {
@PrimaryKey(autoGenerate = true)
private int id;
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface UserDao {
@Insert
void insert(User user);
@Query("SELECT * FROM users")
List<User> getAllUsers();
@Query("SELECT * FROM users WHERE id = :userId")
User getUserById(int userId);
// 可以定义更多的查询方法和操作方法
}
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = {User.class}, version = 1, exportSchema = false)
public abstract class MyAppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
import android.content.Context;
import androidx.room.Room;
public class DatabaseClient {
private final Context context;
private static DatabaseClient mInstance;
// Room 数据库实例
private MyAppDatabase appDatabase;
private DatabaseClient(Context context) {
this.context = context;
// 创建或获取 Room 数据库实例
appDatabase = Room.databaseBuilder(context.getApplicationContext(),
MyAppDatabase.class, "my_database")
.fallbackToDestructiveMigration() // 数据库升级时使用,清除所有数据重新创建
.build();
}
public static synchronized DatabaseClient getInstance(Context context) {
if (mInstance == null) {
mInstance = new DatabaseClient(context);
}
return mInstance;
}
public MyAppDatabase getAppDatabase() {
return appDatabase;
}
}
本文来自博客园,作者:赵千万,转载请注明原文链接:https://www.cnblogs.com/zhaoqianwan/p/17533476.html
千万千万赵千万