5

总的来说,我对 Android 开发还很陌生,而且我什至从未使用过 greenDAO。但是在花了很多时间研究我的生成器类(我在其中建模我的实体)之后,我终于能够生成一些看起来类似于 GitHub 上给出的示例的东西。

import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Property;
import de.greenrobot.daogenerator.Schema;
import de.greenrobot.daogenerator.ToMany;


public class simbalDAOgen {

public static void main(String[] args) throws Exception {
    Schema schema = new Schema(1, "com.bkp.simbal"); //Schema(Int version, String package name)
    addCBTrans(schema); //Add the entities to the schema
    new DaoGenerator().generateAll(schema, "../Simbal/src-gen", "../Simbal/src-test"); //Generate DAO files
}

private static void addCBTrans(Schema schema){
    Entity checkbook = schema.addEntity("Checkbook");
    checkbook.addIdProperty();
    checkbook.addStringProperty("name").notNull();
    checkbook.addDateProperty("dateModified");
    checkbook.addStringProperty("balance"); // Use a string property because BigDecimal type should be used for currency

    Entity transaction = schema.addEntity("Transaction");
    transaction.setTableName("TRANS"); // "TRANSACTION" is a reserved SQLite keyword
    transaction.addIdProperty();
    transaction.addStringProperty("name");
    transaction.addStringProperty("category");
    Property transDate = transaction.addDateProperty("date").getProperty();
    transaction.addStringProperty("amount"); // Again use string for BigDecimal type
    transaction.addStringProperty("notes");
    Property cbName = transaction.addStringProperty("cb").notNull().getProperty(); //What checkbook the transaction is in

    ToMany cbToTrans = checkbook.addToMany(transaction, cbName); //Actually ties the transactions to their correct checkbooks
    cbToTrans.setName("Transactions");
    cbToTrans.orderAsc(transDate);
}       
}

然后,我将代码作为 java 应用程序运行以生成我的 DAO 文件,就像 greenDAO 上的文档所说的那样。文件已成功生成,但是我在 Eclipse 的控制台中确实得到了这一行:

Warning to-one property type does not match target key type: ToMany 'Transactions' from Checkbook to Transaction

由于文件已生成,我真的不确定是否需要担心。但我不明白的是,当我使用“对多”关系时,为什么会提到“一对一”关系,正如我的代码中所见。(支票簿实体中可以有许多交易实体,我打算使用每个支票簿实体的名称将交易与它联系起来。)

我需要返回并修复我的部分代码吗?请询问我是否需要澄清任何事情,并感谢您的时间!

4

2 回答 2

7

查看 greenDAO 为我生成的文件后,我找到了解决问题的方法。在我看来, addToMany() 方法期望将 Long 属性传递给它,而我使用的是 String 属性。所以我在生成器代码中更改了这两行:

Property cbName = transaction.addStringProperty("cb").notNull().getProperty();

ToMany cbToTrans = checkbook.addToMany(transaction, cbName);

对此:

Property checkbookId = transaction.addLongProperty("checkbookId").notNull().getProperty();

ToMany cbToTrans = checkbook.addToMany(transaction, checkbookId);

这解决了我的问题。我的印象是我可以使用任何类型的属性将交易与支票簿联系起来,所以我尝试使用支票簿名称。

于 2013-04-10T19:55:32.427 回答
0

似乎 GreenDao 只接受类型 Long 作为外键

于 2016-03-15T14:40:38.867 回答