我注意到当相关数据已经存在时,foreignAutoCreate会崩溃,抛出类似这样的东西:
E/SQLiteLog﹕ (2067) abort at 20 in [INSERT INTO `Group` (... etc,`id` ) VALUES (?,?,?)]:
UNIQUE constraint failed: Group.id
但我有一个列表,例如:
List<User> lstUsers = //values
我用循环插入值&#34;用于&#34;使用createOrUpdate:
for(...) {
dao.createOrUpdate(user);
}
和用户通过示例与Group有相关数据:
@DatabaseField(canBeNull = true, foreign = true, foreignAutoCreate = true,
foreignAutoRefresh = true)
private Group group;
当我有重复的组ID值时,操作失败:
lstUsers.get(0).getGroup().getId(); // group id = 1 <-- foreign insert
lstUsers.get(1).getGroup().getId(); // group id = 1 <-- crash
lstUsers.get(3).getGroup().getId(); // group id = 1 <-- crashed already
lstUsers.get(3).getGroup().getId(); // group id = 2 <-- crashed already
... etc.
我需要自动插入一个或多个未重复的组(仅插入一次),而不需要手动使用foreignAutoCreate。
lstUsers.get(0).getGroup().getId(); // group id = 1 <-- foreign insert
lstUsers.get(1).getGroup().getId(); // group id = 1 <-- foreign exists, skip
lstUsers.get(3).getGroup().getId(); // group id = 1 <-- foreign exists, skip
lstUsers.get(3).getGroup().getId(); // group id = 2 <-- foreign insert
有办法做到这一点??
更新1:
请尝试这个测试:
public void poblatingUsersAndGroupsList(){
List<User> lstUsers = new ArrayList<>();
Group group1 = new Group();
// this group doesn't exists in database
group1.setId(1); // should be inserted by ForeignAutoCreate
lstUsers.add(new User("user1",group1));
lstUsers.add(new User("user2",group1));
lstUsers.add(new User("user3",group1));
Group group2 = new Group();
group1.setId(2);
// this group doesn't exists in database
group1.setId(1); // should be inserted by ForeignAutoCreate
lstUsers.add(new User("user4",group1));
lstUsers.add(new User("user5",group2));
lstUsers.add(new User("user6",group2));
createUsersInGroup(lstUsers);
}
public void createUsers(List<User> lstUsers){
for(User user : lstUsers){
// here is the error
// group1 inserted the 1st time
// the 2nd, 3rd, n times are throwing error
// same for group2
dao.createOrUpdate(user);
}
}
foreignAutoCreate应该像这段代码一样工作,所以我们可以避免这段代码:
public void createUsers(List<User> lstUsers){
for(User user : lstUsers){
// (innecesary) calling or instantiating the groupDao
// (innecesary) check if not exists
groupDao.createIfNotExists(user.getGroup());
dao.createOrUpdate(user);
}
}
答案 0 :(得分:0)
这是一个老问题,我假设你继续前进。然而,我无法重现这一点。我使用dao.createOrUpdate(...)
扩展了多个插入的测试用例。请参阅ForeignObjectTest unit test code。
我想知道的一件事是,当您使用关联的User
创建Group
时,必须已创建Group
以使其具有id
}。这可能是问题吗?
Group group = new Group();
// need to do this first to have group get an id
groupDao.create(group);
User user = new User();
user.setGroup(group);
for(...) {
dao.createOrUpdate(user);
}