我正在使用Room持久性库开发Android应用程序.我有一个User和一个Car实体
@Entity(tableName = "users")
public class User {
@PrimaryKey
@NonNull
private int id;
private String name;
public User(@NonNull int id, String name) {
this.id = id;
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
和
@Entity(tableName = "cars", foreignKeys = @ForeignKey(parentColumns =
"id", childColumns = "userId", entity = User.class))
public class Car {
@PrimaryKey(autoGenerate = true)
private int id;
private int userId;
private String brand;
public Car(int userId, String brand) {
this.userId = userId;
this.brand = brand;
}
}
Run Code Online (Sandbox Code Playgroud)
我还创建了一个UserWithCar类,如下所示:
public class UserWithCar …Run Code Online (Sandbox Code Playgroud) 我有两个具有外键关系的实体:product和category。
@Entity(primaryKeys = "id")
public class Product {
public final long id;
@NonNull
public final String name;
@ForeignKey(entity = Category.class, parentColumns = "id", childColumns = "categoryId")
public final long categoryId;
public Product(long id, @NonNull String name, long categoryId) {
this.id = id;
this.name = name;
this.categoryId = categoryId;
}
}
@Entity(primaryKeys = "id")
public class Category {
public final long id;
@NonNull
public final String name;
public Category(long id, @NonNull String name) {
this.id = id; …Run Code Online (Sandbox Code Playgroud) 我有一个 PostDAO,看起来像这样。
@Dao
public interface PostDAO extends DAOTemplate<Post> {
@Query("SELECT * FROM posts order by time DESC")
LiveData<List<Post>> getPosts();
}
Run Code Online (Sandbox Code Playgroud)
还有 Post Pojo 存在。
@Keep
@Entity(tableName = "posts")
open class Post : Serializable, Cloneable {
@NonNull
@PrimaryKey
var id: String? = null
var text: String? = null
var time: Long = 0
var uid: String? = null
@Embedded
var user: User? = null
public override fun clone(): Post {
return super.clone() as Post
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,User对象是@Embedded
和用户的 …
java android kotlin android-room android-architecture-components