我有以下3个课程:
public class Object {
...whatever
}
public class CustomerObject {
@OneToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "OBJECT_ID", referencedColumnName = "OBJECT_ID", insertable = false, updatable = false)
private Object object;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CUSTOMER_TYPE_ID", referencedColumnName = "OBJECT_ID", insertable = false, updatable = false)
private CustomerTypeObject customerTypeObject;
}
public class CustomerTypeObject {
@JoinColumn(name = "OBJECT_ID", referencedColumnName = "OBJECT_ID", insertable = false, updatable = false)
@OneToOne(optional = false, fetch = FetchType.LAZY)
private Object object;
}
当我这样做时:
entityManager.createQuery(
"select cust from CustomerObject cust "
+ "left join fetch cust.customerTypeObject customerType "
+ "where cust.id = :customer_id
, CustomerObject.class)
.setParameter("customer_id", BigDecimal.valueOf(1))
.getSingleResult();
Hibernate发出1条查询以获取带有其customerType的客户,但随后也发出查询以获取CustomerTypeObject实体中的Object关联。通过加入获取该关联即可解决问题(即仅发出一个查询):
entityManager.createQuery(
"select cust from CustomerObject cust "
+ "left join fetch cust.customerTypeObject customerType "
+ "left join fetch customerType.object customerTypeObject "
+ "where cust.id = :customer_id
, CustomerObject.class)
.setParameter("customer_id", BigDecimal.valueOf(1))
.getSingleResult();
但是我不想这样做。有没有办法做到这一点? (即,不要急于在已经通过查询获取的实体中获取OneToOne关联。)