Assume thre are two entities with ManyToOne relation:
Code:
@Entity
public class A {
private long code;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getCode() {
return code;
}
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:
Code:
// 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:
Code:
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?