我正在将用户类实现为:
@Entity
public class User implements Serializable {
/** Serial version UID */
static final long serialVersionUID = 200L;
@Id
/** The user system id */
private long id;
@Index(unique = true)
/** The user login username*/
private String username;
/** The user first name */
private String firstName;
/** The user last name*/
public String lastName;
@ToOne
@NotNull
/** The company this user belongs*/
private Company company;
...
}
和公司
@Entity
public class Company extends JsonModel implements Serializable {
/** Serial version UID */
static final long serialVersionUID = 100L;
@Id
/** The sqlite record id */
private long id;
@NotNull
/** The company public name */
private String name;
...
}
@ToOne应该可以正常工作,因为我可以通过TABLE指令看到生成的UserDao:
public final static Property Company = new Property(6, long.class, "company", false, "COMPANY");
在app流程中,我创建了一个User实例(而不是db),并为其设置了一个Company对象。
然后我打电话给:
UserDao userDao = daoSession.getUserDao();
userDao.insert(user);
但是我的应用程序未能指定公司不能为空。当我打开 UserDao 生成的类时,我发现bindValues在保存用户之前从不创建公司。
@Override
protected final void bindValues(DatabaseStatement stmt, User entity) {
stmt.clearBindings();
stmt.bindLong(1, entity.getDbId());
stmt.bindLong(2, entity.getId());
String username = entity.getUsername();
if (username != null) {
stmt.bindString(3, username);
}
String firstName = entity.getFirstName();
if (firstName != null) {
stmt.bindString(4, firstName);
}
String lastName = entity.getLastName();
if (lastName != null) {
stmt.bindString(5, lastName);
}
}
为了创建子实体,我该怎么做?
修改
好的,我刚刚读到ORM不会自动管理关系。我没有看到使用lib hehe的许多好处..
答案 0 :(得分:0)
好的,我刚刚读到ORM不会自动管理关系。
所以我应该先插入公司。