【问题标题】:How do I properly annotate inheritance classes using ORMLite?如何使用 ORMLite 正确注释继承类?
【发布时间】:2012-04-24 00:31:33
【问题描述】:

我正在尝试将继承与 ORMLite 一起使用,但通过查看文档和谷歌搜索,我无法确定它是否受支持。

我想做的是拥有

public abstract class Person{
   public int id;
   public String name;
}

public class Student extends Person{
   public String school;
    public String year;
    //  other student stuff
}

public class Teacher extends Person{
   public String title;
    // other teacher stuff
}

我无法解决(假设它受支持)是如何为 ORMLite 注释 3 个类。

我只需要用@DatabaseTable(tableName = "Student")注释具体类还是我也需要抽象类?

我不断收到如下错误:

04-24 10:18:30.857: E/AndroidRuntime(30495): Caused by: java.lang.RuntimeException: java.sql.SQLException: Unknown field 'name' from the Android sqlite cursor, not in:[year , 学校]

【问题讨论】:

    标签: android sqlite inheritance ormlite


    【解决方案1】:

    @DatabaseTable 注释仅在 StudentTeacher 表上是必需的,如果它在 Person 基类上则不会使用。

    您需要在Personidname 字段上添加@DatabaseField 注释。例如:

    public abstract class Person{
        @DatabaseField(generatedId = true)
        public int id;
        @DatabaseField
        public String name;
    }
    

    ORMLite 应该遍历类层次结构,并且基类中的任何字段都应该包含在StudentTeacher 表中。如果您编辑您的问题以显示@DatabaseField 或其他注释,我可以发表更多评论。

    【讨论】:

    • 谢谢,这也回答了我关于 ORMLite 是否适用于这种情况的问题。
    【解决方案2】:

    好吧,但是现在,在该示例中,如何实现包含List<AbstractPerson> 的第四个类?

    我的问题是准确的:

    public class ClassRoom {
        @ForeignCollectionField(foreignFieldName="asYouWant")
        public Collection<Person>   peoples;
    }
    
    peoples.add(new Student());
    peoples.add(new Teacher());
    peoples.add(new Student());
    

    因为当 ormlite 会尝试访问以下人群时:

    for (Person person : classRoom.peoples)
    {
        if (person.getType() == Student)
            //do stuff
        else if (person.getType() == Student)
            //do other stuff
    }
    

    将无法获取 personDAO,因为它不存在(抽象)... 我的所有数据库功能都具有良好的 ID 和关系,这只是一个数据访问问题?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 2020-11-13
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      相关资源
      最近更新 更多