@Entity
public class User {
@PrimaryKey
public int userId;
public String name;
}
@Entity
public class Book {
@PrimaryKey
public int bookId;
public String title;
@ForeignKey(entity = User.class, parentColumns = "userId", childColumns = "bookId")
public int userId;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE User (userId INTEGER PRIMARY KEY, name TEXT)");
db.execSQL("CREATE TABLE Book (bookId INTEGER PRIMARY KEY, title TEXT, userId INTEGER, FOREIGN KEY(userId) REFERENCES User(userId))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
db.execSQL("ALTER TABLE Book ADD COLUMN userId INTEGER");
db.execSQL("UPDATE Book SET userId=(SELECT userId FROM User WHERE name='default') WHERE userId IS NULL");
db.execSQL("CREATE INDEX index_Book_userId ON Book(userId)");
db.execSQL("FOREIGN KEY(userId) REFERENCES User(userId) ON DELETE CASCADE");
}
}
以上步骤可以确保在更新表结构和数据库版本时不会破坏外键约束。