Hibernate ORM 6.2.1 / Wrong select clause generated / OneToOne between the same entity

Hi,

The following code seems to generate an erroneous SQL query.

@Entity
public class Person {

    @Id
    private String id;

    @OneToOne
    private Person bestFriend;

    public Person() {

    }

    public Person(String id, Person bestFriend) {
        this.id = id;
        this.bestFriend = bestFriend;
    }

    public String getId() {
        return id;
    }
}
@Test
public void wrong_select_generated() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    Person friend = new Person("friend", null);
    Person person = new Person("person", friend);

    entityManager.persist(friend);
    entityManager.persist(person);

    entityManager.getTransaction().begin();

    List<Object[]> results = entityManager.createQuery("""
                    select p.id, f.id
                    from Person p
                    left join p.bestFriend f
                    order by p.id desc
                    """, Object[].class)
            .getResultList();

    Assert.assertEquals(person.getId(), results.get(0)[0]);
    Assert.assertEquals(friend.getId(), results.get(0)[1]);

    entityManager.getTransaction().commit();
    entityManager.close();
}

The unit test result is:

Expected :friend
Actual   :person

The generated query is:

Hibernate: 
    select
        p1_0.id 
    from
        Person p1_0 
    order by
        p1_0.id

The unit test passes with Hibernate 6.1.7.Final and the generated query is:

Hibernate: 
    select
        p1_0.id,
        p1_0.bestFriend_id 
    from
        Person p1_0 
    order by
        p1_0.id desc

Code of the unit test: GitHub - smalbequi/hibernate-test-case-bug-select-one2one

This looks like a bug, please open a new JIRA issue and attach the reproducer you have linked.

JIRA issue created: [HHH-16488] - Hibernate JIRA