因此它不会在具有外键User的表 Task 中插入数据。
这是任务类:
package com.example.gencode.execomtodolist.model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable
public class Task{
@DatabaseField(generatedId = true)
private Long id;
@DatabaseField
private String title;
@DatabaseField
private String description;
@DatabaseField
private boolean done;
@DatabaseField (foreign = true, foreignAutoRefresh = true)
private User user;
public Task(){
}
public Task(User user, String title, String description, boolean done) {
this.user = user;
this.title = title;
this.description = description;
this.done = done;
}
@Override
public String toString() {
return " " + title;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public boolean isDone() { return done; }
}
这是用户类:
package com.example.gencode.execomtodolist.model;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
import java.util.Collection;
@DatabaseTable
public class User{
@DatabaseField(generatedId = true)
private Long id;
@DatabaseField
private String username;
@DatabaseField
private String password;
@ForeignCollectionField
private ForeignCollection<Task> userTasks;
public User(){
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return " " + username + " " + password;
}
public String getUsername() {
return username;
}
public Long getId() {
return id;
}
public String getPassword() {
return password;
}
public Collection<Task> getUserTasks() { return userTasks; }
}
当我尝试这个时:
private void insertUsers(){
User user1 = new User("Djavo", "666");
User user2 = new User("Martel", "123");
userDao.create(user1);
userDao.create(user2);
Task task1 = new Task(user1, "naslov1", "opis232", false);
Task task2 = new Task(user1, "naslov2", "opis3232", false);
taskDao.create(task1);
taskDao.create(task2);
Log.d("ORMLITEDEMO", "User1 and User2 and Task1 and Task2 CREATED!!!");
}
发生错误:
引起:java.sql.SQLException:插入数据库失败:INSERT INTO
task
(description
,user_id
,title
,done
)VALUES (?,?,?,?)
我是Android的初学者,特别是在ORMLite,所以请帮忙。
答案 0 :(得分:0)
好的,我发现了什么问题。 因为我在Task类中更改了Task表,所以需要重新创建数据库以提交更改。 所以我做的是删除我的数据库,然后再次创建它。 它现在有效。