问题
I need to write an app that uses date as id, and I must be able to update just by comparing date
@Entity
data class DailyCount(@PrimaryKey
var date:DateTime,
var summ: Double = 0.0)
And here is the DAO
@Query("update DailyCount set summ = :sum where date = :today")
fun updateCash(today: DateTime, sum: Double)
I want to make like this :
@Entity
data class DailyCount(@PrimaryKey
var date:Date,//JodaTime containing only date
var summ: Double = 0.0)
Or like this:
@Query("update DailyCount set summ = :sum where date.today = :dateArg.today")
fun updateCash(dateArg: DateTime, sum: Double)
回答1:
Room doesn't know how to save your primary field DateTime
into database.
You need to write a TypeConverter.
public class TypeConverter {
private static Gson gson = new Gson();
@TypeConverter
public static DateTime stringToDate(String data) {
Type type = new TypeToken<DateTime>() {
}.getType();
return gson.fromJson(data, type);
}
@TypeConverter
public static String dateToString(DateTime dateTime) {
return gson.toJson(dateTime);
}
}
Then annotate your primary key
@PrimaryKey
@TypeConverters(TypeConverter::class.java)
var date:DateTime
回答2:
I was needed to write this query :
@Query("update DailyCount set summ = :sum where date between :startTimeOfDay and :endTimeOfDay")
fun updateCash(startTimeOfDay: DateTime, endTimeOfDay: DateTime, sum: Double)
I gave here a range with start and end time. This approach returns true when I want to set info in today's Id
来源:https://stackoverflow.com/questions/56051963/how-to-use-joda-datetime-date-as-id-in-room-or-how-to-get-date-in-query