Many To Many Mapping with JPA Annotations

I have used the example at this link http://cuppajavamattiz.com/2014/05/17/many-to-many-hibernate-mapping-using-mapping-table/ to work with JPA annotations. I have used most of the jars in apache commons in the spring-framework-with dependencies download, in addition to the EJB3 libraries that you can download from the Eclipse marketplace for Juno/ Indigo Eclipse and the spring framework core library jars – see screenshot for complete list of jars. I had to do an additional download for java-assist.jar. Like most other examples on this site this example runs as a standalone doing away with tedious UI development for feature demonstration.

First run the following sql – same as in last example, except for one minor change – the pry key with auto-increment:

drop database pubs;
create database pubs;
use pubs;
drop table TB_AUTHORS;
CREATE TABLE TB_AUTHORS (AUTHOR_ID int(11) NOT NULL AUTO_INCREMENT ,AUTHOR_NAME varchar(30) default NULL,PRIMARY KEY (AUTHOR_ID)) ;
drop table TB_BOOKS;
CREATE TABLE TB_BOOKS (ISBN_CODE varchar(10) NOT NULL, BOOK_TITLE varchar(30) default NULL,PRIMARY KEY (ISBN_CODE)) ;
drop table TB_AUTHORS_BOOKS;
CREATE TABLE TB_AUTHORS_BOOKS (AUTHOR_ID_IN_MAP int(11) NOT NULL, ISBN_CODE varchar(10) not NULL);

mattiz .xml – the spring configuration file looks like this:




    
        
        
        
        
    
    
        
        
    
    
	    
	    
	       
	           com.mattiz.persistence.beans.Author
	           com.mattiz.persistence.beans.Book     
	       
	    
	   
	        
	            org.hibernate.dialect.MySQLDialect
	            false
	        
	    
	
    
        
            
        
    
    
        
            
        
    
    
        
            
        
    
    
        
    
    
        
    

The entities look like this:

package com.mattiz.persistence.beans;

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

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

@Entity
@Table(name = "TB_AUTHORS")
public class Author implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "AUTHOR_ID")
	private int authorId;

	@Column(name = "AUTHOR_NAME")
	private String name;
	
	@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
	@JoinTable(name = "TB_AUTHORS_BOOKS", joinColumns = { @JoinColumn(name = "AUTHOR_ID_IN_MAP", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "ISBN_CODE", nullable = false, updatable = false) })
	private Set books = new HashSet();

	public int getAuthorId() {
		return this.authorId;
	}

	public void setAuthorId(int authorId) {
		this.authorId = authorId;
	}

	public String getName() {
		return this.name;
	}

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

	public Set getBooks() {
		return books;
	}

	public void setBooks(Set books) {
		this.books = books;
	}
	
}
package com.mattiz.persistence.beans;

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

@Entity
@Table(name = "TB_BOOKS")
public class Book implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	public Book(String isbn, String title) {
		this.isbn = isbn;
		this.title = title;
	}

	@Id
	@Column(name = "ISBN_CODE")
	private String isbn;

	@Column(name = "BOOK_TITLE")
	private String title;

	public Book() {
	}

	public Book(String isbn) {
		this.isbn = isbn;
	}

	public String getIsbn() {
		return this.isbn;
	}

	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

	public String getTitle() {
		return this.title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
}

The Dao class is almost similar to the last example:

package com.mattiz.persistence.data;

import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.mattiz.persistence.beans.Author;
import com.mattiz.persistence.beans.Book;

public class MattizDao implements IMattizDao {

	private HibernateTemplate hibernateTemplate;

	public Set getBooksForAuthor(int authorId) throws DataAccessException {
		Author authorBean = null;
		
		HibernateTemplate template = getHibernateTemplate();
		authorBean = (Author)template.get(Author.class,
				authorId);		
		System.out.println(authorBean.getName()+"n");
		
		Set books = authorBean.getBooks();
		for(Book b: books){
			System.out.println(b.getTitle());
		}	
		template.flush();
		template.clear();
		
		return books;
	}
	

	public void insertAuthor(String authorName, Set books)
			throws DataAccessException {
		Author authorBean = new Author();
		authorBean.setBooks(books);		
		authorBean.setName(authorName);
		HibernateTemplate template = getHibernateTemplate();
		template.saveOrUpdate(authorBean);
		System.out.println("Inserted/Updated AuthorBean "
				+ authorBean.getName());
		template.flush();
		template.clear();
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
}

The Dao interface:

package com.mattiz.persistence.data;

import java.util.Set;

import org.springframework.dao.DataAccessException;

import com.mattiz.persistence.beans.Book;

public interface IMattizDao {

	public Set getBooksForAuthor(int authorId) throws DataAccessException;

	public void insertAuthor(String authorName, Set books)
			throws DataAccessException;

}

The Delegate class:

package com.mattiz.service.spring;

import java.util.Set;

import com.mattiz.persistence.beans.Book;
import com.mattiz.persistence.data.IMattizDao;

public class MattizDelegate implements IMattizDelegate {

	private IMattizDao mattizDao;

	public void insertAuthor(String authorName, Set books) {
		getMattizDao().insertAuthor(authorName, books);
	}

	public Set getBooksForAuthor(int authorId) {
		Set books = getMattizDao().getBooksForAuthor(authorId);
		return books;
	}

	public IMattizDao getMattizDao() {
		return mattizDao;
	}

	public void setMattizDao(IMattizDao mattizDao) {
		this.mattizDao = mattizDao;
	}

}

The Delegate interface:

package com.mattiz.service.spring;

import java.util.Set;

import com.mattiz.persistence.beans.Book;
import com.mattiz.persistence.data.IMattizDao;

public interface IMattizDelegate {

	public void insertAuthor(String authorName, Set books);

	public Set getBooksForAuthor(int authorId);

	public IMattizDao getMattizDao();

	public void setMattizDao(IMattizDao mattizDao);

}

Finally the main class:

package com.mattiz.web.managedbeans;

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mattiz.persistence.beans.Book;
import com.mattiz.service.spring.IMattizDelegate;

public class MattizMain {

	private ApplicationContext applicationContext;

	private IMattizDelegate mattizDelegate;

	public IMattizDelegate getMattizDelegate() {
		mattizDelegate = (IMattizDelegate) applicationContext
				.getBean("mattiz.service.delegate");
		return mattizDelegate;
	}

	public void setMattizDelegate(IMattizDelegate mattizDelegate) {
		this.mattizDelegate = mattizDelegate;
	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	public static void main(String[] args) {
		MattizMain mattizMain = new MattizMain();
		mattizMain.applicationContext = new ClassPathXmlApplicationContext(
				"resources/mattiz.xml");
		Book a = new Book("1e","The Cool Drink");
		Book b = new Book("1a","Lost Island");
		Book c = new Book("1b","Treasure Hunt");
		Book d = new Book("1c","Down With Fever");
		Book e = new Book("1d","Imagination runs Wild");
		Book f = new Book("1r","The Wild West");
		Book g = new Book("1h","Gregorios");
		Book h = new Book("14","Mar Thoma");
		Book i = new Book("15","Christ and the Disciples");
		Book j = new Book("1t","Long live His Cotton Socks");
		Book k = new Book("19","Praise Be to Harman!");
		Set aa = new HashSet();
		aa.add(a);
		aa.add(b);
		aa.add(c);		
		aa.add(d);
		aa.add(e);
		aa.add(f);
		aa.add(g);
		Set ab = new HashSet();
		ab.add(a);		
		ab.add(b);
		ab.add(h);
		Set ac = new HashSet();
		ac.add(i);
		ac.add(j);		
		ac.add(k);
		Set ad = new HashSet();
		ad.add(a);		
		ad.add(k);	
		Set af = new HashSet();
		af.add(a);
		Set ag = new HashSet();
		ag.add(a);	
		Set ah = new HashSet();
		ah.add(e);	
		Set aj = new HashSet();
		aj.add(f);	
		mattizMain.getMattizDelegate().insertAuthor("Mac",aa);
		mattizMain.getMattizDelegate().insertAuthor("Kenzie", ab);
		mattizMain.getMattizDelegate().insertAuthor("John",ac);		
		mattizMain.getMattizDelegate().insertAuthor("Warbler",ad);
		mattizMain.getMattizDelegate().insertAuthor("Huan",af);
		mattizMain.getMattizDelegate().insertAuthor("Mike",ag);
		mattizMain.getMattizDelegate().insertAuthor("Don",ag);		
		mattizMain.getMattizDelegate().insertAuthor("John",ah);
		mattizMain.getMattizDelegate().insertAuthor("Mark",aj);
		mattizMain.getMattizDelegate().insertAuthor("Jim",ah);
		mattizMain.getMattizDelegate().insertAuthor("Joe",ah);
		mattizMain.getMattizDelegate().insertAuthor("Harry",ad);		
		mattizMain.getMattizDelegate().insertAuthor("Noman",ag);
		mattizMain.getMattizDelegate().insertAuthor("Julian",aj);
		mattizMain.getMattizDelegate().insertAuthor("Tick",af);
		mattizMain.getMattizDelegate().insertAuthor("Toe",ac);
		System.out.println("----------------------");
		mattizMain.getMattizDelegate().getBooksForAuthor(1);
		System.out.println("----------------------");
		mattizMain.getMattizDelegate().getBooksForAuthor(5);
	}

}

The entire source download here –

ManyManyWithAnnotations

TB_BOOKS

TB_AUTHORS

TB_AUTHORS_BOOKS

folder_structure

libraries_1

libraries_2

Output:

output

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Comments are closed.

%d bloggers like this: