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.