这是sqlite查询,我想要此房间数据库 这里首先尝试插入数据(如果数据存在),然后使用id更新数据
INSERT INTO books(id, title, author, year_published) VALUES(@id, @title, @author, @year_published)
ON DUPLICATE KEY UPDATE title = @title, author = @author;
答案 0 :(得分:0)
Room支持@RawQuery批注以在运行时构造查询。所以你需要:
@Dao
interface BooksDao{
@RawQuery
List<Book> books(SupportSQLiteQuery query);
}
并以旧学校风格创建查询:
String queryString = "here is your query";
List<Object> args = new ArrayList(); // here is your args for your query
然后执行您的查询:
SimpleSQLiteQuery query = new SimpleSQLiteQuery(queryString, args.toArray());
List<Book> result = booksDao.books(query);
答案 1 :(得分:0)
您可以通过 OnConflictStrategy.REPLACE
实现此目标@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertBooks(vararg books: Book)
并且您必须将ID id 指定为主键
@Entity(tableName = "book_table")
data class Book(
@PrimaryKey val id: String,
val title: String,
val author: String,
val year_published: Int
)