I just started reading of JPA, and the implementation in hibernate to understand the details. but, to continue with development till then, can you help to clarify a basic qn
1: When working with entity relations, you must always use the appropriate annotations (OneToOne, OneToMany, ManyToOne, or ManyToMany). The choice you have is whether you want to make sure the entity behind the relation is not transient yourself, or specify the cascade property on the OneToOne annotation to let JPA take care of that for you. This allows you to create a whole graph of objects and persist them in one call:
@OneToOne(cascade = CascadeType.ALL)
private MyType myType;
2: Yes, an employer-employee relationship sounds like a OneToMany relationship, and the employee-employer relationship would be ManyToOne. If you'd like to have both directions, that's called a bi-directional relationship. Have a look at the relevant section in the Java EE tutorial for details.
The JPA section in the Java EE tutorial is a good reference to start from.
When to use OneToOne I may use OneToOne if the entity manager needs to handle the persistency of the related object. the point is, I can always live without specifying oneToOne, but then the responsibility is on me to manage the relationship and making sure that the referred objects are not in transient state. Is this true?
You need not mark the relationship if you don't want the entity manager to handle operations. You can have the related entity as a transient field and persist the related entity manually. But in that case, you wouldn't be using the whole list of features that JPA provides.
By marking the relationships, the EntityManager comes to know about the database structure. And that is essential if you want to utilize the power of JPA.
Eg: class Car
{
@OneToOne
Warehouse warehouse;
//other fields
}
Here
I can retrieve the related Warehouse object while retrieving a Car
I can persist a Warehouse object while persisting a Car (with cascade option as explained by the poster below )
Apart from these, while using JPQL,
you can traverse to Warehouse
as in
em.createQuery("select c.warehouse from Car c");
These wouldn't work unless you mark the relationship.