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

	training.User ( id INT NOT NULL AUTO_INCREMENT , 
	username VARCHAR(250) NOT NULL , 
	password VARCHAR(250) NOT NULL , 
	email_address VARCHAR(250) NULL ,
	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


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) { = name;

	public SocialClub(Integer clubId, String name, Set users) {
		this.clubId = clubId; = 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) { = name;

	public Set getUsers() {
		return users;

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


5. Create User Class


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) { = 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;

	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" "" >
	<class name="" table="socialclub">
		<id name="clubId" column="club_id">
			<generator class="increment" />

		<property name="name" type="string" column="name"></property>
		<set name="users" table="user_socialclub" inverse="true" lazy="true"
				<column name="club_id" not-null="true" />
			<many-to-many entity-name="">
				<column name="user_id" not-null="true" />


7. Create user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "" >
	<class name="" table="User2">
		<id name="id" column="id">
			<generator class="increment" />

		<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">
				<column name="id" not-null="true" />
			<one-to-many class="" />
		<set name="clubs" table="user_socialclub" inverse="false"
			lazy="true" fetch="select" cascade="all">
				<column name="user_id" not-null="true" />
			<many-to-many entity-name="">
				<column name="club_id" not-null="true" />

8. Update hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		<!--<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" />


9. Create a method in UserDAO Class


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;


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;
		Transaction tx = session.beginTransaction();
		User user = new User();

		user.setUsername("a_user2" + new Date().getTime());

		Set clubs = new HashSet(); 
		clubs.add(new SocialClub("CHESS CLUB"));
		clubs.add(new SocialClub("BOOK CLUB"));
		status = true;

		return status;

	public static void main(String[] args) {




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

SELECT * FROM training.user_socialclub;
user_id, club_id


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 or email
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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s