例如,如果我有一个表Shows
,并且我与表Actors
有多对多关系
当插入没有id(其自动生成)的Show
时,如果我没有与之相关的节目的id,我如何插入Actors
?
下面是DaoGenerator的代码:
Entity show = schema.addEntity("Show");
show.setHasKeepSections(true);
show.addIdProperty();
show.addIntProperty("tvdb_id").notNull();
show.addStringProperty("title");
show.addIntProperty("year");
show.addStringProperty("url");
show.addLongProperty("first_aired");
show.addStringProperty("country");
show.addStringProperty("overview");
show.addIntProperty("runtime");
show.addStringProperty("status");
show.addStringProperty("network");
show.addStringProperty("air_day");
show.addStringProperty("air_time");
show.addStringProperty("certification");
show.addStringProperty("imdb_id");
show.addIntProperty("tvrage_id");
show.addLongProperty("last_updated");
show.addIntProperty("rating");
show.addIntProperty("votes");
show.addIntProperty("loved");
show.addIntProperty("hated");
Entity actor = schema.addEntity("Actor");
actor.addIdProperty();
actor.addStringProperty("name");
actor.addStringProperty("character");
actor.addStringProperty("image");
Property showId = actor.addLongProperty("show_id").notNull().getProperty();
ToMany showToActor= show.addToMany(actor, showId);
showToActor.setName("actors");
插入对象时自动生成ID
所以你必须在添加演员之前插入节目
您可以在该实体上调用refresh(),当前副本将被更新,因此它的id。
那么你应该把这个showId设置为每个演员的show id。
show.refresh();
for (Actor actor : actors)
actor.setShowId(show.getId());
actorDao.insertAllInTx(actors);