Syntax and Examples of Hibernate One to Many

Syntax and Examples of Hibernate One to Many
Techiio-author
Written by Sagar RabidasFebruary 18, 2022
10 min read
Hibernate
4 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 4 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

In this blog, we will discuss Syntax and Examples of Hibernate One to Many.

Introduction to Hibernate One to Many:-

In easy terms, “one to many” is a name given to a relationship among tables described in a database. If any entry in table a is associated with a couple of access in desk b, then that type of relationship is called “one to many”. This dating can be completed with the help of a hibernate platform. Hibernate can hyperlink java-primarily based the front-cease programs to any database with the assist of JPA annotations or XML. It comes preloaded with many functions, which may be referred to as with the aid of adding related libraries in your task.

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 is more than one entry linked to one column rather than just one column mapping with another one.

There are certain syntaxes to be followed to establish one too 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, catalog, 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 hibernating 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 that 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 too 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();
}
}
}
}

Conclusion:-

Hibernate is a version to hold item family members from front-stop programs evolved on java to back-cease databases. One of the important relation kinds we've got often labored on in databases without delay is “one to many”. It has to turn out to be easy to create “one to many” members of the family in tables using hibernate one to many mapping annotations. It's far a clean and clutter-unfastened technique of operating with database-intensive applications. It enables builders to focus on writing business logic impartial of any database. It's far one of the cool pieces of equipment in java international to work on databases.

Hibernate
Hibernate OnetoMany
Java
4 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 4 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+8 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance