https://developer.android.google.cn/training/data-storage/room
实体类,对应数据库中的表:
@Entity(tableName = "user_table")
public class UserEntity {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "name")
public String name;
@ColumnInfo(name = "address")
public String address;
public UserEntity (String name, String address) {
this.name= name;
this.address= address;
}
}
Dao接口,每个方法对应一条sql语句:
@Dao
public interface UserEntityDao {
@Query("SELECT * FROM user_table")
List<UserEntity> queryAll();
@Insert
void insetItem(UserEntity userEntity);
@Insert
void insertAll(UserEntity... userEntities);
}
创建数据库实例:
@Database(entities = {UserEntity.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
private static MyDatabase sMyDatabase;
public abstract UserEntityDao mUserEntityDao();
public static MyDatabase getMyDatabase() {
if (sMyDatabase== null) {
synchronized (MyDatabase .class) {
sMyDatabase= Room.databaseBuilder(BaseApplication.getAppContext(),
MyDatabase .class, "demo_db").build();
}
}
return sMyDatabase;
}
}
使用:
public void loadHistories() {
new Thread(() -> {
MyDatabase database = MyDatabase .getMyDatabase();
List<UserEntity> list = database.mUserEntityDao().queryAll();
}).start();
}
github:https://github.com/guolindev/LitePal
注意:
github:https://github.com/greenrobot/greenDAO,https://github.com/yuweiguocn/GreenDaoUpgradeHelper
android {
greendao {
schemaVersion 1 //当前数据库版本
}
}
除schemaVersion外还可以添加的配置:
daoPackage:生成的DAO,DaoMaster和DaoSession的软件包名称。 默认为源实体的程序包名称。
targetGenDir:应将生成的源存储在的位置。 默认为生成目录内生成的源文件夹( build/generated/source/greendao)。
generateTests: 设置为true以自动生成单元测试
targetGenDirTests: 应将生成的单元测试存储在的基本目录。默认为 src/androidTest/java.。
public class GreenDaoManager {
private static GreenDaoManager sInstance;
private final DaoSession mDaoSession;
public static GreenDaoManager getInstance() {
if (sInstance == null) {
synchronized (GreenDaoManager.class) {
sInstance = new GreenDaoManager();
}
}
return sInstance;
}
private GreenDaoManager() {
DaoMaster.OpenHelper helper = new MyOpenHelper(BaseApplication.getApplication(), "greendao_user.db");
Database db = helper.getWritableDb();
mDaoSession = new DaoMaster(db).newSession();
}
public GreenDaoUserEntityDao getUserEntityDao() {
return mDaoSession.getGreenDaoUserEntityDao();
}
// 通过GreenDaoUserEntityDao进行crud操作
public void insertAllUsers(List<GreenDaoUserEntity> lists) {
if (lists != null) {
for (GreenDaoUserEntity userEntity : lists) {
getUserEntityDao().insert(userEntity);
}
}
}
public List<GreenDaoUserEntity> queryUsersByName(String name) {
return getGreenDaoUserEntityDao().queryBuilder().where(GreenDaoUserEntityDao.Properties.Name.eq(name)).list();
}
}