Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
We must use one-to-many association to map the list element if the persistent class contains a list object that contains an entity reference.
For example, consider the Forum scenario in which one question has multiple answers.
There may be multiple answers to a question, and each answer may contain unique information, which is why we used a list in the persistent class to represent a collection of answers.
Persistent Class having list object
Let's start by learning about the persistent class that has list objects (containing Answer class objects).
package com.codingninjas;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<Answer> answers;
//getters and setters
}
You can also try this code with Online Java Compiler
There are list objects with entity references in the Question class (i.e., Answer class object). In this case, we must map this object using a one-to-many list. Let's check out how we can map it.
Persistent classes in Hibernate are Java classes whose objects or instances will be persisted in database tables. Hibernate performs best when these classes adhere to a few simple conventions, generally known as the Plain Old Java Object (POJO) programming paradigm.
This persistent class defines the class's attributes, including list.
Question.java
package com.codingninjas;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<Answer> answers;
//getters and setters
}
You can also try this code with Online Java Compiler
To retrieve every record in the Question class, including the responses, we used HQL. In this instance, it fetches the data from two functionally related tables.
Here, we are directly printing the object of the answer class in this case, but we have overridden the function toString() method in the Answer class, which returns the answername and poster name. As a result, instead of the reference id, it prints the answername and postername.
One of the main components of Hibernate is association mappings. Similar linkages to those in the relational database model are supported. As follows:
One-to-one relationships
many-to-one relationships
many-to-many relationships
What is HQL?
The abbreviation for Hibernate Query Language is HQL. It is a database-independent, object-oriented query language.
What is the One-to-Many association in Hibernate?
In this kind of linkage, a single thing may be connected to numerous other objects. In terms of the mapping, a Set Java collection without any unnecessary elements is used to implement the One-to-Many mapping. The set's One-to-Many element describes the relationship between a single object and many other things.
Conclusion
In this article, we have extensively discussed the One-to-many mapping in hibernate using XML, its example, and file mapping in hibernate project structure.