ORMLite Foreign抽象类的集合

时间:2016-12-07 15:35:57

标签: java android foreign-keys abstract-class ormlite

我有4个班级:

@DatabaseTable(tableName = "bucket")
public class Bucket {
    ...
    @ForeignCollectionField(eager = true)
    private Collection<Good> goods;
    ...
}

public abstract class Good {
    ...
    @DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
    private Bucket bucket;
    ...
}

@DatabaseTable(tableName = "bread")
public class Bread extends Good {
    ...
}

@DatabaseTable(tableName = "milk")
public class Milk extends Good {
    ...
}

因此,在Bucket内,我有ForeignCollectionField抽象类Good,当然,它没有自己的数据库表。

数据库条目是正常创建的,但是当我尝试调用queryForAll()时,它会给我错误:

bucketDao.queryForAll(); 
// no such table: good (code 1): , while compiling: SELECT * FROM `basecard` WHERE `bucket_id` = ?

有没有办法解决这个问题?
或者我甚至无法创建抽象类的ForeignCollectionField?

1 个答案:

答案 0 :(得分:1)

我发现解决这个问题非常简单。

我刚从@ForeignCollectionField模型中删除了Bucket。因此,Inside Bucket表ORMLite对Good实体一无所知。

坚持数据:

// 1 using bucketDao add bucket
bucketDao.add(bucket)
// 2 iterate over collection
for (Bread bread: breadList) {
  bread.setBucket(bucket); // set current bucket to good item
  breadDao.add(bread); // using breadDao add bread
}
// 3 do the same with milk collection
for (Milk milk: milkList) {
  milk.setBucket(bucket);
  milkDao.add(milk);
}

加载数据:

int bucketId = 1; // for example working with bucket with id=1
Bucket bucket = bucketDao.queryForEq("id", bucketId)); // query for this bucket
List<Milk> milkList = milkDao.queryForEq("bucket_id", bucketId); // query for all milks, that has a foreign key to current bucket
List<Break> breadList = breadDao.queryForEq("bucket_id", bucketId); // the same for bread

// finally set milks and breads to Good collection inside Bucket
List<Good> goodList = new ArrayList<>();   
goodList.addAll(milkList);   
goodList.addAll(breadList);   
bucket.setGoods(goodList);