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
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(); } public void insertAllUsers(List<GreenDaoUserEntity> lists) { if (lists != null) { for (GreenDaoUserEntity userEntity : lists) { getUserEntityDao().insert(userEntity); } } } }