想要学习新东西,个人建议从JetPack入手还是挺不错的,这套组件库里面基本包含了目前最前沿的技术点,奥里给!
通过 @Query 注解可以去动态自己编写需要的SQL语句,非常实惠!
别忘了 红框框内的符号哦~~~~~~~~~~~
这里不多说废话,直接上代码,个人亲测能跑!
def room_version = "2.2.0-alpha01"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
@Dao
public interface StudentDao
{
//插入数据
@Insert
void insertStudent(Student student);
//根据插入数据去删除数据
@Delete
void deleteStudent(Student student);
//更新数据
@Update
void updateStudent(Student student);
//查询所有数据
@Query("SELECT * FROM student")
List<Student> getStudentList();
//根据id去查询数据
@Query("SELECT * FROM student WHERE id = :id")
Student getStudentById(int id);
//删除全部数据
@Query("DELETE FROM student")
void deleteAll();
//根据id去删除相对应的数据
@Query("delete from student where id= :id")
void deleteID(int id);
}
@Entity(tableName = "student")
public class Student
{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id", typeAffinity = ColumnInfo.INTEGER)
public int id;
@ColumnInfo(name = "name", typeAffinity = ColumnInfo.TEXT)
public String name;
@ColumnInfo(name = "age", typeAffinity = ColumnInfo.TEXT)
public String age;
/**
* Room会使用这个构造器来存储数据,也就是当你从表中得到Student对象时候,Room会使用这个构造器
* */
public Student(int id, String name, String age)
{
this.id = id;
this.name = name;
this.age = age;
}
/**
* 由于Room只能识别和使用一个构造器,如果希望定义多个构造器,你可以使用Ignore标签,让Room忽略这个构造器
* 同样,@Ignore标签还可用于字段,使用@Ignore标签标记过的字段,Room不会持久化该字段的数据
* */
@Ignore
public Student(String name, String age)
{
this.name = name;
this.age = age;
}
}
@Database(entities = {Student.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
private static final String DATABASE_NAME = "my_db";
private static MyDatabase databaseInstance;
public static synchronized MyDatabase getInstance(Context context) {
if (databaseInstance == null) {
databaseInstance = Room
.databaseBuilder(context.getApplicationContext(), MyDatabase.class, DATABASE_NAME)
.build();
}
return databaseInstance;
}
public abstract StudentDao studentDao();
}
public class MainActivity extends AppCompatActivity {
private MyDatabase myDatabase;
private Student student;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDatabase = MyDatabase.getInstance(getApplicationContext());
new Thread(new Runnable() {
@Override
public void run() {
//myDatabase.studentDao().deleteAll();
student = new Student("狗蛋","18");
myDatabase.studentDao().insertStudent(student);
//myDatabase.studentDao().insertStudent(new Student("三狗","20"));
//myDatabase.studentDao().deleteStudent(student);
//myDatabase.studentDao().deleteID(29);
List<Student> studentList = myDatabase.studentDao().getStudentList();
MainActivity.this.student = myDatabase.studentDao().getStudentById(30);
((TextView) findViewById(R.id.tv_txt)).setText(MainActivity.this.student.name);
}
}).start();
}
}