Unidirectional Many-To-Many Relationship with Join Tables in Hibernate

In unidirectional association, we will have navigation only in one direction, i.e, only one side of the association will have the reference to the other side. The one side of the association will implement one of the collection interfaces, if it has the reference to the other entity.

In many to many relationship, multiple target objects can have relationship with multiple source objects. Let’s consider CD and Artist. So only one Artist can write multiple CD or a CD can be written by multiple Artists. So we will create three tables CD, Artist and CDArtist in the database and we will see how many-to-many relationship works step by step.

Step 1. Create tables
Create table – CD

CREATE TABLE `cd` (
  `cdId` bigint(20) NOT NULL AUTO_INCREMENT,
  `cdTitle` varchar(50) NOT NULL,
  PRIMARY KEY (`cdId`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

 
Create table – Artist

CREATE TABLE `artist` (
  `artistId` bigint(20) NOT NULL AUTO_INCREMENT,
  `artistName` varchar(50) NOT NULL,
  PRIMARY KEY (`artistId`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

 
Create table – CDArtist

CREATE TABLE `cdartist` (
  `cdId` bigint(20) NOT NULL,
  `artistId` bigint(20) NOT NULL,
  PRIMARY KEY (`cdId`,`artistId`),
  KEY `FK82065EE860AB4868` (`cdId`),
  KEY `FK82065EE835296F34` (`artistId`),
  CONSTRAINT `FK82065EE835296F34` FOREIGN KEY (`artistId`) REFERENCES `artist` (`artistId`),
  CONSTRAINT `FK82065EE860AB4868` FOREIGN KEY (`cdId`) REFERENCES `cd` (`cdId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

Step 2. Create a java project in any Java based IDE and configure for hibernate jars.

Step 3. Create hibernate reverse engineering and configuration file.
hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
    <schema-selection match-catalog="hibernate_assoc"/>
    <table-filter match-name="cdartist"/>
    <table-filter match-name="cd"/>
    <table-filter match-name="artist"/>
</hibernate-reverse-engineering>

 
hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!-- hibernate database specific dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- hibernate database specific driver -->
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <!-- hibernate database connection URL -->
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_assoc?zeroDateTimeBehavior=convertToNull</property>
    <!-- hibernate database username -->
    <property name="hibernate.connection.username">root</property>
    <!-- show sql in console -->
    <property name="hibernate.show_sql">true</property>
    <!-- format sql in cosole for better readability -->
    <property name="hibernate.format_sql">true</property>
    <!-- which context to use for sql processing -->
    <property name="hibernate.current_session_context_class">thread</property>
    <!-- translator for HSQL -->
    <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
    <!-- hibernate mapping resources or files -->
    <mapping resource="in/webtuts/hibernate/domain/Cd.hbm.xml"/>
    <mapping resource="in/webtuts/hibernate/domain/Artist.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

 
Step 4. Create hibernate utility class which creates singleton SessionFactory from which Session object will be created.

package in.webtuts.hibernate.utils;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author admin
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

 
Step 5. Create mapping xml file and POJO for artist table
Artist.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="in.webtuts.hibernate.domain.Artist" table="artist" catalog="hibernate_assoc">
        <id name="artistId" type="java.lang.Long">
            <column name="artistId" />
            <generator class="identity" />
        </id>
        <property name="artistName" type="string">
            <column name="artistName" length="50" not-null="true" />
        </property>
        <set name="cds" table="cdartist" inverse="true" lazy="true" fetch="select" cascade="all">
            <key>
                <column name="artistId" not-null="true" />
            </key>
            <many-to-many entity-name="in.webtuts.hibernate.domain.Cd">
                <column name="cdId" not-null="true" />
            </many-to-many>
        </set>
    </class>
</hibernate-mapping>
package in.webtuts.hibernate.domain;
import java.util.HashSet;
import java.util.Set;
public class Artist implements java.io.Serializable {
    private Long artistId;
    private String artistName;
    private Set cds = new HashSet(0);
    public Artist() {
    }
    public Artist(String artistName) {
        this.artistName = artistName;
    }
    public Artist(String artistName, Set cds) {
        this.artistName = artistName;
        this.cds = cds;
    }
    public Long getArtistId() {
        return this.artistId;
    }
    public void setArtistId(Long artistId) {
        this.artistId = artistId;
    }
    public String getArtistName() {
        return this.artistName;
    }
    public void setArtistName(String artistName) {
        this.artistName = artistName;
    }
    public Set getCds() {
        return this.cds;
    }
    public void setCds(Set cds) {
        this.cds = cds;
    }
}

 
Step 6. Create mapping xml file and POJO for cd table.
Cd.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="in.webtuts.hibernate.domain.Cd" table="cd" catalog="hibernate_assoc">
        <id name="cdId" type="java.lang.Long">
            <column name="cdId" />
            <generator class="identity" />
        </id>
        <property name="cdTitle" type="string">
            <column name="cdTitle" length="50" not-null="true" />
        </property>
        <set name="artists" table="cdartist" inverse="false" lazy="true" fetch="select" cascade="all">
            <key>
                <column name="cdId" not-null="true" />
            </key>
            <many-to-many entity-name="in.webtuts.hibernate.domain.Artist">
                <column name="artistId" not-null="true" />
            </many-to-many>
        </set>
    </class>
</hibernate-mapping>
package in.webtuts.hibernate.domain;
import java.util.HashSet;
import java.util.Set;
public class Cd implements java.io.Serializable {
    private Long cdId;
    private String cdTitle;
    private Set artists = new HashSet(0);
    public Cd() {
    }
    public Cd(String cdTitle) {
        this.cdTitle = cdTitle;
    }
    public Cd(String cdTitle, Set artists) {
        this.cdTitle = cdTitle;
        this.artists = artists;
    }
    public Long getCdId() {
        return this.cdId;
    }
    public void setCdId(Long cdId) {
        this.cdId = cdId;
    }
    public String getCdTitle() {
        return this.cdTitle;
    }
    public void setCdTitle(String cdTitle) {
        this.cdTitle = cdTitle;
    }
    public Set getArtists() {
        return this.artists;
    }
    public void setArtists(Set artists) {
        this.artists = artists;
    }
}

 

Step 7. Now we will create a main class for testing unidirectional many-to-many with join tables.

package in.webtuts.hibernate.test;
import in.webtuts.hibernate.domain.Artist;
import in.webtuts.hibernate.domain.Cd;
import in.webtuts.hibernate.utils.HibernateUtil;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
 *
 * @author https://roytuts.com
 */
public class ManyToManyJoinedUnidirectional {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Session session = null;
        Transaction transaction = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            Cd cd1 = new Cd();
            cd1.setCdTitle("CD One");
            Artist a1 = new Artist();
            a1.setArtistName("abc");
            Artist a2 = new Artist();
            a2.setArtistName("klm");
            Artist a3 = new Artist();
            a3.setArtistName("xyz");
            Set<Artist> artists = new HashSet<>();
            artists.add(a1);
            artists.add(a2);
            artists.add(a3);
            cd1.setArtists(artists);
            session.save(cd1);
            transaction.commit();
        } catch (HibernateException e) {
            e.printStackTrace();
            transaction.rollback();
        }
    }
}

 
Step 8. Run the main class and see the output as shown below. While we save value for cd, below values are stored into the database tables.
inserted data into artist table

insert  into `artist`(`artistId`,`artistName`) values (1,'abc'),(2,'klm'),(3,'xyz');

inserted data into cd table

insert  into `cd`(`cdId`,`cdTitle`) values (1,'CD One');

inserted data into cdartist table

insert  into `cdartist`(`cdId`,`artistId`) values (1,1),(1,2),(1,3);

Console Output

Hibernate:
    insert
    into
        hibernate_assoc.cd
        (cdTitle)
    values
        (?)
Hibernate:
    insert
    into
        hibernate_assoc.artist
        (artistName)
    values
        (?)
Hibernate:
    insert
    into
        hibernate_assoc.artist
        (artistName)
    values
        (?)
Hibernate:
    insert
    into
        hibernate_assoc.artist
        (artistName)
    values
        (?)
Hibernate:
    insert
    into
        cdartist
        (cdId, artistId)
    values
        (?, ?)
Hibernate:
    insert
    into
        cdartist
        (cdId, artistId)
    values
        (?, ?)
Hibernate:
    insert
    into
        cdartist
        (cdId, artistId)
    values
        (?, ?)

 
That’s all. Thanks for your reading.

Leave a Reply

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