Persistence a child object with existing parent one
Assume there are two entities with ManyToOne relation:
@Entity
public class A {
private long code;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getCode() {
return code;
开发者_Python百科 }
public viod setCode(long code) {
this.code = code;
}
// additional setters and getters
}
@Entity
public class B {
private long code;
private A a;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getCode() {
return code;
}
public viod setCode(long code) {
this.code = code;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="acode", nullable=false)
public A getA() {
return a;
}
public void setA(A a) {
this.a = a
}
// additional setters and getters
}
As part of the business flow I have code value of the existing A object and I need to insert new B object and relate it to the existing A. This code works fine:
// inject em
A a = em.find(A.class, code);
B b = new B();
b.setA(a);
em.persist(b);
My problem is with "A a = em.find(A.class, code)" line. This looks like for me as a redundant query because the B table contains a foreign key (acode). In order to improve performance I tried to create A object with an existing code value:
A a = new A();
a.setCode(code);
B b = new B();
b.setA(a);
em.persist(b);
but it doesn't work. Is there any way to avoid unnecessary query?
There is a special getReference()
method that can be used instead of find()
in exactly this scenario. It creates a proxy object with the specified id without issuing queires. Existence of A
with that id is checked by foreign key constraint at the database side when saving B
.
A a = em.getReference(A.class, code);
B b = new B();
b.setA(a);
em.persist(b);
精彩评论