Room是Google官方的数据库框架,在SQLite上提供了一个抽象层,以便在利用SQLite的全部功能的同时能更加流畅的访问数据库。
优点是:
1.减少了代码量
2.谷歌官方提供的,更加安全可靠
具体使用方法:
build.gradle
implementation "androidx.room:room-runtime:latest.release"
annotationProcessor "androidx.room:room-compiler:latest.release"
User.java
package com.jxd.studyone.room;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class User {
@PrimaryKey(autoGenerate = true)
public int uid;
@ColumnInfo(name = "name")
public String name;
@ColumnInfo(name = "pwd")
public String password;
}
UserDao.java
package com.jxd.studyone.room;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
@Query("SELECT * FROM user WHERE name LIKE :first AND name LIKE :last LIMIT 1")
User findByName(String first, String last);
@Insert
void insertAll(User... users);
@Delete
void delete(User user);
}
AppDatabase.java
package com.jxd.studyone.room;
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = {User.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
调用方式:
package com.jxd.studyone.room;
import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import com.jxd.studyone.R;
import java.util.List;
import java.util.concurrent.Executors;
public class RoomActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
initData();
}
private void initData() {
//对数据库进行迁移。
Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE `user_t` (`uid` INTEGER PRIMARY KEY autoincrement ,`name` TEXT,`pwd` TEXT)");
database.execSQL("INSERT INTO `user_t` (`name` , `pwd`) SELECT `name`, `pwd` FROM `user`");
database.execSQL("DROP TABLE `user`");
database.execSQL("ALTER TABLE `user_t` RENAME TO `user`");
}
};
//初始化数据库
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name")
.addMigrations(MIGRATION_1_2).build();
Executors.newSingleThreadExecutor().submit(() -> {
User u = new User();
u.name = "jxdzs";
u.password = "13662";
db.userDao().insertAll(u);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<User> userList = db.userDao().getAll();
for (User user:userList){
Log.d("room_tag",user.uid+" "+user.name+" "+user.password);
}
});
}
}