Table of contents
1.
Introduction
1.1.
Hibernate supports following collection interfaces:
2.
How Collection Mapping works
2.1.
Mapping a Primitive Type
2.2.
Mapping an Object Type
3.
Mapping List
4.
Mapping Set
5.
Mapping Maps
6.
Mapping sorted sets
7.
Mapping Enums
8.
When should you use Collection Mapping
9.
Frequently Asked Questions
9.1.
What distinguishes spring boot from hibernate?
9.2.
What are ORM and JPA?
9.3.
What does Hibernate's lazy loading mean?
9.4.
What is the use of generator class in hibernate?
9.5.
What is Association in Hibernate?
10.
Conclusion
Last Updated: Mar 27, 2024
Medium

Hibernate collections mappings

Author Ayush Tiwari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Collection mapping is supported as a value type by Hibernate. The collection is mapped into a separate table in this mapping.

When a class's data-type properties like integers, longs, floats, or objects from wrapper classes or strings need to be persistent, they are directly stored in the class's table. To save this property, however, we need an additional collection table if the class property is of the collection type.

Hibernate supports following collection interfaces:

  1. java.util.Set – java.util.HashSet is used to store value.
  2. java.util. - TreeSet is used to store value.
  3. java.util.List – java.util.ArrayList is used to store value. Preserves the position with an index column
  4. Bag semantics – java.util.ArrayList is used to store valre however the position is not preserved.
  5. java.util.Map – java.util.HashMap is used to store value.
  6. java.util.SortedMap – java.util.TreeMap is used to store value.

How Collection Mapping works

To support collection mapping, JPA offers an annotation referred to as @ElementCollectionOn the Collection that you want to persist to the database, you must specify this annotation. You can map a collection that contains both primitive and non-primitive (object) data using collection mapping.

Mapping a Primitive Type

You only need to specify the @ElementCollection annotation on the field that corresponds to the collection in order to map a collection that contains primitive types of data. Hibernate will automatically persist the collection along with the main entity whenever you attempt to persist the main entity. The values in the Collection are transferred to a new table that Hibernate creates. This method can be used to map a List, Set, or Map. A thorough code sample will be provided in a different article by me.

Mapping an Object Type

If the collection contains objects, you must specify the @ElementCollection annotation on the field corresponding to the collection, just like you would for a primitive type collection. Additionally, the class whose objects are in the Collection must have the @Embeddable annotation specified. Hibernate will automatically persist the collection along with the main entity whenever you attempt to persist the main entity. A new table with columns for each field in the @Embeddable class is created by Hibernate. Records that match the objects in the Collection are inserted. This method can be used to map a List, Set, or Map.

Mapping List

A List is a Java collection that allows duplicate elements and stores elements in order. Each element's placement in the list can be precisely controlled by the user of this interface. The user can search for elements in the list and access elements by their integer index. Formally speaking, lists typically permit pairs of elements e1 and e2 such that e1.equals(e2), and if they do allow null elements at all, they typically permit multiple null elements. 

As an alternative to mapping a list, you could map a Java array. With the exception of the element and attribute names ("array" and "array-index"), an array mapping is essentially identical to the previous example. However, applications using Hibernate rarely use arrays for the reasons previously mentioned.

To learn more follow Mapping List 

When keeping track of order position is required and duplicates of the elements are acceptable, lists are used. The additional annotation @OrderColumn, which specifies the name of the column to track the element order/position (name defaults to property> ORDER), is what we're going to use in this case:

@Entity 
@Table(name=”studentId”)
Public class Student{
…..
…..
@ElementCollection 
@CollectionTable( name=”image”)
@OrderColumn 
@Column(name=”file_name”)
private List<string> images = new ArrayList<string>();
…..
…..
}

Mapping Set

Declares an element collection mapping with @ElementCollection. A separate table houses the information for the collection.

Gives the name of the table that will house the collection in the @CollectionTable attribute. additionally offers the join column to make reference to the main table.

@Column - The name of the column in the collection table that is to be mapped.

The following relationships are defined using @ElementCollection: Java primitives (wrappers), such as int, integer, double, date, string, etc., have a one-to-many relationship to a @Embeddable object and a one-to-many relationship to a Basic object.

Right about now, you're probably wondering how this compares to @OneToMany.

In contrast to @OneToMany, @ElementCollection's target object is not a @Entity. These annotations provide a simple means of defining a collection of straightforward/basic objects. Target objects, however, cannot be queried, persistent, or merged separately from their parent object. As there is no cascade option supported by ElementCollection, target objects are ALWAYS saved, merged, and deleted along with their parent object.

@Entity 
@Table(name=”studentId”)
Public class Student{
…..
…..
@ElementCollection 
@CollectionTable( 
         name=”image”,
        joinColumns=@JoinColumn(name=”student_id”))
@Column(name=”file_name”)
private Set<string> images = new HashSet<string>();
…..
…..
}

Mapping Maps

Maps should probably be used when you want to access data using a key rather than an integer index. The additional map annotation @MapKeyColumn aids in defining the name of the key column for a map. The name is always property> KEY:

@Entity 
@Table(name=”studentId”)
Public class Student{
…..
…..
@ElementCollection 
@CollectionTable( name=”image”)
@MapKeyColumn(name=”file_name”)
@Column(name=”image_name”)
private Map<string> images = new HashMap<string>();
…..
…..
}

Mapping sorted sets

The set is an unsorted collection of unique items, as we already mentioned. What happens, though, if we don't require duplicates and retrieval order is also crucial? When a collection is retrieved, we can use @OrderBy to specify the ordering of the elements.

Syntax: @OrderBy(“[field name or property name] [ASC |DESC]”)

@Entity 
@Table(name=”studentId”)
Public class Student{
…..
…..
@ElementCollection 
@CollectionTable( name=”image”)
@OrderBy(“file_name” = “image”)
@Column(name=”file_name”)
private Set<string> images = new LinkedHashSet<string>();
…..
…..
}

Mapping Enums

Hibernate maps an enum to a number by default. Although there is a high likelihood that adding or removing a value from your enum will alter the ordinal of the remaining values, this mapping is very effective. As a result, you ought to use the @Enumerated annotation to map the enum value to a String. An Enum type is referenced by this annotation, which stores the field's data as a String in the database.

@Entity 
@Table(name=”studentId”)
Public class Student{
…..
@Id 
@GeneratedValue(strategy = Generated)
private int id;
@Column(name=”first_name”)
private String firstName;
…. 
….
@Enumerated(EnumType.STRING)
@column(name=”status”)
private Status = status; 
…..
…..
}

When should you use Collection Mapping

Collection mapping has some drawbacks despite appearing to be simple to use. For starters, the collection's elements cannot be saved or queried separately. In addition, Hibernate replaces all of the records in the corresponding table with new ones if the collection is changed and the entity is saved. Therefore, this is not very effective. Therefore, only very small collections should be mapped using collection mappings. A one-to-many association is preferable in all other circumstances.

Must Read Array of Objects in Java

Frequently Asked Questions

What distinguishes spring boot from hibernate?

While Hibernate framework is suitable for object-relational persistence, access data layers, and query retrieval services for enterprise-level applications, the Spring framework is helpful for transaction management, dependency injection, and aspect-oriented programming for applications.

What are ORM and JPA?

Java objects are changed into database tables through a technique known as object-relational mapping (ORM). In other words, this enables SQL-free interaction with a relational database. How to persist data in Java programs is specified by the Java Persistence API (JPA) specification.

What does Hibernate's lazy loading mean?

Lazy setting is used to determine whether to load child objects while loading the parent object This setting must be made in the parent class's appropriate hibernate mapping file. True = Lazy (means not to load child) then the child objects' sluggish loading is enabled by default.

What is the use of generator class in hibernate?

When creating an ID for an item that will be used as a primary key in the database, a generator class is utilized. The persistent class's objects have an ID as a special identification. According to our needs, we can use any generator classes in our program.

What is Association in Hibernate?

One of the main components of JPA and Hibernate is association mapping. In your domain model, they represent the connection between two database tables as attributes. This lets you explore your domain model's associations, and JPQL or Criteria queries easily.

Conclusion

In this article, we have extensively discussed the Hibernate collection mapping.

We hope this blog has helped you enhance your knowledge regarding Hibernate collection mapping. If you want to learn more, check out our articles on Hibernate ArchitectureHibernate ConfigurationHB Generator classes.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Live masterclass