我有一个 Person 表,其中有一列名为 CREATEBY。它的引用列是人员的ID。
我怎么只能得到一级引用?
这是人:
@Entity
@Table(name = "person")
public class Person {
@Id
private int id;
@Column(name = "cname")
private String cname;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "createby", referencedColumnName="id")
private Person createby;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public Person getCreateby() {
return createby;
}
public void setCreateby(Person createby) {
this.createby = createby;
}
@Override
public String toString() {
return "Person [id=" + id + ", cname=" + cname + ", createby="
+ createby + "]";
}
}
这是测试用例
public class SelfJoinTest extends ExampleBaseTestCase {
@Before
public void before() {
Person p1 = new Person();
p1.setId(1);
p1.setCname("p1");
Person p2 = new Person();
p2.setId(2);
p2.setCname("p2");
p2.setCreateby(p1);
Person p3 = new Person();
p3.setId(3);
p3.setCname("p3");
p3.setCreateby(p2);
Ebean.save(p1);
Ebean.save(p2);
Ebean.save(p3);
}
@Test
public void test() {
Person p = Ebean.find(Person.class, 3);
System.out.println(p);
// jackson
ObjectMapper mapper = new ObjectMapper();
try {
String s = mapper.writeValueAsString(p);
System.out.println(s);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
某处说使用 Jackson 注释来解决它,但我认为这不是最好的方法。这种方式浪费了许多数据库查询。 JPA 对此有解决方案吗?
最佳答案
我现在有一个解决方案。我意识到 JPA 不应该处理这种情况,甚至是 jackson 。我的模式有问题。
作为问题的POJO,我应该使用open session in view模式,但它不适合我。
因此,我创建了一个名为 PersonWithoutCreateby
的 DTO,其中不包含 createby
字段。
并且在 Person
中,createby
字段更改为 private PersonWithoutCreateby createby;
。并将 Person
转移到 View 。
关于java - JPA self-join问题,我怎么只能得到第一级引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31374712/