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;
}
}
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;
}
}
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");
}
}
Output:






