Hibernate Mapping and Relationship / Association

Learning Objectives:

This presentation will take you through an example of mapping or association using JPA and Hibernate annotations. By the end of this session, learners will be able to:

  • Demonstrate how to work with relationships between entities in Hibernate.

  • Describe the relationships and mapping annotations in JPA and Hibernate.

Hibernate Mapping and Relationship Association

Table of Contents

  • Hibernate Mapping and Relationship Overview.

  • Annotations - Hibernate Mapping and Relationship

  • Hibernate Mapping and Relationship Example.

  • Unidirectional and bidirectional Association/Mapping.

  • Many-to-One Relationship.

    • Many-To-One Relationship Example.

  • One-to-Many Relationship.

    • One-to-Many Relationship Example.

  • One-to-One Relationship.

    • One-to-One Relationship Example.

  • Many-to-Many Relationship.

    • Many-to-Many Relationship Example.

Hibernate Mapping and Relationship Overview

Hibernate is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. Hibernate can treat entities as both object-oriented classes and relational tables, and it is possible to create relationships between entities. The relationship between the two entities is called association. Hibernate mapping establishes the relationship (association) between tables as attributes in entity classes (model classes) that allow you to easily navigate the associations in models and queries. The relationships (associations) that can be established between entities include:

  • one-to-one — represents the one-to-one relationship between two tables.

  • one-to-many/many-to-one — represents the one-to-many relationship between two tables.

  • many-to-many — represents the many-to-many relationship between two tables. Each relationship can be mapped as a unidirectional or bi-directional relationship, which means that they can be modeled as an attribute on only one of the associated entities, or on both. This has no impact on database mapping, but it does determine in which direction the relationship can be used in the domain model and HQL.

Annotations - Hibernate Mapping and Relationship

AnnotationDescription

@ManyToOne

Defines that many of this entity can exist in another entity and stores that entity as a variable (e.g., staff can exist in a department; a relationship between a student and a library, in such a way that more than one student can be issued the same book).

@OneToMany

Defines that many other entities can relate to one of this entity and stores the entities in a list (e.g., department can have one-to-many staff; a relationship between a student and a library, in such a way that one student can be issued more than one type of book from the library).

@OneToOne

Only one of this entity can belong to one of another entity (e.g., Staff -> Teaching Staff or Non-Teaching Staff; relationship between a student and a library, in such a way that one student can be issued only one type of book).

@ManyToMany

Many of this entity can belong to many of another entity (e.g., Teachers -> Courses; relationship between a student and a library, in such a way that any number of students can be issued any type of book).

Note: many-to-one and one-to-many associations represent the same association from two different perspectives; it depends on which side of the relationship the entity is present.

Additional Annotations

  • Cascading: Entity relationships often depend on the existence of another entity. For example, a person–address relationship is dependent. Without the person, the address entity does not have any meaning of its own. When we delete the person entity, the address entity should also get deleted. This is achieved through Cascading. When performing an action on a target entity, the same action will be applied to the associated entity. Cascade types include ALL, PERSIST, MERGE, REMOVE, REFRESH, and DETACH.

Example: Hibernate Mapping and Relationship

  • The Entity Classes (Models):

    • Teacher

      • The individual teachers.

    • Department

      • The department to which the teacher belongs.

    • Credentials

      • The login information for each teacher.

    • Assigned Course

      • The courses that the teachers are assigned.

  • Relationships:

    • Teacher -> Department (Many → One)

    • Department -> Teacher (One → Many)

    • Teacher -> Credentials (One → One)

    • Teacher -> Assigned Course (Many → Many)

Unidirectional and bidirectional Association/Mapping

The Association/Mapping can be either Unidirectional or Bidirectional.

Unidirectional Association:

Unidirectional association means that only one entity has a relationship field or property that refers to the other. The source entity has a relationship field that refers to the target entity, and the source entity’s table contains the foreign key.

Bidirectional Association:

The term “bidirectional” literally means “functioning in two directions. In a bidirectional association, each entity (i.e. source and target) has a relationship field that refers to each other and the target entity’s table contains the foreign key. The source entity must use the mappedBy attribute to define the bidirectional mapping.

Many-To-One Relationship

In Hibernate, there are two ways to create Many-to-One relationships between entities:

  1. In a unidirectional manner (i.e. from Employee to Department - many-to-one relationship is applicable). This means that each employee record contains one department id, which should be a primary key in the Department table. Here in the Employee table, Department id is the foreign Key (did).

  2. Use Foreign Key association (we will use this technique in this course).

One-To-Many Relationship

In a one-to-many relationship, each row of one entity is referenced to many child records in another entity. The important thing is that child records cannot have multiple parents. In a one-to-many relationship between Table A and Table B, each row in Table A is linked to 0, 1, or many rows in Table B.

A @OneToMany association occurs when each record in one table corresponds to multiple records in a related table. In other words, we can say that the One-To-Many mapping comes into the category of collection-valued association where an entity is associated with a collection of other entities. In this type of association, the instance of one entity can be mapped with any number of instances of another entity.

@OneToMany association must create an intermediate table called “Join Table” that holds two foreign key columns. One foreign key column refers to the source table; the other foreign key column refers to the target table.

One-To-Many Relationship (continued)

  • @OneToMany association must create an intermediate table called “Join Table” that holds two foreign key columns. One foreign key column refers to the source table; the other foreign key column refers to the target table.

  • Having a unique foreign key for the target table also means that our collection (java.util.Collections) cannot have duplicates. A One-to-Many mapping can be implemented using a Set<E> java collection that does not contain any duplicate element so that every record is unique.

One-To-Many Relationship Example

  • Teacher.java Class

  • Department.java Class

App.java Class

  • One-To-Many Relationship Example Teacher Entity and Department Entity

public class App{
    public static void main( String[] args ){
        SessionFactory factory = new Configuration().configure().buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();

        Teacher t1 = new Teacher();
        t1.setTeachername("Haseeb");
        t1.setSalary("100");

        Teacher t2 = new Teacher();
        t2.setTeachername("Jenny Finch");
        t2.setSalary("10000");

        Teacher t3 = new Teacher();
        t3.setTeachername("James");
        t3.setSalary("25000");

        ArrayList<Teacher> teachlist = new ArrayList<Teacher>();
        teachlist.add(t1);
        teachlist.add(t2);
        teachlist.add(t3);

        session.persist(t1);
        session.persist(t2);
        session.persist(t3);

        //Creating Department
        Department department = new Department();
        department.setDname("Development");
        department.setTeacherList(teachlist);

        //Storing Department
        session.save(department);

        t.commit();
    }
}

Hands On LAB: Many-to-One and One-to-Many

  • Find the GLAB - 305.5.1 - Demonstration to ManyToOne and OneToMany Relationships and Mapping on Canvas under the Assignment section

  • If you have any technical questions while performing the lab activity, ask your instructors for assistance.

One-To-One Relationship

  • A @OneToOne association occurs when there is exactly one record in a table that corresponds to exactly one record in a related table. In this case, both tables will contain the same number of records, and each row of the first table is linked to another row in the second table.

  • A one-to-one relationship is where Table A has a special column (foreign-key column) referencing to the primary key column of Table B. Table A is known as the child-table; Table B is known as the parent-table.

  • In Hibernate, there are three ways to create one-to-one relationships between two entities.

    1. Using Foreign Key association (we will use this technique in this course).

    2. Using JOIN table.

    3. Using shared primary key.

    4. The Person can have one address and one address belongs to one person only.

Example: One-To-One Relationship Person Entity and Address Entity

  • Address.java Class

  • Person.java Class

public class App{
    public static void main( String[] args ){
        SessionFactory factory = new Configuration().configure().buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();

        Address a1 = new Address();
        a1.setCity("nyc");
        a1.setState("NY");
        a1.setStreet("27th street");
        a1.setZipcode(11103);

        Address a2 = new Address();
        a2.setCity("Bufflo");
        a2.setState("NY");
        a2.setStreet("28th street");
        a2.setZipcode(15803);

        Person p1 = new Person();
        p1.setAge(25);
        p1.setEmail("e.jon@email.com");
        p1.setName("elbert Adam");
        p1.setAdress(a1);

        Person p2 = new Person();
        p2.setAge(45);
        p2.setEmail("ch.fink@email.com");
        p2.setName("Christ fink");
        p2.setAdress(a2);

        session.persist(p1);
        session.persist(p2);
        session.persist(a1);
        session.persist(a2);

        t.commit();
    }
}

Hands On LAB: One-To-One Relationship

  • Find the lab GLAB - 305.5.2 - Demonstration of @OneToOne Relationship and Mapping on canvas under the Assignment section.

  • If you have any technical questions while performing the lab activity, ask your instructors for assistance.

Many-To-Many Relationship

  • A Many-to-Many relationship is where one or more rows from one entity are associated with more than one row in another entity.

  • @ManyToMany association must create an intermediate table called a Join Table that holds two foreign key columns. One foreign key column refers to the source table; the other foreign key column refers to the target table.

  • In the join table, there is no unique key constraint on any of the two foreign key columns so that many-to-many multiplicity can be achieved.

  • Having no unique foreign key in the join table also means that the collection can have duplicates, and the same target entity can be shared among different instances of the source entity's collection.

  • Typical examples for such a many-to-many association are (Products and Stores), (Class and Teacher), (employees and projects), and (groups and users).

  • In Hibernate, there are two ways to create many-to-many relationships between two entities:

    1. Using Foreign Key association

    2. Using JOIN table.

Example: Many-To-Many Relationship Cohort and Teacher Models

  • Cohort.java Class

  • Teacher.java Class

@Entity
@Table(name="Teacher")
public class Teacher{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int tit;
    private String salary;
    private String Teachername;

    @ManyToMany(targetEntity=Cohort.class)
    private Set CohortSet;

    public Teacher(String salary, String teachername, Set<Cohort> CohortSet) {
        this.salary = salary;
        this.Teachername = teachername;
        this.CohortSet = CohortSet;
    }

    public Teacher() { }

    public Set getCohortSet() {
        return CohortSet;
    }

    public void setCohortSet(Set cohortSet) {
        CohortSet = cohortSet;
    }

    public int getTit() {
        return tit;
    }

    public void setTit(int tit) {
        this.tit = tit;
    }

    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }

    public String getTeachername() {
        return Teachername;
    }

    public void setTeachername(String teachername) {
        Teachername = teachername;
    }
}

@Entity
@Table(name="cohort")
public class Cohort{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int cid;
    private String CName;
    private String duration;

    public Cohort( String cName, String duration) {
        CName = cName;
        this.duration = duration;
    }

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    public String getCName() {
        return CName;
    }

    public void setCName(String cName) {
        CName = cName;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }
}

public class App{
    public static void main( String[] args ){
        SessionFactory factory = new Configuration().configure().buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();

        //----Create Cohort/class Entity set one----
        Cohort Class1 = new Cohort("Java Developer", "14 weeks");
        Cohort Class2 = new Cohort("FullStack Developer", "7 Weeks");
        Cohort Class3 = new Cohort("Python Developer", "12 Weeks");

        //------ Store Cohort/ Class --------
        session.persist(Class1);
        session.persist(Class2);
        session.persist(Class3);

        //-----Create Cohort/Class one --------
        Set<Cohort> ClassSet1 = new HashSet<Cohort>();
        ClassSet1.add(Class1);
        ClassSet1.add(Class2);
        ClassSet1.add(Class3);

        //-----Create Cohort/Class two --------
        Set<Cohort> ClassSet2 = new HashSet<Cohort>();
        ClassSet2.add(Class2);
        ClassSet2.add(Class3);
        ClassSet2.add(Class1);

        //-----Create Cohort/Class three --------
        Set<Cohort> ClassSet3 = new HashSet<Cohort>();
        ClassSet3.add(Class3);
        ClassSet3.add(Class1);
        ClassSet3.add(Class2);

        Teacher t1 = new Teacher("100", "Haseeb", ClassSet1);
        Teacher t2 = new Teacher("200", "Jenny", ClassSet2);
        Teacher t3 = new Teacher("200", "Charlie", ClassSet3);

        session.persist(t1);
        session.persist(t2);
        session.persist(t3);

        t.commit();
    }
}

Hands-On LAB - Many-to-Many Relationship

  • Find the GLAB 305.5.3 - Demonstration of @ManytoMany Relationship and Mapping on canvas under the Assignment section

  • If you have any technical questions while performing the lab activity, ask your instructors for assistance.

Knowledge Check

  • What is a One-to-One association in Hibernate?

  • What is a One-to-Many association in Hibernate?

  • What is a Many-to-Many association in Hibernate?

Summary

  • Hibernate mappings establish the relationship between two database tables as attributes in your model that allows you to easily navigate the associations in your model and queries.

  • You can establish either unidirectional or bidirectional mapping.

  • The relationship that can be established between entities are:

    • one to one

    • one to many/many to one

    • many to many

References

Last updated