Newsletter

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….

  • Categories.java
  • Item.java
  • hibernate.cfg.xml
  • ForOurLogic.java

Categories.java

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;

@Entity
@Table(name="categories")
public class Categories
{
	@Id
	@Column(name="catid")
	 private int categoryId;
	@Column(name="catname",length=10)
	private String categoryName;
	@ManyToMany(targetEntity=Item.class,cascade=CascadeType.ALL)
	@JoinTable(name="categories_items",joinColumns=@JoinColumn(name="cat_id_fk",referencedColumnName="catid"),inverseJoinColumns=@JoinColumn(name="item_id_fk",referencedColumnName="itemid"))
	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;
	}

}

Item.java

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;

@Entity
@Table(name="items")
public class Item
{
	@Id
	@Column(name="itemid")
	private int itemId;
	@Column(name="itemname",length=10)
	private String itemName;
	@ManyToMany(targetEntity=Categories.class,mappedBy="items")
	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;
	}
}

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.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</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="hbm2ddl.auto">update</property>

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

ForOurLogic.java

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();
		cfg.configure("hibernate.cfg.xml"); 

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

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

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

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

		i1.setItemId(101);
		i1.setItemName("item1");

		i2.setItemId(102);
		i2.setItemName("item2");

		Set  s =new HashSet();
		s.add(i1);
		s.add(i2);

		c1.setItems(s);
		c2.setItems(s);

		Transaction tx = ses.beginTransaction();
		ses.save(c1);
		ses.save(c2);
		tx.commit();
		System.out.println("Man to Many using annotations been done...!!!!!");
		ses.close();
	}

}

Eclipse Output

In the database

​​

You Might Also Like

  ::. About the Author .::

Java4s_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.

Comments

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
    Sudhakar

  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(SessionFactoryImpl.java:489)

  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(Configuration.java:1597)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1552)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1531)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1505)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
    at com.mapping.ForOurLogic.main(ForOurLogic.java:18)
    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: com.java.Categories.items[org.hibernate.cache.ReadWriteCache$Item]
    at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1068)
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:600)
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:541)
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1130)
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:324)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)

    • Tomeshwar says:

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

  6. manoj says:

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

  7. anil says:

    Outstanding site superb!

Name*
Mail*
Website



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.