@PrimaryKey(autoGenerate = true) private int uid; @ColumnInfo(name = "first_name") private String firstName; @ColumnInfo(name = "last_name") private String lastName; // Getters and setters are ignored for brevity, // but they're required for Room to work. }
{ @Query("SELECT * FROM user") List<User> getAll(); @Query("SELECT * FROM user WHERE uid IN (:userIds)") List<User> loadAllByIds(int[] userIds); ▶ @Query("SELECT * FROM user WHERE uid IN (:userIds)") LiveData<List<User>> loadAllByIds(int[] userIds); ……
WHERE first_name LIKE :first AND last_name LIKE :last LIMIT 1") User findByName(String first, String last); @Insert void insertAll(User... users); @Delete void delete(User user); ▶ @Update int update(User user); }
relational data. • The class that's annotated with @Database should satisfy the following conditions: • Abstract class that extends RoomDatabase. • Include the list of entities associated with the database within the annotation. • Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.
thread • java.lang.IllegalStateException ▶ Cannot access database on the main thread since it may potentially lock the UI for long period of time. • to allow queries on the main thread. Don't do this on a real app! • MyApp.database = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "user-database") .allowMainThreadQueries() .build();
Looks like you’ve changed schema but forgot to update the version number. You can simply fix this by increasing the version number. • A migration from 1 to 2 is necessary. Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables. • Two Solutions : 1) Drop and recreate the whole database. 2) Upgrade existing database schema to the newer version.
RepoDatabase.class, DB_NAME) .fallbackToDestructiveMigration() .build(); • Allows Room to destructively recreate database tables if Migrations that would migrate old database schemas to the latest schema version are not found. • Note that this will delete all of the data in the database tables managed by Room.
• It makes you verify your database code during compile time. • It makes your code more modular and readable as you divide your database code in three components like Entity ,DAO and Database.
• Persisting Data with Room on Android - Orlando Android (https://www.youtube.com/watch?v=9xdtVdO-XAA) • Medium : SQLite Made Easy : Room Persistence Library ▶ (https://medium.com/mindorks/sqlite-made-easy-room-persistence-library-ecd1a5bb0a2c) References