Read into nested object from SQL query using Hibernate 5.4

Viewed 375

New to Hibernate. I have the following setup:

@Entity
@Table(name = "primary_doctor")
public class PrimaryDoctor {
    @Id
    private Long rid;

    @OneToOne
    @JoinColumn(name = "pid")
    private Patient patient;

    @OneToOne
    @JoinColumn(name = "did")
    private Doctor doctor;
}
@Entity
@Embeddable
public class Doctor {

    @Id
    private Long did;
    String name;
    String phone;
}
@Entity
public class Patient {

    @Id
    private Long pid;
    String name;
    String gender;
    String height;
    String birthDate;
}

I want to get a Doctor object by querying the primary_doctor table. I know I can join on did of the two tables but I feel if I do that I'm not using Hibernate object mapping. Can you guide me how to do this properly. Here is what I have:

EntityManager entityManager = ...
entityManager.getTransaction().begin();
String sqlQuery = "SELECT * FROM DOCTOR WHERE DID = (SELECT DID FROM PRIMARY_DOCTOR WHERE pid = " + pid + ");";
Query q = entityManager.createNativeQuery(sqlQuery);
Object[] resultRow = (Object[]) q.getResultList().get(0);
String doctorName = (String) resultRow[1];

Also I have a persistence.xml file as follows:

<persistence-unit name="test">
        <class>model.Patient</class>
        <class>model.Doctor</class>
        <class>model.PrimaryDoctor</class>
...

I don't have a cfg file. Do I need to have that?

My Hibernate version:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.31.Final</version>
</dependency>

I'm using H2 for database:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>

And using Maven on IntelliJ.

1 Answers

That's a pretty simple JPQL/HQL query and since you are new to Hibernate, I'd suggest you start by reading a book or following a tutorial on the topic instead of coming to StackOverflow as I think you will learn the most by first working through some material. You will most likely have many more questions while learning Hibernate and most of them you can easily answer yourself by learning the basics first. That's just a friendly tip to avoid you get frustrated because you wait for answers, so do whatever you see fit. Anyway, the query for your use case would look like this:

Doctor d = entityManager.createQuery("select d from PrimaryDoctor p join p.doctor d where p.id = :id", Doctor.class)
    .setParameter("id", primaryDoctorId)
    .getSingleResult();
Related