当前位置:网站首页>room数据库的使用
room数据库的使用
2022-07-05 05:13:00 【菜鸟xiaowang】
1.导包
implementation "androidx.room:room-runtime:2.4.2" annotationProcessor "androidx.room:room-compiler:2.4.2"
2.gradle中配置
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}3.创建数据对象实体
@Entity
public class User {
@PrimaryKey(autoGenerate = true)
long userId;
@ColumnInfo(name = "username")
String userName;
@ColumnInfo(name = "password")
String password;
public User(@NonNull String userName,@NonNull String password){
this.userName = userName;
this.password = password;
}
}4.创建对应的Dao
@Dao
public interface UserDao {
@Insert
void addUser(User ... user);
@Delete
int deleteUser(User user);
@Update
int updateUser(User user);
@Query("SELECT * FROM user WHERE userID = :id")
User queryUser(long id);
}5.创建数据库
//exportSchema = true 支持导出Room生成的配置文件
@Database(entities = {User.class},version = 3,exportSchema = true)
public abstract class MyRoomDatabase extends RoomDatabase {
public static String roomName = "user";
public static MyRoomDatabase instance;
public abstract UserDao getUserDao();
public static MyRoomDatabase getInstance(Context context){
if (instance == null){
synchronized (MyRoomDatabase.class){
if (instance == null){
instance = Room.databaseBuilder(context,MyRoomDatabase.class,roomName).allowMainThreadQueries().build();
}
}
}
return instance;
}
}6.调用
MyRoomDatabase.getInstance(this).getUserDao().addUser(new User("wang","lllll"));边栏推荐
- cocos2dx_ Lua particle system
- Django reports an error when connecting to the database. What is the reason
- AutoCAD - Center zoom
- xftp7与xshell7下载(官网)
- MD5 bypass
- Unity card flipping effect
- Detailed explanation of the ranking of the best universities
- Reverse one-way linked list of interview questions
- GameObject class and transform class of unity
- 2020-10-27
猜你喜欢

Merge sort

Unity3d learning notes

AutoCAD - command repetition, undo and redo

C4D simple cloth (version above R21)

Embedded database development programming (VI) -- C API

Applet Live + e - commerce, si vous voulez être un nouveau e - commerce de détail, utilisez - le!

UE fantasy engine, project structure

669. Prune binary search tree ●●

stm32Cubemx(8):RTC和RTC唤醒中断

AutoCAD - window zoom
随机推荐
Redis 排查大 key 的4种方法,优化必备
2022/7/1学习总结
Establish cloth effect in 10 seconds
嵌入式数据库开发编程(六)——C API
Listview is added and deleted at the index
Common technologies of unity
Personal required code
Do a small pressure test with JMeter tool
GameObject class and transform class of unity
2022/7/1 learning summary
2021-10-29
2020-10-27
AutoCAD - Zoom previous
《动手学深度学习》学习笔记
Grail layout and double wing layout
Lua determines whether the current time is the time of the day
Cocos2dx Lua registers the touch event and detects whether the click coordinates are within the specified area
Unity check whether the two objects have obstacles by ray
win10虚拟机集群优化方案
3dsmax2018 common operations and some shortcut keys of editable polygons