Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use / not to use, @OneToOne and @ManyToOne

Tags:

java

jpa

I just started reading about JPA and its implementation in Hibernate. To understand the details better I need some clarification on some of the basics.

  1. 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 make sure that the referred objects are not in transient state.
    Is this true?

  2. When to use, or not to use @ManyToOne?
    Say, I'm defining an Employee class and need to define the relationship with the Employer class. In this case, do I need to specify @ManyToOne as below?

    @Entity   
    public class Employer {  
        String name;   
    }   
    
    @Entity   
    class Employee {  
        String name;
    
        @ManytoOne  //or not??   
        Employer employer;   
    }
    
like image 641
bsr Avatar asked Jul 16 '10 09:07

bsr


1 Answers

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.

like image 124
Henning Avatar answered Sep 20 '22 07:09

Henning