'Hibernate one to one unidirectional mapping runs additional query even if 'join fetch' used in query

I have one to one unidirectional mapping. I am explicitly fetching both data using 'left join fetch'. Yet, when I run the query, hibernate runs 2 queries. Why?

public class Person {
    @Id
    private Long personId;

    @OneToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="address_id", referrencedColumnName="address_id")
    private Address address;
}

public class Address {
    @Id
    @Column(name="address_id", nullable=false)
    private Long addressId
}

public interface PersonRepository extends JpaRepository<Person, Long> {
    @Query(value="select p from Person p left join fetch p.address where p.personId = :personId")
    Person getPerson(@Param("personId") Long personId)
}

@DataJpaTest
@RunWith(SpringRunner.class)
public class PersonTest {
    @Autowired
    private PersonRepository repo;
    @Test
    public void test() {
        Person person = repo.getPerson(1l);
    }
}

When I run the above test, it runs 2 queries.

1. select * from Person p left join address a on p.address_id=a.address_id where p.person_id=?

2. select * from address a where a.address_id=? -- why is this run?

Why is it running the second query when it's lazily fetched and I am explicitly fetching it in my query?

If you see some typos, it's because I had to rename classes and type them manually.

Another post with somewhat similar issue was offered as a solution to this. But that doesn't solve the issue.

  1. I have set the relationship as lazy
  2. I am explicitly fetching the associated data
  3. It does not have N+1 issue, as this is a one to one relationship


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source