ORM Lite throws error when creating tables containing multi level foreign key

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-04 05:51:27

问题


I'm getting this error on ORM Lite when creating table ActivityLog :

10-23 04:06:32.255: E/com.timelord.dao.DatabaseHelper(1487): 
Caused by: java.sql.SQLException: ORMLite can't store unknown class class 
com.timelord.pojo.Category for field 'category'. Serializable fields must 
specify dataType=DataType.SERIALIZABLE

I suspected that this is caused by the multi level foreign key. As you can see from the POJO class below, ActivityLog has Activity, and Activity has Category.

Activity and Category are working fine.

Any idea of how to do the correct mapping?

@DatabaseTable(tableName = "activityLogs")
public class AcitvityLog implements Serializable {

    private static final long serialVersionUID = 1L;

    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(canBeNull = false)
    @DatabaseFieldForeign(foreign = true)
    private Activity activity;

    @DatabaseField(dataType = DataType.DATE, canBeNull = false)
    private Timestamp start;

    @DatabaseField(dataType = DataType.DATE, canBeNull = true)
    private Timestamp end;
}

@DatabaseTable(tableName = "activities")
public class Activity extends BaseEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @DatabaseField(canBeNull = false)
    @DatabaseFieldForeign(foreign = true)
    private Category category;
}

@DatabaseTable(tableName = "categories")
public class Category extends BaseEntity implements Serializable {

    private static final long serialVersionUID = 1L;
}

public class BaseEntity {
    @DatabaseField(generatedId = true)
    private Integer id;

    @DatabaseField(canBeNull = false)
    private String name;
}

回答1:


No, ORMLite can handle multi level foreign keys without any issues. The problem is that you cannot mix @DatabaseField and @DatabaseFieldForeign annotations. What you want is:

@DatabaseField(canBeNull = false, foreign = true)
private Activity activity;

Or, if you want to use the smaller annotations which run faster under Android:

@DatabaseFieldSimple(canBeNull = false)
@DatabaseFieldForeign(foreign = true)

Either you use just the @DatabaseField or @DatabaseFieldSimple and the other @DatabaseField... annotations. Here are the docs for @DatabaseFieldSimple:

http://ormlite.com/javadoc/ormlite-core/com/j256/ormlite/field/DatabaseFieldSimple.html



来源:https://stackoverflow.com/questions/7872880/orm-lite-throws-error-when-creating-tables-containing-multi-level-foreign-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!