我使用JPA 2与Hibernate 4.2.0-Final作为提供者,我有以下实体:
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {
@Id
private String id;
.. Person attributes ..
.. Getters/Setters ..
}
@Entity
@Table(uniqueConstraints={@UniqueConstraint(name="UniqueCode", columnNames="code")})
public class Customer extends Person {
@Column(nullable=false)
private String code;
.. Other Customer attributes ..
.. Getters/Setters ..
}
我有以下JPQL:
SELECT count(distinct c.code) FROM Customer c
Hibernate生成以下SQL:
select
count(distinct customer0_.code) as col_0_0_
from
Customer customer0_
inner join
Person customer0_1_
on customer0_.id=customer0_1_.id
但是我只需要计算具有不同代码的客户,这恰好是一个特定于Customer的字段,因此不需要对'Person'进行内部连接。我想Hibernate生成如下SQL(即不加入表'Person'):
select
count(distinct customer0_.code) as col_0_0_
from
Customer customer0_
是否有办法告诉Hibernate避免不必要的内部连接?也许是一些hibernate特定的查询提示?
JPA
中的JOINED Strategy
为对象层次结构中的每个类使用单独的表。
所以如果你想为subclass
加载对象,你也有从父类加载信息(因为子类单独不能代表没有父类属性的完整图片)。这将在查询子对象时产生JOIN
。
从JPA文档中,您可以看到这是join策略的主要缺点。
1)除了所描述的每类表策略的某些使用之外下面,join策略通常是最慢的继承模型。检索任何子类需要一个或多个数据库连接,和存储子类需要多个INSERT或UPDATE语句。