我正在RoomDatabase
上执行SQL INSERT语句。
使用RoomDatabase.query()
进行相同操作。但是,除非我在返回的cursor
上调用任何函数,否则插入的行不会提交到数据库 -
@Entity
public class Person {
@PrimaryKey
@NonNull
private String uuid;
@Embedded
@NonNull
private Address address;
public Person(@NonNull String uuid, @NonNull Address address) {
this.uuid = uuid;
this.address = address;
}
@NonNull
public String getUuid() {
return uuid;
}
@NonNull
public Address getAddress() {
return address;
}
}
public class Address {
@NonNull
private String street;
@NonNull
private String city;
public Address(String street, String city) {
this.street = street;
this.city = city;
}
@NonNull
public String getStreet() {
return street;
}
@NonNull
public String getCity() {
return city;
}
}
@Dao
public interface PersonDao {
@Query("SELECT * FROM Person")
List<Person> getPersons();
}
@TypeConverters(DateConverter.class)
@Database(entities = {Person.class}, version = 1, exportSchema = false)
public abstract class PersonDb extends RoomDatabase {
private static volatile PersonDb INSTANCE;
public abstract PersonDao getPersonDao();
public static PersonDb getInstance(Context context) {
if (INSTANCE == null) {
synchronized (PersonDb.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
PersonDb.class, "persons.db")
.allowMainThreadQueries()
.build();
}
}
}
return INSTANCE;
}
}
这是我的测试用例 -
@RunWith(AndroidJUnit4.class)
public class PersonsIssueTest {
private final static String TAG = PersonsIssueTest.class.getSimpleName();
private PersonDb mDb;
private SimpleSQLiteQuery personsInsertQuery =
new SimpleSQLiteQuery("INSERT INTO Person (uuid, street, city) " +
"VALUES ('1', 'lane', 'york')");
@After
public void closeDb() throws IOException {
mDb.close();
}
@Test
public void insertQueryTest() {
Context context = InstrumentationRegistry.getTargetContext();
Cursor c;
mDb = PersonDb.getInstance(context);
PersonDao dao = mDb.getPersonDao();
List<Person> persons = dao.getPersons();
Log.d(TAG, "> number of persons " + persons.size() + " rows");
Log.d(TAG, "> running: " + personsInsertQuery.getSql());
c = mDb.query(personsInsertQuery);
/* If I comment the next statement, number of persons returned is 0 in the following dao.getPersons() */
c.moveToFirst();
c.close();
persons = dao.getPersons();
Log.d(TAG, "> number of persons " + persons.size() + " rows");
assertEquals(1, persons.size());
}
}
如果我评论c.moveToFirst()
,则以下dao.getPersons()
这里有任何问题吗?
答案 0 :(得分:-1)
Room提供了一个内置插入方法,您可以按如下方式设置
@Dao
public interface PersonDao {
@Query("SELECT * FROM Person")
List<Person> getPersons();
@Insert
void insertPersonData(Person person);
}
现在您创建一个人物实例,填充其值并使用
插入 dao.insertPersonData(personObject);