一、引入依赖
//room
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
二、创建数据库实体
@Entity
public class User {
@PrimaryKey(autoGenerate = true)
@NonNull
public int id;
@ColumnInfo(name = "user_name", defaultValue = "")
public String userName;
@ColumnInfo(name = "user_age")
public int userAge;
@ColumnInfo(name = "nick_name")
public String nickName;
@ColumnInfo(name = "address")
public String address;
public User(String userName, int userAge, String nickName, String address) {
this.userName = userName;
this.userAge = userAge;
this.nickName = nickName;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
三、创建Dao接口
@Dao
public interface UserDao {
/**
* 增加
*
* @param users 用户
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertUser(User... users);
/**
* 查询所有用户
* @return 用户列表
*/
@Query("SELECT * FROM user")
List<User> queryAll();
/**
* 按用户名查询
* @param userName 用户名
* @return 用户
*/
@Query("SELECT * FROM user WHERE user_name LIKE :userName LIMIT 1")
User findByName(String userName);
/**
* 修改
* @param users 根据用户进行修改
*/
@Update
void update(User... users);
/**
* 删除
* @param users 根据用户进行删除
*/
@Delete
void delete(User... users);
}
四、创建 MyDatabase
@Database(entities = {User.class}, version = 1,exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
五、activity或者Fragment
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
private MyDatabase db;
private List<User> mList = new ArrayList<>();
private UserAdapter mAdapter;
private Button btn_add;
private Button btn_delete;
private Button btn_update;
private Button btn_query;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
initView();
}
/**
* 初始化
*/
private void initView() {
btn_add= findViewById(R.id.btn_add);
btn_delete= findViewById(R.id.btn_delete);
btn_update= findViewById(R.id .btn_update);
btn_query= findViewById(R.id.btn_query);
//列表
RecyclerView rv = findViewById(R.id.rv);
mAdapter = new UserAdapter(R.layout.item_rv, mList);
rv.addItemDecoration(new DividerItemDecoration(this, VERTICAL));
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setAdapter(mAdapter);
//初始化数据库
initDB();
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//添加用户
addUser();
}
});
btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//删除用户
deleteUser();
}
});
btn_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//修改用户
updateUser();
}
});
btn_query.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//查询所有用户
queryAll();
}
});
}
/**
* 初始化数据库
*/
private void initDB() {
Room.inMemoryDatabaseBuilder(getApplicationContext(), MyDatabase.class);
//本地持久化数据库
db = Room.databaseBuilder(getApplicationContext(), MyDatabase.class, "DemoDB")
//是否允许在主线程上操作数据库,默认false。
.allowMainThreadQueries()
//数据库创建和打开的事件会回调到这里,可以再次操作数据库
.addCallback(new CallBack())
.build();
}
/**
* 增加用户
*/
private void addUser() {
runOnUiThread(() -> {
db.userDao().insertUser(new
User("张三", 20, "aaa", "从网上")
);
Toast.makeText(MainActivity.this, "增加成功", Toast.LENGTH_SHORT).show();
});
}
/**
* 删除用户
*/
private void deleteUser() {
runOnUiThread(() -> {
User user = db.userDao().findByName("张三");
if (user == null) return;
db.userDao().delete(user);
Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
});
}
/**
* 修改用户
*/
private void updateUser() {
runOnUiThread(() -> {
User user = db.userDao().findByName("李四");
if (user == null) return;
user.setUserName("赵四");
user.setUserAge(10);
user.setNickName("尼古拉斯.赵四");
user.setAddress("中国东北");
db.userDao().update(user);
Toast.makeText(MainActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
});
}
/**
* 查询所有用户
*/
private void queryAll() {
runOnUiThread(() -> {
mList.clear();
mList.addAll(db.userDao().queryAll());
mAdapter.notifyDataSetChanged();
});
}
static class CallBack extends RoomDatabase.Callback {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
Log.d(TAG, "db create");
}
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
Log.d(TAG, "db open");
}
}
}
运行效果:
Dome链接: