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 Architecture, Hibernate Configuration, HB Generator classes.
Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, Machine 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 problems, interview experiences, and interview bundle for placement preparations.
Do upvote our blog to help other ninjas grow.
Happy Coding!