Hibernate @OneToOne即使使用@Fetch(FetchMode.JOIN)也会执行多个查询

San*_*ani 6 hibernate query-optimization one-to-one fetch

考虑EmployeeAddress关系.之间存在一一对一映射EmployeeAddress.以下是型号:

@Entity
@Table(name = "Address")
public class Address
{
    @Id
    @GeneratedValue
    @Column(name = "addressId")
    private int addressId;

    @Column(name = "city")
    private String city;

    .
    .
}

@Entity
@Table(name = "Employee")
public class Employee
{
    @Id
    @Column(name = "employeeId")
    private int employeeId;

    @Column(name = "name")
    private String name;

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "addressId")
    @Fetch(FetchMode.JOIN)
    private Address address;

    .
    .
}
Run Code Online (Sandbox Code Playgroud)

现在,当我执行以下HQL查询时,它会在内部生成两个查询.一个用于获取Employee,另一个用于获取地址.

"FROM Employee WHERE id = " + 1

Hibernate生成的SQL查询

Hibernate: select employee0_.employeeId as employeeId0_, employee0_.addressId as addressId0_, employee0_.name as name0_ from Employee employee0_ where employee0_.employeeId=1

Hibernate: select address0_.addressId as addressId1_0_, address0_.city as city1_0_ from Address address0_ where address0_.addressId=?

正如我正在使用的那样@Fetch(FetchMode.JOIN),我希望Hibernate只能通过连接执行一个查询来一次性获取Employee和Address数据.

知道它为什么执行两个查询,我怎样才能使Hibernate只使用join执行一个查询?

我正在使用Hibernate 3.3.0.

小智 7

使用显式HQL查询"FROM Employee WHERE id ="+ 1",Hibernate将不会遵循带注释的Fetch模式.您需要在HQL查询中指定连接或在条件中指定获取模式.

当您使用Query接口(Session.createQuery)时,Hibernate 3.x会忽略Fetch Mode批注,因此在这种情况下,您必须将INNER JOIN FETCH子句添加到查询的FROM部分.