Hibernate One to Many Example using Annotation

In this segment, we will perform one-to-numerous relationship to outline list object of persevering class utilizing annotation.

Here, we are utilizing the situation of Forum where one inquiry has various answers.

In such case, there can be numerous responses for an inquiry and each answer may have its own data that is the reason we have utilized rundown in the constant class (containing the reference of Answer class) to speak to an accumulation of answers.

Example of One to Many mapping utilizing annotation

1) Create the Persistent class

This persevering class characterizes properties of the class including List.

Question.java package com.javacodegeeks;    

  • import javax.persistence.*;  
  • import java.util.List;    
  •   
  • @Entity  
  • @Table(name="q5991")  
  • public class Question {    
  •   
  • @Id   
  • @GeneratedValue(strategy=GenerationType.TABLE)  
  • private int id;    
  • private String qname;    
  •   
  • @OneToMany(cascade = CascadeType.ALL)  
  • @JoinColumn(name="qid")  
  • @OrderColumn(name="type")  
  • private List<Answer> answers;  
  • public int getId() {  
  •     return id;  
  • }  
  • public void setId(int id) {  
  •     this.id = id;  
  • }  
  • public String getQname() {  
  •     return qname;  
  • }  
  • public void setQname(String qname) {  
  •     this.qname = qname;  
  • }  
  • public List<Answer> getAnswers() {  
  •     return answers;  
  • }  
  • public void setAnswers(List<Answer> answers) {  
  •     this.answers = answers;  
  • }      
  • }  
  • Answer.java

    2) Add project information and configuration in pom.xml file.

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

    1. <dependency>  
    2.     <groupId>org.hibernate</groupId>  
    3.     <artifactId>hibernate-core</artifactId>  
    4.     <version>5.3.1.Final</version>  
    5. </dependency>  
    6.       
    7. <dependency>  
    8.     <groupId>com.oracle</groupId>  
    9.     <artifactId>ojdbc14</artifactId>  
    10.     <version>10.2.0.4.0</version>  
    11. </dependency>  

    3) Create the configuration file

    This file contains information about the database and mapping file.

    1. <?xml version='1.0' encoding='UTF-8'?>    
    2. <!DOCTYPE hibernate-configuration PUBLIC    
    3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
    4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
    5.     
    6. <hibernate-configuration>    
    7.     
    8.     <session-factory>    
    9.         <property name="hbm2ddl.auto">update</property>    
    10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
    11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>    
    12.         <property name="connection.username">system</property>    
    13.         <property name="connection.password">jtp</property>    
    14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>    
    15.      <mapping class="com.javacodegeeks.Question"/>   
    16.     </session-factory>    
    17.     
    18. </hibernate-configuration>    

    4) Create the class to store the data

    In this class we are storing the data of the question class.

    1. package com.javacodegeeks;    
    2.   
    3. import java.util.ArrayList;    
    4.   
    5. import org.hibernate.Session;  
    6. import org.hibernate.SessionFactory;  
    7. import org.hibernate.Transaction;  
    8. import org.hibernate.boot.Metadata;  
    9. import org.hibernate.boot.MetadataSources;  
    10. import org.hibernate.boot.registry.StandardServiceRegistry;  
    11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
    12. public class StoreData {    
    13. public static void main(String[] args) {    
    14.      
    15.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
    16.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
    17.       
    18.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
    19.     Session session=factory.openSession();  
    20.       
    21.     Transaction t=session.beginTransaction();    
    22.         
    23.     Answer ans1=new Answer();    
    24.     ans1.setAnswername("Java is a programming language");    
    25.     ans1.setPostedBy("Ravi Malik");    
    26.         
    27.     Answer ans2=new Answer();    
    28.     ans2.setAnswername("Java is a platform");    
    29.     ans2.setPostedBy("Sudhir Kumar");    
    30.         
    31.     Answer ans3=new Answer();    
    32.     ans3.setAnswername("Servlet is an Interface");    
    33.     ans3.setPostedBy("Jai Kumar");    
    34.         
    35.     Answer ans4=new Answer();    
    36.     ans4.setAnswername("Servlet is an API");    
    37.     ans4.setPostedBy("Arun");    
    38.         
    39.     ArrayList<Answer> list1=new ArrayList<Answer>();    
    40.     list1.add(ans1);    
    41.     list1.add(ans2);    
    42.         
    43.     ArrayList<Answer> list2=new ArrayList<Answer>();    
    44.     list2.add(ans3);    
    45.     list2.add(ans4);    
    46.         
    47.     Question question1=new Question();    
    48.     question1.setQname("What is Java?");    
    49.     question1.setAnswers(list1);    
    50.         
    51.     Question question2=new Question();    
    52.     question2.setQname("What is Servlet?");    
    53.     question2.setAnswers(list2);    
    54.         
    55.     session.persist(question1);    
    56.     session.persist(question2);    
    57.         
    58.     t.commit();    
    59.     session.close();    
    60.     System.out.println("success");    
    61. }    
    62. }   > import java.util.ArrayList; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; 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.cfg.xml").build(); Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build(); SessionFactory factory=meta.getSessionFactoryBuilder().build(); Session session=factory.openSession(); Transaction t=session.beginTransaction(); Answer ans1=new Answer(); ans1.setAnswername("Java is a programming language"); ans1.setPostedBy("Emma"); Answer ans2=new Answer(); ans2.setAnswername("Java is a platform"); ans2.setPostedBy("Olivia"); Answer ans3=new Answer(); ans3.setAnswername("Servlet is an Interface"); ans3.setPostedBy("Isabella"); Answer ans4=new Answer(); ans4.setAnswername("Servlet is an API"); ans4.setPostedBy("Charlotte"); ArrayList<Answer> list1=new ArrayList<Answer>(); list1.add(ans1); list1.add(ans2); ArrayList<Answer> list2=new ArrayList<Answer>(); list2.add(ans3); list2.add(ans4); Question question1=new Question(); question1.setQname("What is Java?"); question1.setAnswers(list1); Question question2=new Question(); question2.setQname("What is Servlet?"); question2.setAnswers(list2); session.persist(question1); session.persist(question2); t.commit(); session.close(); System.out.println("success"); } }

    Output

    Hibernate One to Many Example using Annotation 1
    Hibernate One to Many Example using Annotation 2

    How to fetch the data of List

    Here, we have used HQL to fetch all the records of Question class including answers. In such case, it fetches the data from two tables that are functional dependent.

    1. package com.javacodegeeks;    
    2. import java.util.*;  
    3. import javax.persistence.TypedQuery;  
    4. import org.hibernate.*;  
    5. import org.hibernate.boot.Metadata;  
    6. import org.hibernate.boot.MetadataSources;  
    7. import org.hibernate.boot.registry.StandardServiceRegistry;  
    8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
    9.     
    10. public class FetchData {    
    11. public static void main(String[] args) {    
    12.         
    13.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
    14.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
    15.       
    16.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
    17.     Session session=factory.openSession();  
    18.         
    19.     TypedQuery query=session.createQuery("from Question");    
    20.     List<Question> list=query.getResultList();    
    21.         
    22.     Iterator<Question> itr=list.iterator();    
    23.     while(itr.hasNext()){    
    24.         Question q=itr.next();    
    25.         System.out.println("Question Name: "+q.getQname());    
    26.             
    27.         //printing answers    
    28.         List<Answer> list2=q.getAnswers();    
    29.         Iterator<Answer> itr2=list2.iterator();    
    30.        while(itr2.hasNext())  
    31.        {  
    32.         Answer a=itr2.next();  
    33.             System.out.println(a.getAnswername()+":"+a.getPostedBy());  
    34.         }    
    35.     }  
    36.     session.close();    
    37.     System.out.println("success");    
    38. }    
    39. }    

    Output

    Question name : What is Java ?
    Java is a programming language : Emma Question name : What is Servelet ?
    Servelet is an Interface : Isabella Servelet is an API : Charlotte





    javacodegeeks is optimized for learning.© javacodegeeks .
    All Right Reserved and you agree to have read and accepted our term and condition