hibernatequery-optimizationfetchone-to-one

Hibernate @OneToOne executes multiple queries even with @Fetch(FetchMode.JOIN)


Consider and Employee and Address relationship. There is a One-to-one mapping between Employee and Address. Following are models:

@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;

    .
    .
}

Now when I execute following HQL query it internally generates two queries. One to fetch Employee and another to fetch Address.

"FROM Employee WHERE id = " + 1

SQL queries generated by Hibernate

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=?

As I am using @Fetch(FetchMode.JOIN), I was expecting Hibernate to execute only 1 query with a join to fetch Employee and Address data in one go.

Any idea why it is executing two queries and how can I make Hibernate to execute only one query using join?

I am using Hibernate 3.3.0.


Solution

  • Using explicit HQL query "FROM Employee WHERE id = " + 1", Hibernate will not respect the annotated Fetch mode. You would need to specify the join in the HQL query or the fetch mode in the criteria.

    Hibernate 3.x ignores the Fetch Mode annotation when you use the Query interface (Session.createQuery) so in this case you have to add an INNER JOIN FETCH clause to the FROM part of your query.