Table of contents
1.
Introduction
2.
What are many to many annotations? 
2.1.
Creating Persistent classes in Many to Many annotations
2.1.1.
Questions.java
2.1.2.
Answers.java
2.2.
Adding project information and configuration in pic.xml file for Many to Many annotations
2.2.1.
pic.xml
2.3.
Creating the configuration file in Many to Many annotations
2.3.1.
hibernate_config.cfg.xml
2.4.
Creating the class for storing the data in Many to Many annotations
2.4.1.
Store_Data.java
3.
Frequently Asked Questions  
3.1.
What is a POJO class in Java?
3.2.
What is an XML file?
3.3.
What is HQL?
4.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Many to Many Annotations

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hibernate makes use of an XML mapping file for the transformation of data to database tables from POJO and vice versa. Hibernate annotations are the newest method for defining mappings without the use of an XML file. Hibernate Annotations are a powerful way to provide the metadata for the Object and Relational Table mapping. 

So, in this article, we will discuss Many to Many annotations in detail.

What are many to many annotations? 

Many to Many annotations are also called Many-to-Many relations. In this kind of annotation, one attribute is mapped to another attribute in such a way that any number of attributes may be linked to other attributes with zero restriction on the number.

This can be better understood with an instance. For example, there is a list of questions and another list of answers. Now, each question may have more than one answer and also, one answer may satisfy more than one question. This is a perfect example of Many-to-Many annotations. 

Let us look at it in more depth.

Creating Persistent classes in Many to Many annotations

Questions.java

package codingninjas;

import java.util.List;
import javax.persistence.*;

@Entity
@Table(name = "ques11123")
public class Questions {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int ques_id;

  private String quesname;

  @ManyToMany(targetEntity = Answers.class, cascade = { CascadeType.ALL })
  @JoinTable(
    name = "ques_ans11123",
    joinColumns = { @JoinColumn(name = "ques_id") },
    inverseJoinColumns = { @JoinColumn(name = "ans_id") }
  )
  private List<Answers> Answers;

  public int getId() {
    return ques_id;
  }

  public void setId(int ques_id) {
    this.ques_id = ques_id;
  }

  public String getQuesname() {
    return quesname;
  }

  public void setQuesname(String quesname) {
    this.quesname = quesname;
  }

  public List<Answer> getAnswers() {
    return answers;
  }

  public void setAnswers(List<Answer> answers) {
    this.answers = answers;
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Answers.java

package codingninjas;

import javax.persistence.*;

@Entity
@Table(name = "ques_ans11123")
public class Answers {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int ans_id;

  private String answersname;
  private String posted_by;

  public int getId() {
    return ans_id;
  }

  public void setId(int ans_id) {
    this.ans_id = ans_id;
  }

  public String getAnswersname() {
    return answersname;
  }

  public void setAnswersname(String answersname) {
    this.answersname = answersname;
  }

  public String getPosted_by() {
    return posted_by;
  }

  public void setPosted_by(String posted_by) {
    this.posted_by = posted_by;
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Adding project information and configuration in pic.xml file for Many to Many annotations

Open pom.xml file and click source. Then, add the below dependencies between <dependencies>....</dependencies> tag.

pic.xml

<dependency>    
    <groupId>org.hibernate</groupId>    
    <artifactId>hibernate-core</artifactId>    
    <version>5.3.1.Final</version>    
</dependency>    


<dependency>    
    <groupId>com.oracle</groupId>    
    <artifactId>ojdbc14</artifactId>    
    <version>10.2.0.4.0</version>    
</dependency>     

Creating the configuration file in Many to Many annotations

This file has data about the database and mapping file.

hibernate_config.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>    
<!DOCTYPE hibernate-configuration PUBLIC    
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
    
<hibernate-configuration>    
    
    <session-factory>    
        <property name="hbm2ddl.auto">create</property>    
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>    
        <property name="connection.username">system</property>    
        <property name="connection.password">jtp</property>    
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>    
    <mapping class="com.codingninjas.Questions"/>    
    <mapping class="com.codingninjas.Answers"/>  
    </session-factory>    
    
</hibernate-configuration>  

Creating the class for storing the data in Many to Many annotations

Store_Data.java

package codingninjas;

import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class StoreData {

  public static void main(String[] args) {
    StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
      .configure("hibernate_config.cfg.xml")
      .build();
    Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
    SessionFactory factory = meta.getSessionFactoryBuilder().build();
    Session session = factory.openSession();
    Transaction t = session.beginTransaction();

    Questions q1 = new Questions();
    q1.setQuesname("What is orange?");

    Answers a1 = new Answers();
    a1.setAnswersname("Orange is a color.");
    a1.setPosted_by("Coder 1");

    Answers a2 = new Answers();
    a2.setAnswersname("Orange is also a fruit");
    a2.setPosted_by("Coder 2");

    ArrayList<Answers> list1 = new ArrayList<Answers>();
    list1.add(a1);
    list1.add(a2);
    q1.setAnswers(list1);

    Questions q2 = new Questions();
    q2.setQuesname("What is ‘leave’?");

    Answers a3 = new Answers();
    a3.setAnswersname("Leave is a verb.");
    a3.setPosted_by("Coder 3");

    Answers a4 = new Answers();
    a4.setAnswersname("Leave is a noun.");
    a4.setPosted_by("Coder 4");

    ArrayList<Answers> list2 = new ArrayList<Answers>();
    list2.add(a3);
    list2.add(a4);
    q2.setAnswers(list2);

    session.persist(q1);
    session.persist(q2);

    t.commit();
    session.close();
    System.out.println("Done");
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output: 

Question Table

 
 

Answer Table

Frequently Asked Questions  

What is a POJO class in Java?

POJO stands for Plain Old Java Object. It is an ordinary Java object that is not bound by any special restriction other than those forced by the Java language specification and does not requires any classpath. POJOs increase the reusability and readability of a program.

What is an XML file?

An XML file stands for Extensible Markup Language file, and it is used to structure data for transport and storage. In an XML file, there are both text and tags..     

What is HQL?

HQL stands for Hibernate Query Language. It is an object-oriented query language, like SQL, but instead of operating on columns and labels. HQL works with persistent objects and their properties.

Conclusion 

This article extensively discusses the concept of Many to Many annotations in detail. It goes on to mention the code involved and the examples. 

To hold a tight grip on the topic, we recommend going through the topics:Hibernate annotationsOne To One AnnotationOne To Many Annotation and Many To One Annotation.

We hope that this blog has helped you enhance your knowledge regarding Many-to-Many annotations, and if you would like to learn more, check out our articles on Coding Ninjas Blogs

You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSQLSystem Design, 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 organized 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.

Nevertheless, you may consider our Courses to give your career an edge over others!

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass