I was playing with Room, where I couldn't find some solution to my queries.
Below is the data.
Table
CREATE TABLE `Employee` (
`id` INTEGER NOT NULL,
`first_name` TEXT,
`last_name` TEXT,
PRIMARY KEY(`id`)
);
Table Data
Entity
@Entity(tableName = "Employee")
public class Employee {
@PrimaryKey
private int id;
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;
..Getters & Setters..
}
Query 1
@Query("Select * from Employee")
List<Employee> getEmployees();
Result Its successfull
Query 2
@Query("Select first_name, last_name from Employee")
List<Employee> getEmployees();
Result
error: The columns returned by the query does not have the fields [id] in ***.Employee even though they are annotated as non-null or primitive. Columns returned by the query: [first_name, last_name]
If I add id
to above Query 2
, it works.
Same goes, if we have a Foreign Key
in the Table and we try to Query Subset of Columns, it throws Error. The Error goes when we add both Primary Key
& Foreign Key
Column in the Query.
Question 1
Does that mean we have to always include Primary Key
& Foreign Key
(if present) in a Query ?
Question 2 What actually happens under the hood that it throws such error ? Or Am I doing anything wrong ?
Room Version 1.1.1
Also, referred this link but it doesn't solve my issue with Primary Keys.
If nothing is found based on your criteria, it will return null.
In the Options menu, select Clear all data. All words should disappear. Restart the app. (Restart it from your device or the emulator; don't run it again from Android Studio) You should see the initial set of words.
When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.
initializeWithDefaults(this) in your Application and view your database using the chrome inspect tool. Enter the following in your chrome URL bar: chrome://inspect . Presto! You can see your Room database .
To select data from multiple fields consider below example.
From the docs
Room allows you to return any Java-based object from your queries as long as the set of result columns can be mapped into the returned object. For example, you can create the following plain old Java-based object (POJO) to fetch the user's first name and last name:
public class NameTuple {
@ColumnInfo(name = "first_name")
public String firstName;
@ColumnInfo(name = "last_name")
public String lastName;
}
Now, you can use this POJO in your query method:
@Dao
public interface MyDao {
@Query("SELECT first_name, last_name FROM user")
public List<NameTuple> loadFullName();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With