Many to many relationship example using Hibernate – Step by Step Instructions

Many to many relationship using Hibernate can be super useful for any practical purposes. Here are step by step instructions on how to do the same:
In this example There is a many to many relationship between User and Social Club. A user can belong to many social clubs and a Social Club can have many users

Many to many relationship example using Hibernate

1. Create User Table

	CREATE DATABASE IF NOT EXISTS training; 
	CREATE TABLE IF NOT EXISTS
	training.User ( id INT NOT NULL AUTO_INCREMENT , 
	username VARCHAR(250) NOT NULL , 
	password VARCHAR(250) NOT NULL , 
	email_address VARCHAR(250) NULL ,
	PRIMARY KEY (id) , UNIQUE INDEX
	username_UNIQUE (username ASC) );

2. Create SocialClub Table

CREATE TABLE `training`.`socialclub` (
  `club_id` INT NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`club_id`));

3. Create User_SocialClub Table

CREATE TABLE `training`.`user_socialclub` (
  `user_id` INT NOT NULL,
  `club_id` INT NOT NULL,
  PRIMARY KEY (`user_id`,`club_id`),
  CONSTRAINT `fk_user_id`
    FOREIGN KEY (`user_id`)
    REFERENCES `training`.`User2` (`id`),
    
  CONSTRAINT `fk_club_id`
    FOREIGN KEY (`club_id`)
    REFERENCES `training`.`socialclub` (`club_id`)
)

4. Create SocialClub Class

package com.st.model;

import java.util.HashSet;
import java.util.Set;

//CREATE TABLE `training`.`socialclub` (
//		  `club_id` INT NOT NULL,
//		  `name` VARCHAR(45) NOT NULL,
//		  PRIMARY KEY (`club_id`));

public class SocialClub {
	private Integer clubId;
	private String name;
	private Set users = new HashSet();

	public SocialClub(String name) {
		
		
		this.name = name;
		
	}

	public SocialClub(Integer clubId, String name, Set users) {
		super();
		this.clubId = clubId;
		this.name = name;
		this.users = users;
	}

	public Integer getClubId() {
		return clubId;
	}

	public void setClubId(Integer clubId) {
		this.clubId = clubId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set getUsers() {
		return users;
	}

	public void setUsers(Set users) {
		this.users = users;
	}

}


5. Create User Class

package com.st.model;

import java.util.HashSet;
import java.util.Set;

/**
@author asinha
 *
 */
public class User {
	private int id;

	private String emailAddress;
	private String username;
	private String password;
	
	private Set userPurchases = new HashSet();
	
	
	private Set clubs = new HashSet();

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Set getUserPurchases() {
		return userPurchases;
	}

	public void setUserPurchases(Set userPurchases) {
		this.userPurchases = userPurchases;
	}

	public Set getClubs() {
		return clubs;
	}

	public void setClubs(Set clubs) {
		this.clubs = clubs;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", emailAddress=" + emailAddress + ", username=" + username + ", password=" + password
				+ "]";
	}

}

6. Create socialclub.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="com.st.model.SocialClub" table="socialclub">
		<id name="clubId" column="club_id">
			<generator class="increment" />
		</id>


		<property name="name" type="string" column="name"></property>
		
		<set name="users" table="user_socialclub" inverse="true" lazy="true"
			fetch="select">
			<key>
				<column name="club_id" not-null="true" />
			</key>
			<many-to-many entity-name="com.st.model.User">
				<column name="user_id" not-null="true" />
			</many-to-many>
		</set>

	</class>
</hibernate-mapping>

7. Create user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="com.st.model.User" table="User2">
		<id name="id" column="id">
			<generator class="increment" />
		</id>

		<property name="username" type="string" column="username"></property>
		<property name="password" type="string" column="password"></property>
		<property name="emailAddress" type="string" column="email_address"></property>
		
		<set name="userPurchases" table="user_purchase" inverse="true"
			lazy="true" fetch="select">
			<key>
				<column name="id" not-null="true" />
			</key>
			<one-to-many class="com.st.model.UserPurchase" />
		</set>
		
		<set name="clubs" table="user_socialclub" inverse="false"
			lazy="true" fetch="select" cascade="all">
			<key>
				<column name="user_id" not-null="true" />
			</key>
			<many-to-many entity-name="com.st.model.SocialClub">
				<column name="club_id" not-null="true" />
			</many-to-many>
		</set>
	</class>
</hibernate-mapping>

8. Update 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>
		<!--<property name="connection.url">jdbc:mysql://localhost:3306/sansa_ads</property> -->
		<property name="connection.url">jdbc:mysql://localhost:3306/training</property>
		<property name="connection.username">root</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
		<!-- thread is the short name for org.hibernate.context.ThreadLocalSessionContext 
			and let Hibernate bind the session automatically to the thread -->
		<property name="current_session_context_class">thread</property>

		<!-- this will show us all sql statements -->
		<property name="hibernate.show_sql">true</property>

		<!-- mapping files -->


		<mapping resource="user.hbm.xml" />
		<mapping resource="user-purchase.hbm.xml" />
		<mapping resource="socialclub.hbm.xml" />


	</session-factory>
</hibernate-configuration>

9. Create a method in UserDAO Class

package com.st.dao;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.st.model.SocialClub;
import com.st.model.User;


public class UserDAO {

	static Session session;

	static void createSession() {
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		session = sessionFactory.openSession();
	}



	public static boolean testCreateManyToMany() {
		boolean status = false;
		createSession();
		
		Transaction tx = session.beginTransaction();
		User user = new User();

		user.setEmailAddress("a@apple.com2");
		user.setUsername("a_user2" + new Date().getTime());
		user.setPassword("a_pass2");
		//session.save(user);
		

		Set clubs = new HashSet(); 
		clubs.add(new SocialClub("CHESS CLUB"));
		clubs.add(new SocialClub("BOOK CLUB"));
		user.setClubs(clubs);
		session.save(user);
		
		
		tx.commit();
		status = true;

		return status;

	}
	
	public static void main(String[] args) {


		testCreateManyToMany();

	}

}

10. That’s it. You should see an output like below to show that data has been inserted in the tables

Hibernate: insert into User (username, password, email_address, id) values (?, ?, ?, ?)
Hibernate: insert into socialclub (name, club_id) values (?, ?)
Hibernate: insert into socialclub (name, club_id) values (?, ?)
Hibernate: insert into user_socialclub (user_id, club_id) values (?, ?)
Hibernate: insert into user_socialclub (user_id, club_id) values (?, ?)

Also, Verify this in the database using a tool such as MySQL Workbench:

SELECT * FROM training.socialclub;
club_id, name
'1','BOOK CLUB'
'2','CHESS CLUB'


SELECT * FROM training.user_socialclub;
user_id, club_id
'10','5'
'10','6'


Advertisements

About sansatechnology

Sansa Technology is an IT staffing, Consulting and Training company located in the heart of Silicon Valley. If you are a consultant looking for your new gig, send us your resume to us. If you are looking for training in the field of White Box Testing, Java, Java EE, Selenium, DevOps, Android and others, connect with us as well. Visit us at www.sansatechnology.com or email contact@sansatechnology.com
This entry was posted in Coding Challenges, Computers and Internet, IT Jobs and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s