1

This is SQLite query i want to use in room database here is the first to try insert data and if data is already exist then update the data by using id

INSERT INTO books(id, title, author, year_published)  VALUES(@id, @title, @author, @year_published)
 ON DUPLICATE KEY UPDATE title = @title,  author = @author;
hio
  • 915
  • 8
  • 26

2 Answers2

0

Room supports @RawQuery annotation to construct queries at run-time. So you need:

@Dao
interface BooksDao{
    @RawQuery
    List<Book> books(SupportSQLiteQuery query);
}

And create your query in old school style:

String queryString = "here is your query";
List<Object> args = new ArrayList(); // here is your args for your query

And ther performe your query:

SimpleSQLiteQuery query = new SimpleSQLiteQuery(queryString, args.toArray());
List<Book> result = booksDao.books(query);
0

You can achieve this with OnConflictStrategy.REPLACE

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertBooks(vararg books: Book)

And you have to specify the id id as primary key

@Entity(tableName = "book_table")
data class Book(
    @PrimaryKey val id: String,
    val title: String,
    val author: String,
    val year_published: Int
)