0

我有以下 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 实体中的对象关联。通过连接获取该关联来解决问题(即只发出一个查询):

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 关联)。

4

0 回答 0