gpt4 book ai didi

java - 如何在没有生成 id 的情况下使用 ORMLite 外来对象?

转载 作者:行者123 更新时间:2023-11-30 01:16:10 24 4
gpt4 key购买 nike

我正在学习如何将 ORMLite 与 android 一起使用。我的问题是我从服务器收到带有 ID 的对象,我认为对我的数据库使用相同的 ID 会很好。这意味着我没有使用 generatedId = true,因此不能使用 foreignAutoGenerate = true

public class Artwork {

@DatabaseField(id = true, columnName = "id")
String id;

@DatabaseField
String name;

@DatabaseField
String file;

@DatabaseField(columnName = "user_id", foreign = true, foreignAutoCreate = true)
User owner;
}

如您所见,艺术品引用了拥有它的用户。两者在服务器端都已经有 ID,我想将其用作我的数据库的 ID。

public class User {

@DatabaseField(id = true, unique = true)
String id;

@DatabaseField
String name;
}

下面是魔法应该发生的地方......

Artwork artwork = new Artwork();
artwork.setName("name");
artwork.setFile("filepath");
artwork.setId("generated_by_server_0000");

User owner = new User();
owner.setId("generated_by_server_0001")
owner.setName("user");

artwork.setOwner(owner);

DatabaseHelper dbHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);

Dao<Artwork, String> artworkDao = dbHelper.getArtworkDao();
Dao<User, String> userDao = dbHelper.getUserDao();

userDao.create(owner);
artworkDao.create(artwork);

List<Artwork> artworksOnDb = artworkDao.queryForAll();

我如何使用 ORMLite 轻松地保留这些对象,但自己设置 ID?

最佳答案

My problem is that I receive objects with an ID from the server and I think it would be good to use the same ID for my DB. This means I am not using generatedId = true and therefore cannot use foreignAutoGenerate = true

没错。您不必对外部对象执行 generatedId = true,但不幸的是,您确实需要使用 foreignAutoCreate = true 执行此操作,否则ORMLite 不知道是否需要创建 User。如果您使用自己的 id,则需要使用 UserDao 并直接创建 User 而不是依赖自动机制。

引用docs for foreignAutoGenerate :

Set this to be true (default false) to have the foreign field automatically created using an internal DAO if its ID field is not set (null or 0). So when you call dao.create() on the parent object, any foreign field that has this set to true will possibly generate an additional create call via an internal DAO. By default you have to create the object using its DAO directly. By default you have to create the object using its DAO directly. This only works if generatedId is also set to true.

有一点很重要,就是您必须先插入 User ,然后再插入 Artwork,因为 Artwork 在其表中存储一个 user_id

User owner = new User();
owner.setId("generated_by_server_0001")
owner.setName("user");
...
// do this _before_ the create of Artwork
userDao.create(owner);

Artwork artwork = new Artwork();
artwork.setName("name");
...
artwork.setOwner(owner);
artworkDao.create(artwork);

关于java - 如何在没有生成 id 的情况下使用 ORMLite 外来对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37839935/

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