IT

Room Persistence lib의 기본 키를 자동 증분으로 만드는 방법

lottoking 2020. 6. 22. 07:30
반응형

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,
        "","","","")
}

참고URL : https://stackoverflow.com/questions/44109700/how-to-make-primary-key-as-autoincrement-for-room-persistence-lib

반응형