Collection Mapping in Hibernate

Posted By : Preeti Singh | 09-Dec-2020

Collection elements of the Persistent class can be mapped in Hibernate. Collection mapping as value type is supported by Hibernate. The collection is mapped into a separate table, in this mapping. When we have to persist property which is of data type like double, integer, long, float, etc, or object of wrapper classes or Strings, these types of properties are directly stored in the table of class. However, if we have to persist property which id of collection type then to save this property we need an additional collection table.

 

Hibernate supports following collection interfaces :

  • java.util.List
  • java.util.Set
  • java.util.SortedSet
  • java.util.Map
  • java.util.SortedMap
  • java.util.Collection
  • or write the implementation of org.hibernate.usertype.UserCollectionType

 

We will map a property of type set in the below example. Initially, we will create a class Employee with properties employeeId, employeeName, and phoneNumbers. Here we have a property phoneNumbers which represent the phone numbers of employees which could be multiple so phoneNumbers should be declared as collection types.

 

The code for this class is shown bellow:

 

package com.hibernate.collection;

import java.util.Set;

public class Employee {

    private int employeeId;

    private String employeeName;

    private Set<String> phoneNumbers;


      // Setter and getter for employeeId and employeeName

    public Set<String> getPhoneNumbers() {

        return phoneNumbers;

    }

    public void setPhoneNumbers(Set<String> phoneNumbers) {

        this.phoneNumbers = phoneNumbers;

    }

}

 

One to many mapping with join table in HIBERNATE:

 

One to many mapping in hibernate is made up of two entities. It is a 1 to N relationship. The first entity can have a relation with multiple second entity instances but the second can be associated with only one instance of first entity.

 

Let say, we have two entities i.e. EmployeeEntityDemo and AccountEntityDemo such that multiple accounts can be associated with a single employee, but one single account can not be shared between two or more employees.

 

This approach uses a join table to store the associations between account and employee entities. @JoinTable annotation has been used to make this association.

 

@Entity(name = "JoinTableEmployeeEntityDemo")

@Table(name = "Employee", uniqueConstraints = {

@UniqueConstraint(columnNames = "EMP_ID"),

@UniqueConstraint(columnNames = "EMAIL_ID") })

public class EmployeeEntity implements Serializable

{

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "EMP_ID", unique = true, nullable = false)

    private Integer empId;

    @Column(name = "EMAIL_ID", unique = true, nullable = false, length = 50)

    private String emailId;

    @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 50)

    private String fName;

    @Column(name = "LAST_NAME", unique = false, nullable = false, length = 50)

    private String lName;

    @OneToMany(cascade=CascadeType.ALL)

    @JoinTable(name="EMPLOYEE_ACCOUNT", joinColumns={@JoinColumn(name="EMPLOYEE_ID", referencedColumnName="ID")}

    , inverseJoinColumns={@JoinColumn(name="ACCOUNT_ID", referencedColumnName="ID")})

    private Set<AccountEntity> accountDetails;

    //Getters and setters

}

 

@Entity(name = "JoinTableAccountEntity")

@Table(name = "ACCOUNT", uniqueConstraints = {

@UniqueConstraint(columnNames = "ID")})

public class AccountEntity implements Serializable

{

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "ID", unique = true, nullable = false)

    private Integer accountId;

    @Column(name = "ACC_NUMBER", unique = true, nullable = false, length = 100)

    private String accNumber;

    //Getters and setters

}

public class TestTable

{

    public static void main(String[] args)

    {

        Session session = HibernateUtil.getSessionFactory().openSession();

        session.beginTransaction();

        AccountEntity accountObj1 = new AccountEntity();

        accountObj1.setAccountNumber("123-2334-333");

        AccountEntity accountObj2 = new AccountEntity();

        accountObj2.setAccountNumber("123-345-6542882");

        //Add new Employee object

        EmployeeEntity emp = new EmployeeEntity();

        emp.setEmail("[email protected]");

        emp.setFirstName("demoNew");

        emp.setLastName("newUser");

        Set<AccountEntity> accounts = new HashSet<AccountEntity>();

        accounts.add(account1);

        accounts.add(account2);

        emp.setAccounts(accounts);

        //Save Employee

        session.save(emp);

        session.getTransaction().commit();

        HibernateUtil.shutdown();

    }

}

 

At Oodles, we provide end-to-end SaaS development services with a focus on building high-quality websites and web applications using JavaScript-based technologies. Our development team is skilled at using Full stack development frameworks including AngularJS and NodeJS to build scalable and responsive web applications for clients. We have completed several Angular and MEAN stack development projects for clients from across the globe.

About Author

Author Image
Preeti Singh

Preeti Singh is a backend developer and has experience in developing web applications using java, j2EE, Spring Framework. In mean time she loves listening to music.

Request for Proposal

Name is required

Comment is required

Sending message..