Updated April 17, 2023
Introduction to Hibernate One to Many
In simple terms, “One to Many” is a name given to a relationship between two tables defined in a database. If any entry in table A is related to more than one entry in table B, then that kind of relationship is known as “One to Many”. This relationship can be achieved with the help of a hibernate platform. Hibernate can link java-based front end applications to any database with the help of JPA annotations or xml. It comes preloaded with many functions, which can be called by adding linked libraries to your project.
Syntax of Hibernate One to Many
Syntax of Hibernate One to Many mapping is similar to one to one mapping but with a difference that there are more than one entries linked to one column rather than just one column mapping with another one.
There are certain syntaxes to be followed to establish one to many mapping using hibernate successfully, and those are:
- @entity annotation should be declared.
- @table annotation should be declared and define the table structure in the java page. Some related properties can also be declared in this annotation, for example, catalogue, unique Constraint.
- All data members and their getters and setters should be defined well.
- @Id and @GeneratedValue with strategy should be declared to mark any column in the table as a primary key. Other properties like if the column value should be unique and not null can also be defined here.
- @OneToMany annotation should be defined along with the table, which should be mapped to this column.
- All the first five steps should be repeated for other files too, where another table would be defined but with one added annotation of: @joinColumn along with the column name it would map to.
- Driver java application should be created, which would insert the records maintained in the tables created previously with the help of hibernate annotations. All the configurations, session maintenance, commit the data record related critical connector functions are maintained and called using this main java file.
How does “One to Many” Relationship work in Hibernate?
The one to many mapping annotations is used in the table, which has many entities to be mapped.
It looks like:
@OneToMany(mappedBy = “Student”, cascade = CascadeType.ALL)
Cascade rules are already defined in persistence libraries and have to be just called at the time of implementing the example. This table now should be linked with another table which has multiple entries. In this case, we are taking another table as “Marks”.
It looks like:
@ManyToOne
@JoinColumn(name = “S_id”)
There are a lot of coded logics and functions in the background under libraries which are called by the compiler with the help of these annotations.
Example of Hibernate One to Many
Here is the example of “One to Many” mapping using hibernate. You would require Eclipse, JPA libraries related RAR files, Maven and database installed in your system to run Hibernate related programs.
We are taking the example of a student and subject marks. There are two tables created in a database named “student” and “marks”. The relation between these two tables is one to many as one student can give multiple tests and get marks.
Student:
S_id |
S_name |
S_phno |
Marks:
S_id |
M_marks |
M_testid |
File 1: Student.java
Code:
package test
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "Student")
public class Student {
@Id
@GeneratedValue
@Column(name = "S_id")
private int id;
@Column(name = "S_name")
private String Name;
@Column(name = "S_phno")
private String Phone;
@OneToMany(mappedBy = "Student", cascade = CascadeType.ALL)
private Set marksDetails;
public Student() { }
public int getId() {
return S_id;
}
public void setId(long S_id) {
this.S_id = S_id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Set getMarksDetails() {
return marksDetails;
}
public void setMarksDetails(Set marksDetails) {
this.marksDetails = marksDetails;
}
}
File2: Marks.java
Code:
package test;
import javax.persistence.*;
@Entity
@Table(name = "Marks")
public class Marks {
@Id
@GeneratedValue
@Column(name = "M_testid")
private int M_testid;
@Column(name = "M_marks")
private String M_marks;
@ManyToOne
@JoinColumn(name = "S_id")
private Student student;
public Marks() { }
public int getTestId() {
return M_testid;
}
public void setTestId(int M_testid) {
this.M_testid = M_testid;
}
public String getMarks() {
return M_marks;
}
public void setMarks(String M_marks) {
this.M_marks = M_marks;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
File 3: Test.java
Code:
package test;
import org.hibernate.*;
public class Test {
static Session sO;
static SessionFactory sF;
private static SessionFactory buildSessionFactory() {
Configuration cO = new Configuration();
cO.configure("hibernate.cfg.xml");
ServiceRegistry sRO = new StandardServiceRegistryBuilder().applySettings(cO.getProperties()).build();
sFO = cO.buildSessionFactory(sRO);
return sFO;
}
public static void main(String[] args) {
System.out.println("...Example of hibernate one to many mapping...");
try {
sO = buildSessionFactory().openSession();
sO.beginTransaction();
Student studentObj = new Student("Name1", "0123456789");
sessionObj.save(studentObj);
Marks mObj = new Marks ("20", "90");
mObj.setStudent(studentObj);
sO.save(mObj);
Marks mObj = new Marks ("10", "100");
mObj.setStudent(studentObj);
sO.save(mObj);
sO.getTransaction().commit();
System.out.println("\n...Records successfully registered in the database...");
} catch(Exception sqlException) {
if(null != sO.getTransaction()) {
System.out.println("\n.......error......");
sO.getTransaction().rollback();
}
sqlException.printStackTrace();
} finally {
if(sO != null) {
sO.close();
}
}
}
}
Output:
Conclusion
Hibernate is a model to maintain object relations from front end applications developed on java to back end databases. One of the important relation types we have often worked on in databases directly is “One to Many”. It has become easy to create “One to Many” relations in tables using hibernate one to many mapping annotations. It is a clean and clutter-free method of working with database-intensive applications. It helps developers to focus on writing business logic independent of any database beneath. It is definitely one of the cool tools in the java world to work on databases.
Recommended Articles
This is a guide to Hibernate One to Many. Here we discuss the introduction; how does a “one to many” relationship work in hibernate? and example. You may also have a look at the following articles to learn more –