When creating an Account, you have to manually set the back-reference to the Student, cause it is not being set automatically. When retrieving an Account from the database, the Hibernate will load the corresponding parent, i.e. Student.
However, you won't see the belongsTo field in the Account table, because it is regulated on the Student side by a foreign key definition.
Here's how your example should look like (I am using field reference for the sake of the simplicity):
Code:
@Entity
class Student {
@Id
@GeneratedValue
public Long id;
@OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, optional = true)
public Account account;
}
@Entity
class Account {
@Id
@GeneratedValue
public Long id;
@OneToOne(mappedBy = "account", fetch = FetchType.EAGER)
public Student belongsTo;
public Account() {
}
public Account(Student belongsTo) {
this.belongsTo = belongsTo;
}
}
public class StudentTest {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Student s = new Student();
s.account = new Account(s);
em.persist(s);
tx.commit();
em.clear();
Long id = s.id;
Account ac = em.find(Account.class, id);
System.out.println(ac + " belongs to "+ ac.belongsTo);
em.close();
}
}