私のエンティティをCPUとPROCESSORとして考え、共有された主キーと1対1の関係を持っています。1 つの CPU には 1 つのプロセッサがあります。
CPU.java
@Entity
@Table(name = "PKJoin_CPUt")
public class CPU {
private int id;
private String name;
private Processor processor;
@OneToOne(cascade = CascadeType.PERSIST, mappedBy = "cpu", optional = true,fetch=FetchType.LAZY)
public Processor getProcessor() {
return processor;
}
public void setProcessor(Processor processor) {
this.processor = processor;
if (null != processor) {
processor.setCpu(this);
}
}
private Processor2 processor2;
@OneToOne(cascade = CascadeType.PERSIST, mappedBy = "cpu", optional = true,fetch=FetchType.LAZY)
public Processor2 getProcessor2() {
return processor2;
}
public void setProcessor2(Processor2 processor2) {
this.processor2 = processor2;
if (null != processor2) {
processor2.setCpu(this);
}
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
if (null != processor) {
processor.setId(id);
}
if (null != processor2) {
processor2.setId(id);
}
}
public String getName() {
return name;
}
public void setName(String deptName) {
this.name = deptName;
}
}
Processor.java
@Entity
@Table(name = "PKJoin_Processor")
public class Processor {
private int id;
private String name;
private CPU cpu;
@OneToOne(fetch=FetchType.LAZY)
@PrimaryKeyJoinColumn
public CPU getCpu() {
return cpu;
}
public void setCpu(CPU cpu) {
this.cpu = cpu;
}
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Main.java
public class Main {
static EntityManagerFactory emf = Persistence.createEntityManagerFactory("Hello");
static EntityManager em = emf.createEntityManager();
public static void main(String[] a) throws Exception {
em.getTransaction().begin();
new Main().findData();
// new Main().persistData();
em.getTransaction().commit();
em.close();
emf.close();
}
public void findData(){
CPU cpu = em.find(CPU.class, 449);
System.out.println(cpu.getProcessor().getName());
}
}
これは次のように実行されます::
Hibernate: select cpu0_.id as id11_0_, cpu0_.name as name11_0_ from PKJoin_CPUt cpu0_ where cpu0_.id=?
Hibernate: select processor0_.id as id38_0_, processor0_.name as name38_0_ from PKJoin_Processor processor0_ where processor0_.id=?
Hibernate: select processor2x0_.id as id19_0_, processor2x0_.name as name19_0_ from PKJoin_Processor222 processor2x0_ where processor2x0_.id=?
ジョー
CPUName 属性のみをフェッチしているときに、これら 3 つのクエリを実行したくありません。結合もしたくありません。CPU 属性をフェッチしようとするたびに、最初のクエリだけを実行したい。解決策が必要ですか?