Java 防止在RealmList中保存时创建领域对象
我有两个模型类,Product和StoreTransaction,如下所示 Product.ktJava 防止在RealmList中保存时创建领域对象,java,android,kotlin,realm,realm-list,Java,Android,Kotlin,Realm,Realm List,我有两个模型类,Product和StoreTransaction,如下所示 Product.kt open class Product( var barcode: String? = null, var name: String? = null, var price: Double? = null, var quantity: Double? = null ) : RealmObject() StoreTransaction.kt open class Stor
open class Product(
var barcode: String? = null,
var name: String? = null,
var price: Double? = null,
var quantity: Double? = null
) : RealmObject()
StoreTransaction.kt
open class StoreTransaction(
var date: Date? = null,
var productList: RealmList<Product>? = null
// and other variables below
) : RealmObject()
开放类StoreTransaction(
变量日期:日期?=null,
var productList:RealmList?=null
//以及下面的其他变量
):RealmObject()
这里我们有3种产品,产品A、B和C,数量相同,每种5件
然后我购买产品A和C各2件,并像这样保存交易
fun saveTransaction(toBuyList: ArrayList<Product>, realm: Realm) {
val date = Date()
val productList = RealmList<Product>()
productList.addAll(toBuyList.toList())
// other variables
val st = StoreTransaction(date, productList // other vars)
realm.executeTransaction {
realm.copyToRealm(st)
// update stock quantity
toBuyList.forEach { itemToBuy ->
val product = realm.where(Product::class.java)
.equalTo("barcode", itemToBuy.barcode).findFirst()
product?.quantity = product?.quantity?.minus(itemToBuy.quantity!!)
}
}
}
fun saveTransaction(toBuyList:ArrayList,realm:realm){
val date=日期()
val productList=RealmList()
productList.addAll(toBuyList.toList())
//其他变量
val st=StoreTransaction(日期、产品列表//其他变量)
realm.executeTransaction{
realm.copyToRealm(st)
//更新库存数量
toBuyList.forEach{itemToBuy->
val product=realm.where(product::class.java)
.equalTo(“条形码”,itemToBuy.barcode).findFirst()
产品?数量=产品?数量?减(itemToBuy.quantity!!)
}
}
}
当我查询回我的产品时,我得到了以下结果
旁注:我目前的解决方案是将StoreTransaction中的productList属性更改为字符串(通过使用Gson)作为临时属性。它工作得很好,但如果有更好的方法来处理这个问题,我会很好奇。在条形码上使用@PrimaryKey注释
public class TestObj extends RealmObject {
@PrimaryKey
private String code;
}
就像我用Java做的一样
基本上,对象需要有一个主键来更新数据库中现有的对象是的,我试过了,但对我的情况没有好处。问题是我必须保存这些已售出的产品列表,以便以后报告。