Hibernate Many To Many Mapping Using Annotations

Hibernate » on Sep 3, 2011 { 8 Comments } By Sivateja

Let us see the example on many to many using annotations

Files required….

  • hibernate.cfg.xml

package str;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

public class Categories
	 private int categoryId;
	private String categoryName;
	private Set items;

	public int getCategoryId() {
		return categoryId;
	public void setCategoryId(int categoryId) {
		this.categoryId = categoryId;
	public Set getItems() {
		return items;
	public void setItems(Set items) {
		this.items = items;
	public String getCategoryName() {
		return categoryName;
	public void setCategoryName(String categoryname) {
		this.categoryName = categoryname;


package str;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

public class Item
	private int itemId;
	private String itemName;
	private Set  categories;

	public Set getCategories() {
		return categories;
	public void setCategories(Set  categories) {
		this.categories = categories;
	public int getItemId() {
		return itemId;
	public void setItemId(int itemId) {
		this.itemId = itemId;
	public String getItemName() {
		return itemName;
	public void setItemName(String itemName) {
		this.itemName = itemName;


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

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
<property name="connection.url"></property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="">update</property>


package str;

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

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

public class ForOurLogic { 

	public static void main(String args[])
		Configuration cfg = new Configuration();

		SessionFactory factory = new Configuration().configure().buildSessionFactory();
		Session ses = factory.openSession();	

		Categories c1 = new Categories();
		c1.setCategoryName("cat 1");

		Categories c2=new Categories();
		c2.setCategoryName("cat 2");

		Item i1=new Item();
		Item i2 = new Item();



		Set  s =new HashSet();


		Transaction tx = ses.beginTransaction();;;
		System.out.println("Man to Many using annotations been done...!!!!!");


Eclipse Output

In the database


You Might Also Like

  ::. About the Author .::

Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.


8 Responses to “Hibernate Many To Many Mapping Using Annotations”
  1. sudhakar says:

    Hi java4s,
    This is sudhakar. Greetings for Java4s site maintained holders. This site is very useful for java developers. everything mentions and code display process very brilliant. so I like it this site. my desire was this site maintained very long time and using update technology put in the site for java developers and one more thing best wishes for future implements tickets.

    Thanks & Regards

  2. sammaiah says:

    Difference between GenerationType.AUTO and GenerationType.SEQUENCE

  3. Manikandan says:

    Hi java4s,

    I got this error while running your code,

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Exception in thread “main” org.hibernate.MappingException: Unknown entity: com.bean.Categories
    at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(

  4. churanjeevi says:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Exception in thread "main" org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.mapping.Categories"/>
    at org.hibernate.cfg.Configuration.parseMappingElement(
    at org.hibernate.cfg.Configuration.parseSessionFactory(
    at org.hibernate.cfg.Configuration.doConfigure(
    at org.hibernate.cfg.Configuration.doConfigure(
    at org.hibernate.cfg.Configuration.configure(
    at com.mapping.ForOurLogic.main(
    I got this error while running this code.

  5. Sharad says:

    Exception in thread "main" org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class:[org.hibernate.cache.ReadWriteCache$Item]
    at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(
    at org.hibernate.cfg.Configuration.secondPassCompile(
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(
    at org.hibernate.cfg.Configuration.buildSessionFactory(
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(

    • Tomeshwar says:

      SessionFactory factory = new AnnotationConfiguration().configure("/many2many/hibernate.cfg.xml").buildSessionFactory();
      Session ses = factory.openSession();

  6. manoj says:

    its not working above code, getting exception,please correct it sir.
    thanking you sir

  7. anil says:

    Outstanding site superb!


By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.