我想在我的持久实体中使用嵌入式POJO类。
需要匹配我的android应用中的服务器数据模型。应用程序使用GreeanDao框架进行DB DAO层,并使用基于注释的手写库与服务器进行数据交换* *我只想提一提,重写库以匹配限制也是一种解决方案,但是在此之前,我想弄清楚是否存在自然的方法或现有的用例。
我相信我可以在POJO字段中使用@Transient
批注,并将POJO字段的副本保留在Entity类中,而不仅仅是弄乱复制字段的设置者,并且构造函数Green Daou依赖于初始化POJO字段。
但是,如果您问我,听起来有点笨拙。
public class Person{
private String firstName, secondName;
private int age;
/* getters and setters */
}
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Keep;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.Transient;
import org.greenrobot.greendao.annotation.Generated;
@Entity
public class Employee {
@Id(autoincrement = true)
private long id;
@Transient
private Person person;
@Property(nameInDb = "PERSON_FIRST_NAME")
private String firstName;
@Property(nameInDb = "PERSON_SECOND_NAME")
private String secondName;
@Property(nameInDb = "PERSON_AGE")
private int age;
@Keep
public Employee(long id, String firstName, String secondName, int age) {
this.id = id;
this.firstName = firstName;
this.secondName = secondName;
this.age = age;
initPerson();
}
@Generated(hash = 202356944)
public Employee() {
}
private void initPerson(){
if(this.person == null)
this.person = new Person();
person.setFirstName(this.firstName);
person.setSecondName(this.secondName);
person.setAge(this.age);
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
this.setAge(person.getAge());
this.setFirstName(person.getFirstName());
this.setSecondName(person.getSecondName());
}
public void setFirstName(String firstName) {
this.firstName = firstName;
initPerson();
}
public void setSecondName(String secondName) {
this.secondName = secondName;
initPerson();
}
public void setAge(int age) {
this.age = age;
initPerson();
}
/* some getters etc */
}
答案 0 :(得分:0)
我使用类似的方法解决了这个问题,但修改很少。我一直使用注释ToOne。重要的是检查String personId而不是person。
@Entity
public class Employee {
@Id(autoincrement = true)
private long id;
private String personId;
@ToOne(joinProperty = "personId")
private Person person;
@Keep
public Employee(long id) {
this.id = id;
initPerson();
}
@Generated(hash = 202356944)
public Employee() {
}
private void initPerson() {
if (this.personId == null){
Person person = new Person();
person.setFirstName(this.firstName);
person.setSecondName(this.secondName);
person.setAge(this.age);
setPerson(person)
}
}
/** called by internal mechanisms, do not call yourself. */
@Generated(hash = 472550346)
public void setPerson(Person person) {
synchronized (this) {
this.person= person;
personId = person == null ? null : person.getId();
person__resolvedKey = personId;
}
}
/* some getters etc */
}