Skip to content

Instantly share code, notes, and snippets.

@saisurya-kat
Last active May 8, 2017 10:38
Show Gist options
  • Save saisurya-kat/7b336efbe9a5d0f5c32056f69df9a6dc to your computer and use it in GitHub Desktop.
Save saisurya-kat/7b336efbe9a5d0f5c32056f69df9a6dc to your computer and use it in GitHub Desktop.
Hibernate Relationships and associations

Entity Relationships

Relationships between entities are ways

  • OneToOne
  • OneToMany
  • ManyToMany

Each Relationship can be associated two ways

  • Uni Directional
  • Bi Directional

Cascades

  • Cascade.ALL This means that if we perform an insert on the child row, Hibernate will automatically create the parent row based on where the child row is pointing. Similarly If we delete a parent row all the child rows pointing to that parent row will be deleted if cascaded.
Example
OneToMany UniDirectional Relationship

Consider two entities Employer and Employee and their java objects

public class Employer{

    private Long id;  

    private String employerName;

}

public class Employee{  

    private Long id;  
    
    private String employeeName; 
    
    private Employer employer;
    
 }

we would be able to determine which Employer an Employee works for (via employee.getEmployer()) but we wouldn’t be able to determine which Employees work for a given Employer (as we have no employer.getEmployees() method).

This is the meaning of a unidirectional relationship. We can only “look” at the relationship in one way.

If we want to represent a Uni-Directional OneToMany and ManyToOne Relationship we only need to use the @ManyToOne annotation.We need to map the child/many side of the relationship and only the child/many side.

public class Employee{  
    private Long id;  
    
    private String employeeName;
    
    @ManyToOne(cascade=CascadeType.ALL) 
    private Employer employer;
 }

Useful References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment