gpt4 book ai didi

java - 在 ORMLite 中使用 id 字段作为外部字段

转载 作者:搜寻专家 更新时间:2023-10-30 23:44:04 24 4
gpt4 key购买 nike

我尝试在 java 中使用 ORMLite,但遇到了以下问题。

我的代码是这样的:

@DatabaseTable(tableName = "subscriptions")
public class Subscription {
@DatabaseField(id = true, index = true, uniqueCombo=true, foreign = true, foreignColumnName = "gcm_id")
private User user;
@DatabaseField(id = true, index = true, uniqueCombo=true, foreign = true, foreignColumnName = "id")
private Category category;
//other stuff in the class
}

请注意,user 和 category 这两个字段同时标记为 id 和 foreign。我相信这符合我的数据库:

database table subscriptions

这些字段分别指向表Users和Categories。我认为这对于数据库来说是很正常的,但如果我错了,请纠正我。

在线

subscriptionDao = DaoManager.createDao(connectionSource, Subscription.class);

我收到这个错误:

Exception in thread "main" java.lang.IllegalArgumentException: Id field user cannot also be a foreign object at com.j256.ormlite.field.FieldType.(FieldType.java:231) at com.j256.ormlite.field.FieldType.createFieldType(FieldType.java:937) at com.j256.ormlite.table.DatabaseTableConfig.extractFieldTypes(DatabaseTableConfig.java:208) at com.j256.ormlite.table.DatabaseTableConfig.fromClass(DatabaseTableConfig.java:146) at com.j256.ormlite.table.TableInfo.(TableInfo.java:53) at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:149) at com.j256.ormlite.dao.BaseDaoImpl.(BaseDaoImpl.java:126) at com.j256.ormlite.dao.BaseDaoImpl.(BaseDaoImpl.java:105) at com.j256.ormlite.dao.BaseDaoImpl$4.(BaseDaoImpl.java:895) at com.j256.ormlite.dao.BaseDaoImpl.createDao(BaseDaoImpl.java:895) at com.j256.ormlite.dao.DaoManager.createDao(DaoManager.java:70)

错误应该很容易解释,Id 字段 user 不能同时是外部对象。但是,我无法在任何地方找到任何关于为什么会这样或如何解决它的信息。如果我的数据库设计正确,这对我来说也没有意义。

如果我替换这些行,就更没有意义了

@DatabaseField(id = true, index = true, uniqueCombo=true, foreign = true, foreignColumnName = "gcm_id")
private User user;

有了这些

@DatabaseField(id = true, index = true, uniqueCombo=true)
private User user;

我得到了预期的“ORMLite 不知道如何存储类”错误,但是我没有得到相同的 Id 字段 _____ 也不能是类别字段的外来对象错误。我只如果我为我的用户字段设置 id = false,则类别字段会出现此错误。

一个简单的补丁是为表订阅使用生成的 id,但就像我说的,我正在以这种方式设计我的数据库,因为我被教导最好避免在任何地方生成 id,尤其是主键该表很明显,易于处理,有效等(即当您使用生成的 ID 没有真正获得任何 yield 时)。

谢谢大家的帮助。

最佳答案

据我所知,问题是你们都有多个 id 字段,而且它们都是外来的。

根据 id 的文档:

Only one field can have this set in a class

一个非常简单的解决方法是使用如下设计的表格:

@DatabaseTable(tableName = "subscriptions")
public class Subscription {
@DatabaseField(generatedId = true)
private int sub_id;
@DatabaseField(index = true, uniqueCombo=true, foreign = true, foreignColumnName = "gcm_id")
private User user;
@DatabaseField(index = true, uniqueCombo=true, foreign = true, foreignColumnName = "id")
private Category category;
//other stuff in the class
}

当这些对象被插入数据库时​​,generatedId 字段自动递增 id

关于java - 在 ORMLite 中使用 id 字段作为外部字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com