Open In App

Hibernate – Mapping List

Last Updated : 10 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Hibernate, in order to go for an ordered collection of items, mostly List is the preferred one, Along with List, we have different collection mapping like Bag, Set, Map, SortedSet, SortedMap, etc., But still in many places mapping list is the most preferred way as it has the index element and hence searching wise, doing any CRUD operation wise it is easier. We can see this here via employees and their saving plans. One employee can do multiple investments. we can see that here.

Example Project

Project Structure:

Project Structure

 

This is a maven-driven project.

pom.xml

XML




         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>HibernateListMapping</groupId>
  <artifactId>HibernateListMapping</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <release>9</release>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.15.Final</version>
        </dependency>
        <!-- As we are connecting with MySQL, this is needed -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>


Let us see the main configuration files

employeeinvestment.hbm.xml

XML




<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
    
<hibernate-mapping>  
 <class name="com.gfg.hibernate.pojo.EmployeeInvestments" table="Employee">  
   <id name="employeeId">  
     <generator class="increment"></generator>  
   </id>  
   <property name="employeeName"></property>  
      
   <!--  In list, we need to maintain the order. Hence we 
         should maintain the index element. 
            This is the major difference between bag and list. -->
  <list name="investments" table="Investments">  
    
  <!--  Foreign key connecting employee and investments -->
  <key column="employeeId"></key>  
    
  <!-- This will maintain the order of investments, starts with 0 
       Because of this, it is easier to search and do crud operation -->
  <index column="type"></index>  
  <element column="investment" type="string"></element></list>               
 </class>  
              
</hibernate-mapping>


hibernate.cfg.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
<hibernate-configuration>
    
    <session-factory>
      
      <!--  As we are connecting mysql, those driver classes, 
            database name, username and password are specified
            Please change the information as per your requirement -->
        <property name="hbm2ddl.auto">update</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/geeksforgeeks?serverTimezone=UTC</property>        
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <property name="show_sql">true</property>
        <mapping resource="employeeinvestment.hbm.xml" /> 
    </session-factory>
    
</hibernate-configuration>


Let us see the POJO class now

EmployeeInvestments.java

Java




import java.util.List;
public class EmployeeInvestments {
    
    // data member for employee
    private int employeeId;
    private String employeeName;
    
    // investments
    private List<String> investments;
    public int getEmployeeId() { return employeeId; }
    public void setEmployeeId(int employeeId)
    {
        this.employeeId = employeeId;
    }
    public String getEmployeeName() { return employeeName; }
    public void setEmployeeName(String employeeName)
    {
        this.employeeName = employeeName;
    }
    public List<String> getInvestments()
    {
        return investments;
    }
    public void setInvestments(List<String> investments)
    {
        this.investments = investments;
    }
}


Java file for adding and listing the data

EmployeeInvestmentRepository.java

Java




import com.gfg.hibernate.pojo.EmployeeInvestments;
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 EmployeeInvestmentRepository {
    public static void main(String[] args)
    {
        StandardServiceRegistry standardServiceRegistry
            = new StandardServiceRegistryBuilder()
                  .configure("hibernate.cfg.xml")
                  .build();
        Metadata meta
            = new MetadataSources(standardServiceRegistry)
                  .getMetadataBuilder()
                  .build();
  
        SessionFactory sessionFactory
            = meta.buildSessionFactory();
        Session session = sessionFactory.openSession();
  
        Transaction transaction
            = session.beginTransaction();
  
        ArrayList<String> investmentList1
            = new ArrayList<String>();
        investmentList1.add("NSC");
        investmentList1.add("PPF");
        investmentList1.add("LIC");
  
        ArrayList<String> investmentList2
            = new ArrayList<String>();
        investmentList2.add("HousingLoan");
        investmentList2.add("CarLoan");
        investmentList2.add("NSC");
  
        EmployeeInvestments employeeInvestment1
            = new EmployeeInvestments();
        employeeInvestment1.setEmployeeName("EmployeeA");
        employeeInvestment1.setInvestments(investmentList1);
  
        EmployeeInvestments employeeInvestment2
            = new EmployeeInvestments();
        employeeInvestment2.setEmployeeName("EmployeeB");
        employeeInvestment2.setInvestments(investmentList2);
  
        session.persist(employeeInvestment1);
        session.persist(employeeInvestment2);
  
        transaction.commit();
        session.close();
        System.out.println(
            "success. We have seen List mapping here. Check the db data. We can see the index maintained there");
    }
}


On running the project, we can see the output below.

Output:

Output

 

Let us see the query that got executed

Output

 

Let us check MySQL DB data

Output

 

Conclusion

In the above, we have seen how to use the mapping list in the hibernate. Wherever ordering is necessary, we can go for List mapping.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads