Room Persistence lib의 기본 키를 자동 증분으로 만드는 방법
foodId
자동 증가 로 만들고 싶은 Entity (Room Persistence lib) 클래스 Food를 만들고 있습니다.
@Entity
class Food(var foodName: String, var foodDesc: String, var protein: Double, var carbs: Double, var fat: Double)
{
@PrimaryKey
var foodId: Int = 0
var calories: Double = 0.toDouble()
}
foodId
자동 증분 필드는 어떻게 설정 합니까?
당신은 autoGenerate
속성 을 사용해야합니다
기본 키 주석은 다음과 같아야합니다.
@PrimaryKey(autoGenerate = true)
여기 참조
다음 @PrimaryKey(autoGenerate = true)
과 같이 추가 할 수 있습니다 .
@Entity
data class Food(
var foodName: String,
var foodDesc: String,
var protein: Double,
var carbs: Double,
var fat: Double
){
@PrimaryKey(autoGenerate = true)
var foodId: Int = 0 // or foodId: Int? = null
var calories: Double = 0.toDouble()
}
더하다 @PrimaryKey(autoGenerate = true)
@Entity
public class User {
public User(int id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "full_name")
private String name;
@ColumnInfo(name = "phone")
private String phone;
}
데이터를 저장하는 동안
db.userDao().InsertAll(new User(0,sName,sPhone));
객체 (내 경우 사용자 객체)를 만드는 동안 id에 0을 넣으십시오.
필드 유형이 long 또는 int이거나 TypeConverter가 long 또는 int로 변환하는 경우 Insert 메서드는 항목을 삽입하는 동안 0을 설정되지 않은 것으로 간주합니다.
If the field's type is Integer or Long (Object) (or its TypeConverter converts it to an Integer or a Long), Insert methods treat null as not-set while inserting the item.
For example, if you have a users
entity you want to store, with fields (firstname, lastname , email)
and you want autogenerated id, you do this.
@Entity(tableName = "users")
data class Users(
@PrimaryKey(autoGenerated = true)
val id: Long,
val firstname: String,
val lastname: String,
val email: String
)
Room will then autogenerate and auto-increment the id
field.
@Entity(tableName = "user")
data class User(
@PrimaryKey(autoGenerate = true) var id: Int?,
var name: String,
var dob: String,
var address: String,
var gender: String
)
{
constructor():this(null,
"","","","")
}
'IT' 카테고리의 다른 글
특정 위치에서 문자열에 문자를 삽입하는 방법은 무엇입니까? (0) | 2020.06.22 |
---|---|
“전체 화면” (0) | 2020.06.22 |
Flask / Jinja2를 사용하여 HTML을 템플릿으로 전달 (0) | 2020.06.22 |
OnFragmentInteractionListener를 구현하는 방법 (0) | 2020.06.22 |
Objective-C에서 NSString의 대소 문자를 대문자로 바꾸거나 변경 (0) | 2020.06.22 |