Hibernate

1. Hibernate Example using XML in Eclipse.

First we need to add jar files.

Creating Persistent Class

Student.java

public class Student {
private int id;
private String firstName,lastName;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
}  
Creating mapping file for persistent class

student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
 <hibernate-mapping>
  <class name="com.hib.mypackage.Student" table="std100">
    <id name="id">
     <generator class="assigned"></generator>
    </id>
    <property name="firstName"></property>
    <property name="lastName"></property>
  </class>
 </hibernate-mapping>  
Creating configuration File

hibernate.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">update</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">oracle</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <mapping resource="employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>  
Creating class to retrieve or store persistent object
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();
         Student s1=new Student();
            s1.setId(1);
            s1.setFirstName("Raj");
            s1.setLastName("Mehta");
       session.save(s1);
       t.commit();
       System.out.println("successfully saved");
        factory.close();
        session.close();
    }
}  

2. Hibernate example using Annotation in Eclipse

First, we need to create maven project

Adding project information and configuration in pom.xml file

<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>  

Due to certain license issues, Oracle drivers are not present in public Maven repository. We can install it manually. To install Oracle driver into your local Maven repository

Creating persistence class

Here, we are creating the same persistent class which we have created in the previous topic. But here, we are using annotation.

@Entity annotation marks this class as an entity.

@Table annotation specifies the table name where data of this entity is to be persisted. If you don’t use @Table annotation, hibernate will use the class name as the table name by default.

@Id annotation marks the identifier for this entity.

@Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name by default.

Student.java

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name= "emp500")
public class Employee {
@Id
private int id;
private String firstName,lastName;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
}   
Creating config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
    <session-factory>
    <property name="hbm2ddl.auto">update</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.hib.mypackage.Student"/>
    </session-factory>
</hibernate-configuration>  
Create class to retrieve or store the persistent object
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();
    Student s1=new Student();
    s1.setId(101);
    s1.setFirstName("Raj");
    s1.setLastName("Mehta");
    session.save(s1);
    t.commit();
    System.out.println("successfully saved");
    factory.close();
    session.close();
}
}  

3. Hibernate Logging by Log4j using xml file

First , we need to load the slf4j.jar and log4j.jar file.

Creating log4j.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
    debug="false">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
 <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m%n" />
 </layout>
</appender>
    <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
</appender>
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="C:/kodnest.log" />
    <param name="MaxBackupIndex" value="100" />
 <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m%n" />
</layout>
</appender>
    <category name="org.hibernate">
        <priority value="DEBUG" />
    </category>
    <category name="java.sql">
        <priority value="debug" />
    </category>
    <root>
        <priority value="INFO" />
        <appender-ref ref="FILE" />
    </root>
</log4j:configuration>  

4. Hibernate Logging by Log4j using properties files

First , we need to load the slf4j.jar and log4j.jar file.

Creating log4j.properties file

log4j.properties

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\kodnesthibernate.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=INFO, file, stdout
# Log everything. Good for troubleshooting
log4j.logger.org.hibernate=INFO
# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL 

5. Table per class hierachy

In this example we are creating the three classes and provide mapping of these classes in the student.hbm.xml file.

Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let’s create the three classes for the above hierarchy:

Employee.java

package com.kodnest.mypackage;
public class Employee {
private int id;
private String name;
//getters and setters
}  

Regular_Employee.java

package com.kodnest.mypackage;
public class Regular_Employee extends Employee{
private float salary;
private int bonus;
//getters and setters
}  

Contract_Employee.java

package com.kodnest.mypackage;
public class Contract_Employee extends Employee{
    private float pay_per_hour;
    private String contract_duration;
//getters and setters
}  
Creating mapping file for persistence class

employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.kodnest.mypackage.Employee" table="emp121" discriminator-value="emp">
<id name="id">
<generator class="increment"></generator>
</id>
<discriminator column="type" type="string"></discriminator>
<property name="name"></property>
<subclass name="com.kodnest.mypackage.Regular_Employee" discriminator-value="reg_emp">
<property name="salary"></property>
<property name="bonus"></property>
</subclass>
<subclass name="com.kodnest.mypackage.Contract_Employee" discriminator-value="con_emp">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</subclass>
</class>
</hibernate-mapping>  

Adding map of hbm file in configuration file

hibernate.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">update</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 resource="employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>  
Creating the class that stores the persistent object

StoringData.java

package com.kodnest.mypackage;
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 StoringData {
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();
    Employee e1=new Employee();
    e1.setName("Raj Mehta");
    Regular_Employee e2=new Regular_Employee();
    e2.setName("Ram");
    e2.setSalary(50000);
    e2.setBonus(5);
    Contract_Employee e3=new Contract_Employee();
    e3.setName("Karan");
    e3.setPay_per_hour(1000);
    e3.setContract_duration("15 hours");
    session.persist(e1);
    session.persist(e2);
    session.persist(e3);
    t.commit();
    session.close();
    System.out.println("success");
}
}

6. Hibernate Table Per Hierarchy using Annotation

Creating the Persistent class

Employee.java

package com.kodnest.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee101")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="employee")
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
//setters and getters
}

Regular_Employee.java

package com.kodnest.mypackage;
import javax.persistence.*;
@Entity
@DiscriminatorValue("regularemployee")
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
//setters and getters
}  

Contract_Employee.java

package com.kodnest.mypackage;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("contractemployee")
public class Contract_Employee extends Employee{
    @Column(name="pay_per_hour")
    private float pay_per_hour;
    @Column(name="contract_duration")
    private String contract_duration;
    //setters and getters
}  
Adding project information and configuration in pom.xml file
<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>  
Adding the persistent class in configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
    <session-factory>
    <property name="hbm2ddl.auto">update</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.kodnest.mypackage.Employee"/>
        <mapping class="com.kodnest.mypackage.Regular_Employee"/>
        <mapping class="com.kodnest.mypackage.Contract_Employee"/>
    </session-factory>
</hibernate-configuration> 
Creating class for storing persistent object

Storingtest.java

package com.kodnest.mypackage;
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 StoreTest {
    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();
            Employee e1=new Employee();
            e1.setName("Raj Mehta");
            Regular_Employee e2=new Regular_Employee();
            e2.setName("Ram");
            e2.setSalary(50000);
            e2.setBonus(5);
            Contract_Employee e3=new Contract_Employee();
            e3.setName("Karan");
            e3.setPay_per_hour(1000);
            e3.setContract_duration("15 hours");
            session.persist(e1);
            session.persist(e2);
            session.persist(e3);
            t.commit();
            session.close();
            System.out.println("success");
    }
}  

7. Example for Table per Concrete class using Annotation

Creating the persistent class

Employee.java

package com.kodnest.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee102")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
//setters and getters
}  

Regular_Employee.java

package com.kodnest.mypackage;
import javax.persistence.*;
@Entity
@Table(name="regularemployee102")
@AttributeOverrides({
    @AttributeOverride(name="id", column=@Column(name="id")),
    @AttributeOverride(name="name", column=@Column(name="name"))
})
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
//setters and getters
}  

Contract_Employee.java

package com.kodnest.mypackage;
import javax.persistence.*;
@Entity
@Table(name="contractemployee102")
@AttributeOverrides({
    @AttributeOverride(name="id", column=@Column(name="id")),
    @AttributeOverride(name="name", column=@Column(name="name"))
})
public class Contract_Employee extends Employee{
    @Column(name="pay_per_hour")
    private float pay_per_hour;
    @Column(name="contract_duration")
    private String contract_duration;
    public float getPay_per_hour() {
        return pay_per_hour;
    }
    public void setPay_per_hour(float payPerHour) {
        pay_per_hour = payPerHour;
    }
    public String getContract_duration() {
        return contract_duration;
    }
    public void setContract_duration(String contractDuration) {
        contract_duration = contractDuration;
    }
}
Adding project information and configuration in pom.xml file
<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>  
Adding mapping of hbm file in configuration file

hibernate.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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
    <session-factory>
        <property name="hbm2ddl.auto">update</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.kodnest.mypackage.Employee"/>
        <mapping class="com.kodnest.mypackage.Contract_Employee"/>
        <mapping class="com.kodnest.mypackage.Regular_Employee"/>
    </session-factory>
</hibernate-configuration>  
Creating the class that stores the persistence object

StoringData.java

package com.kodnest.mypackage;
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();
        Employee e1=new Employee();
        e1.setName("Raj Mehta");
        Regular_Employee e2=new Regular_Employee();
        e2.setName("Ram");
        e2.setSalary(50000);
        e2.setBonus(5);
        Contract_Employee e3=new Contract_Employee();
        e3.setName("Karan");
        e3.setPay_per_hour(1000);
        e3.setContract_duration("15 hours");
        session.persist(e1);
        session.persist(e2);
        session.persist(e3);
        t.commit();
        session.close();
        System.out.println("success");
    }
}

8. Example for Mapping list in collection mapping

Creating persistence class
package com.kodnest;
import java.util.List;
public class MapExample {
private int id;
private String qname;
private List<String> answers;
//getters and setters
}  
Creating Mapping file for persistent class
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
 <class name="com.kodnest.MapExample" table="q100">
   <id name="id">
     <generator class="increment"></generator>
   </id>
   <property name="qname"></property>
   <list name="answers" table="ans100">
     <key column="qid"></key>
     <index column="type"></index>
     <element column="answer" type="string"></element>
   </list>
 </class>
</hibernate-mapping>
Creating Configuration file
<?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">update</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 resource="MapExample.hbm.xml"/>
    </session-factory>
</hibernate-configuration>  
Creating class to store data
package com.kodnest;
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 StoringData {
 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();
    ArrayList<String> list1=new ArrayList<String>();
    list1.add("Hello");
    list1.add("World");
    ArrayList<String> list2=new ArrayList<String>();
    list2.add("Hello");
    list2.add("Java");
    MapExample me=new MapExample();
    me.setQname("How are you?");
    me.setAnswers(list1);
    MapExample me2=new MapExample();
    me2.setQname("Are you awake?");
    me2.setAnswers(list2);
    session.persist(me);
    session.persist(me2);
    t.commit();
    session.close();
    System.out.println("success");
 }
}    
Fetching data from list
package com.kodnest;
import javax.persistence.TypedQuery;
import java.util.*;
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 FetchData {
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();
    TypedQuery query=session.createQuery("from Question");
    List<Question> list=query.getResultList();
    Iterator<Question> itr=list.iterator();
    while(itr.hasNext()){
        Question q=itr.next();
        System.out.println("Question Name: "+q.getQname());
        //printing answers
        List<String> list2=q.getAnswers();
        Iterator<String> itr2=list2.iterator();
        while(itr2.hasNext()){
            System.out.println(itr2.next());
        }
    }
    session.close();
    System.out.println("success");
}
}    

9.Example for Mapping bag in collection mapping

Creating Persistent class
package com.kodnest;
import java.util.List;
public class MapBagExample {
private int id;
private String qname;
private List<String> answers;
//getters and setters
}  
Creating Mapping file for persistent class
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
 <class name="com.kodnest.MapBagExample" table="q101">
   <id name="id">
     <generator class="increment"></generator>
   </id>
   <property name="qname"></property>
   <bag name="answers" table="ans101">
     <key column="qid"></key>
     <element column="answer" type="string"></element>
   </bag>
 </class>
</hibernate-mapping>  
Creating configuration file
<?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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
    <session-factory>
        <property name="hbm2ddl.auto">update</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 resource="MapBagExample.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
Creating class to store data
package com.kodnest;
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 StoringData {
 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.buildSessionFactory();
     Session session=factory.openSession();
    Transaction t=session.beginTransaction();
    ArrayList<String> list1=new ArrayList<String>();
    list1.add("Hello");
    list1.add("World");
    ArrayList<String> list2=new ArrayList<String>();
    list2.add("Hello");
    list2.add("Java");
    MapBagExample mbe=new MapBagExample();
    mbe.setQname("How are you ?");
    mbe.setAnswers(list1);
    MapBagExample mbe2=new MapBagExample();
    mbe2.setQname("Are you awake?");
    mbe2.setAnswers(list2);
    session.persist(mbe);
    session.persist(mbe2);
    t.commit();
    session.close();
    System.out.println("success");
 }
}    

10. Example for Mapping set in collection mapping.

Creating persistent class
package com.kodnest;
import java.util.Set;
public class MapSetExample {
private int id;
private String qname;
private Set<String> answers;
//getters and setters
}  
Creating mapping file for persistence class
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
 <class name="com.kodnest.MapSetExample" table="q1002">
   <id name="id">
     <generator class="increment"></generator>
   </id>
   <property name="qname"></property>
   <set name="answers" table="ans1002">
     <key column="qid"></key>
     <element column="answer" type="string"></element>
   </set>
 </class>
</hibernate-mapping>  
Creating configuration file
<?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">update</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 resource="MapSetExample.hbm.xml"/>
    </session-factory>
</hibernate-configuration>  
Creating class to store data
package com.kodnest;
import java.util.HashSet;
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 StoringData {
 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();
    HashSet<String> set1=new HashSet<String>();
    set1.add("Hello");
    set1.add("World");
    HashSet<String> set2=new HashSet<String>();
    set2.add("Hello");
    set2.add("Java");
    MappingSetExample mse=new MappingSetExample();
    mse.setQname("How are you  ?");
    mse.setAnswers(set1);
    MappingSetExample mse2=new MappingSetExample();
    mse2.setQname("Are you awake?");
    mse2.setAnswers(set2);
    session.persist(mse);
    session.persist(mse2);
    t.commit();
    session.close();
    System.out.println("success");
 }
}    

11. Example for Mapping Map in collection mapping

MappingMapExample.java

package com.kodnest;
import java.util.Map;
public class MappingMapExample {
private int id;
private String name,username;
private Map<String,String> answers;
public Question() {}
public Question(String name, String username, Map<String, String> answers) {
    super();
    this.name = name;
    this.username = username;
    this.answers = answers;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public Map<String, String> getAnswers() {
    return answers;
}
public void setAnswers(Map<String, String> answers) {
    this.answers = answers;
}
}  
Creating mapping file for persistence class

MappingMapExample.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.kodnest.MappingMapExample" table="question736">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="username"></property>
<map name="answers" table="answer736" cascade="all">
<key column="questionid"></key>
<index column="answer" type="string"></index>
<element column="username" type="string"></element>
</map>
</class>
</hibernate-mapping>
Creating configuration file

hibernate.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">update</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 resource="MappingMapExample.hbm.xml"/>
    </session-factory>
</hibernate-configuration>  
Creating class to store data
package com.kodnest;
import java.util.HashMap;
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 StoringData {
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();
HashMap<String,String> map1=new HashMap<String,String>();
map1.put("Hello","World");
map1.put("Hello","Java");
HashMap<String,String> map2=new HashMap<String,String>();
map2.put("World","Hello");
map2.put("Java","Hello");
map2.put("HelloWorld","HelloJava");
MappingMapExample mme=new Question("How are you?","Raj",map1);
MappingMapExample mme2=new Question("Are you awake?","Ram",map2);
session.persist(mme);
session.persist(mme2);
t.commit();
session.close();
System.out.println("successfully stored");
}
}

12. Example for One to Many mapping in Hibernate by List.

Creating persistence class
package com.kodnest;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<Answer> answers;
//getters and setters
}  
package com.kodnest;
public class Answer {
private int id;
private String answername;
private String postedBy;
//getters and setters
}
}  
Creating mapping file for persistent class
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
          <hibernate-mapping>
          <class name="com.kodnest.Question" table="q501">
          <id name="id">
          <generator class="increment"></generator>
          </id>
          <property name="qname"></property>
          <list name="answers" cascade="all">
          <key column="qid"></key>
          <index column="type"></index>
          <one-to-many class="com.kodnest.Answer"/>
          </list>
          </class>
          <class name="com.kodnest.Answer" table="ans501">
          <id name="id">
          <generator class="increment"></generator>
          </id>
          <property name="answername"></property>
          <property name="postedBy"></property>
          </class>
          </hibernate-mapping>
Creating configuration file
<?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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
    <session-factory>
        <property name="hbm2ddl.auto">update</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 resource="question.hbm.xml"/>
    </session-factory>
</hibernate-configuration>  
Creating class to store data
package com.kodnest;
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 StoringData {
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("Hello World");
    ans1.setPostedBy("Admin");
    Answer ans2=new Answer();
    ans2.setAnswername("World Hello");
    ans2.setPostedBy("Admin");
    Answer ans3=new Answer();
    ans3.setAnswername("Hello Java");
    ans3.setPostedBy("Admin");
    Answer ans4=new Answer();
    ans4.setAnswername("Java Hello");
    ans4.setPostedBy("Admin");
    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("How are you?");
    question1.setAnswers(list1);
    Question question2=new Question();
    question2.setQname("Are you awake?");
    question2.setAnswers(list2);
    session.persist(question1);
    session.persist(question2);
    t.commit();
    session.close();
    System.out.println("success");
}
}

13. Example for One to Many mapping using annotation.

Creating persistence class
package com.kodnest;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name="onetoannot")
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;
}
}  
package com.kodnest;
    import javax.persistence.*;
    @Entity
    @Table(name="oneannot")
    public class Answer {
    @Id
    @GeneratedValue(strategy=GenerationType.TABLE)
    private int id;
    private String answername;
    private String postedBy;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAnswername() {
        return answername;
    }
    public void setAnswername(String answername) {
        this.answername = answername;
    }
    public String getPostedBy() {
        return postedBy;
    }
    public void setPostedBy(String postedBy) {
        this.postedBy = postedBy;
    }
    }    
Creating configuration File
<?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">update</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.kodnest.Question"/>
    </session-factory>
</hibernate-configuration>    
Creating a class to store data
package com.kodnest;
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 StoringData {
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("Hello World");
    ans1.setPostedBy("Admin");
    Answer ans2=new Answer();
    ans2.setAnswername("World Hello");
    ans2.setPostedBy("Admin");
    Answer ans3=new Answer();
    ans3.setAnswername("Hello Java");
    ans3.setPostedBy("Admin");
    Answer ans4=new Answer();
    ans4.setAnswername("Java Hello");
    ans4.setPostedBy("Admin");
    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("How are you?");
    question1.setAnswers(list1);
    Question question2=new Question();
    question2.setQname("Are you awake?");
    question2.setAnswers(list2);
    session.persist(question1);
    session.persist(question2);
    t.commit();
    session.close();
    System.out.println("success");
}
}   

14. Example for Many to Many mapping

Creating persistent class
package com.kodnest;
import java.util.List;
public class Question {
private int id;
private String qname;
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;
}
}  
package com.kodnest;
import java.util.*;
public class Answer {
private int id;
private String answername;
private String postedBy;
private List<Question> questions;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getAnswername() {
    return answername;
}
public void setAnswername(String answername) {
    this.answername = answername;
}
public String getPostedBy() {
    return postedBy;
}
public void setPostedBy(String postedBy) {
    this.postedBy = postedBy;
}
public List<Question> getQuestions() {
    return questions;
}
public void setQuestions(List<Question> questions) {
    this.questions = questions;
}
}  
Creating mapping file for persistent class
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
  <class name="com.kodnest.Question" table="ques1911">
        <id name="id" type="int">
            <column name="q_id" />
            <generator class="increment" />
        </id>
        <property name="qname" />
        <list name="answers" table="ques_ans1911" fetch="select" cascade="all">
            <key column="q_id" />
               <index column="type"></index>
            <many-to-many class="com.kodnest.Answer" column="ans_id" />
        </list>
    </class>
</hibernate-mapping>         
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.kodnest.Answer" table="ans1911">
        <id name="id" type="int">
            <column name="ans_id" />
            <generator class="increment" />
        </id>
        <property name="answername"  />
        <property name="postedBy" />
    </class>
</hibernate-mapping>  
Creating configuration file
<?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 resource="question.hbm.xml"/>
    <mapping resource="answer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>    
Creating a class to store data
package com.kodnest;
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 StoringData {
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("Hello World");
    ans1.setPostedBy("Admin");
    Answer ans2=new Answer();
    ans2.setAnswername("World Hello");
    ans2.setPostedBy("Admin");
    Question q1=new Question();
    q1.setQname("How are you?");
    ArrayList<Answer> l1=new ArrayList<Answer>();
    l1.add(ans1);
    l1.add(ans2);
    q1.setAnswers(l1);
    Answer ans3=new Answer();
    ans3.setAnswername("Hello Java");
    ans3.setPostedBy("Admin");
    Answer ans4=new Answer();
    ans4.setAnswername("Java Hello");
    ans4.setPostedBy("Admin");
    Question q2=new Question();
    q2.setQname("Are you awake?");
    ArrayList<Answer> l2=new ArrayList<Answer>();
    l2.add(ans3);
    l2.add(ans4);
    q2.setAnswers(l2);
    session.persist(q1);
    session.persist(q2);
    t.commit();
    session.close();
    System.out.println("success");
}
}    

15. Example for Many to Many Mapping using annotation

Creating persistence class
package com.kodnest;
import java.util.List;
import javax.persistence.*;
@Entity
@Table(name="ques123")
public class Question {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String qname;
@ManyToMany(targetEntity = Answer.class, cascade = { CascadeType.ALL })
@JoinTable(name = "q_ans1123",
            joinColumns = { @JoinColumn(name = "q_id") },
            inverseJoinColumns = { @JoinColumn(name = "ans_id") })
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;
}
}  
package com.kodnest;
import javax.persistence.*;
@Entity
@Table(name="ans123")
public class Answer {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String answername;
private String postedBy;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getAnswername() {
    return answername;
}
public void setAnswername(String answername) {
    this.answername = answername;
}
public String getPostedBy() {
    return postedBy;
}
public void setPostedBy(String postedBy) {
    this.postedBy = postedBy;
}
}    
Creating configuration file
<?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.kodnest.Question"/>
    <mapping class="com.kodnest.Answer"/>
    </session-factory>
</hibernate-configuration>  
Creating class to store
package com.kodnest;
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 StoringData {
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 an1=new Answer();
    an1.setAnswername("Hello World");
    an1.setPostedBy("Admin");
    Answer an2=new Answer();
    an2.setAnswername("World Hello");
    an2.setPostedBy("Admin");
    Question q1=new Question();
    q1.setQname("Are you awake?");
    ArrayList<Answer> l1=new ArrayList<Answer>();
    l1.add(an1);
    l1.add(an2);
    q1.setAnswers(l1);
      Answer ans3=new Answer();
        ans3.setAnswername("Hello Java");
        ans3.setPostedBy("Admin");
        Answer ans4=new Answer();
        ans4.setAnswername("Java Hello");
        ans4.setPostedBy("Admin");
    Question q2=new Question();
    q2.setQname("Are you awake?");
    ArrayList<Answer> l2=new ArrayList<Answer>();
    l2.add(ans3);
    l2.add(ans4);
    q2.setAnswers(l2);
    session.persist(q1);
    session.persist(q2);
    t.commit();
    session.close();
    System.out.println("success");
}
}   

16. Example of One to One Hibernate using XML

Creating persistent class for one to one mapping

Student.java

package com.kodnest;
public class Student {
private int employeeId;
private String name,email;
private Address address;
//setters and getters
}  

School.java

package com.kodnest;
public class School {
private int addressId;
private String addressLine1,city,state,country;
private int pincode;
private Employee employee;
//setters and getters
}  
Creating mapping files for persistent class

Student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
           <hibernate-mapping>
          <class name="com.kodnest.Employee" table="emp212">
          <id name="StudentId">
          <generator class="increment"></generator>
          </id>
          <property name="name"></property>
          <property name="email"></property>
          <one-to-one name="address" cascade="all"></one-to-one>
          </class>
          </hibernate-mapping>  

School.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
           <hibernate-mapping>
          <class name="com.kodnest.Address" table="address12">
          <id name="addressId">
          <generator class="foreign">
          <param name="property">student</param>
          </generator>
          </id>
          <property name="addressLine1"></property>
          <property name="city"></property>
          <property name="state"></property>
          <property name="country"></property>
          <property name="pincode"></property>
          <one-to-one name="student"></one-to-one>
          </class>
          </hibernate-mapping>
Creating configuration file
<?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">update</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 resource="student.hbm.xml"/>
    <mapping resource="school.hbm.xml"/>
    </session-factory>
</hibernate-configuration>  
User class to store data
package com.kodnest;
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 StoringData {
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();
    Student s1=new Student();
    s1.setName("Raj Mehta");
    s1.setEmail("raj@gmail.com");
    School sl=new School();
    sl.setAddressLine1("F-31 Lake View");
    sl.setCity("Bengaluru");
    sl.setState("Karanatka");
    sl.setCountry("India");
    sl.setPincode(560055);
    s1.setAddress(address1);
    sl.setEmployee(s1);
    session.persist(s1);
    t.commit();
    session.close();
    System.out.println("success");
}
}    

17. Example of One to One Hibernate using Annotation

Creating persistence class
package com.kodnest;
import javax.persistence.*;
@Entity
@Table(name="emp20")
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @PrimaryKeyJoinColumn
private int employeeId;
private String name,email;
@OneToOne(targetEntity=Address.class,cascade=CascadeType.ALL)
private Address address;
public int getEmployeeId() {
    return employeeId;
}
public void setEmployeeId(int employeeId) {
    this.employeeId = employeeId;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public Address getAddress() {
    return address;
}
public void setAddress(Address address) {
    this.address = address;
}
}    
package com.kodnest;
import javax.persistence.*;
@Entity
@Table(name="address220")
public class Address {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
private int addressId;
private String addressLine1,city,state,country;
private int pincode;
@OneToOne(targetEntity=Employee.class)
private Employee employee;
public int getAddressId() {
    return addressId;
}
public void setAddressId(int addressId) {
    this.addressId = addressId;
}
public String getAddressLine1() {
    return addressLine1;
}
public void setAddressLine1(String addressLine1) {
    this.addressLine1 = addressLine1;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
public String getState() {
    return state;
}
public void setState(String state) {
    this.state = state;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}
public int getPincode() {
    return pincode;
}
public void setPincode(int pincode) {
    this.pincode = pincode;
}
public Employee getEmployee() {
    return employee;
}
public void setEmployee(Employee employee) {
    this.employee = employee;
}
}  
Creating Configuration file
<?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">update</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.kodnest.Address"/>
    <mapping class="com.kodnest.Employee"/>
    </session-factory>
</hibernate-configuration>    
User class to store data
package com.kodnest;
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 Store {
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();
    Employee e1=new Employee();
    e1.setName("Raj Mehta");
    e1.setEmail("raj@gmail.com");
    Address address1=new Address();
    address1.setAddressLine1("F-31 Lake View");
    address1.setCity("Bengaluru");
    address1.setState("Karnataka");
    address1.setCountry("India");
    address1.setPincode(560055);
    e1.setAddress(address1);
    address1.setEmployee(e1);
    session.persist(e1);
    t.commit();
    session.close();
    System.out.println("success");
}
}    

18. Example for Transaction Management in Hibernate

Session session = null;
Transaction tx = null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
//some action
tx.commit();
}catch (Exception ex) {
ex.printStackTrace();
tx.rollback();
}
finally {session.close();}  

19. Hibernate Named Query by annotation

Employee.java

package com.kodnest;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@NamedQueries(
    {
        @NamedQuery(
        name = "findEmployeeByName",
        query = "from Employee e where e.name = :name"
        )
    }
)
@Entity
@Table(name="em")
public class Employee {
    public String toString(){return id+" "+name+" "+salary+" "+job;}
    int id;
    String name;
    int salary;
    String job;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    //getters and setters
}

hibernate.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">update</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.kodnest.Employee"/>
    </session-factory>
</hibernate-configuration>  

FetchingData.java

package com.kodnest;
import java.util.*;
import javax.persistence.*;
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 FetchingData {
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();
    //Hibernate Named Query
           TypedQuery query = session.getNamedQuery("findEmployeeByName");
            query.setParameter("name","raj");
            List<Employee> employees=query.getResultList();
    Iterator<Employee> itr=employees.iterator();
     while(itr.hasNext()){
    Employee e=itr.next();
    System.out.println(e);
     }
    session.close();
  }
}    

20. Hibernate Named Query by mapping file.

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.kodnest.Employee" table="em">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="job"></property>
<property name="salary"></property>
</class>
<query name="findEmployeeByName">
<![CDATA[from Employee e where e.name = :name]]>
</query>
</hibernate-mapping>  

Employee.java

package com.kodnest;
public class Employee {
    int id;
    String name;
    int salary;
    String job;
    //getters and setters
}  

Related Articles

HIBERNATE

1. Hibernate Example using XML in Eclipse. First we need to add jar files. Creating Persistent Class Student.java public class Student { private int id;…

Core Java

1. What are primitive types in Java ? byte, short, int, long, float, double, char, boolean… 2. What are tokens? Name the 5 types of tokens available in Java with an example…

Spring

1. Hello World Program HelloWorld.java MainApp.java 2. How to create Spring applcation. Create Java Class Create XML File Create test class Load jar files required…

Hackerearth-Java

     1. Challenge : Welcome to Java! Welcome to the world of Java! In this challenge, we practice printing to stdout. The code stubs…

Responses

Your email address will not be published. Required fields are marked *

KodNest Training New Batch is starting on 21st September 2020. Attend one week free demo classes.Register Now

New Report

Close