Many to many with Hibernate

Many to many with Hibernate

In this article i want show how persist a many to many relationship, whith hibernate and jpa annotation.

Hibernate always, for this relationship, generate 3 table. One table for entity and one join table.

Cliente.java

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;



@Entity
public class Cliente {

	private int id;
	private String name;
	
	private List<Societa> societa;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@ManyToMany
	public List<Societa> getSocieta() {
		return societa;
	}
	public void setSocieta(List<Societa> societa) {
		this.societa = societa;
	}

	
}
Societa.java

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;




@Entity
public class Societa {

	private int id;
	private String name;
	
	private List<Cliente> cliente;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@ManyToMany
	public List<Cliente> getCliente() {
		return cliente;
	}
	public void setCliente(List<Cliente> cliente) {
		this.cliente = cliente;
	}

	
}

as you can see this is a bidirectional association.

Here i have used some annotation


    @Entity
    @Id is for primary key
    @GeneratedValue is for autoincrement for primary key
    @ManyToMany

when i persist with hibernate this two classes


import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class Test1 {

	public static void main(String[] args) {
		
        Configuration config=new Configuration();
        config.addAnnotatedClass(Cliente.class);
        config.addAnnotatedClass(Societa.class);
        config.configure();
 
        
        new SchemaExport(config).create(true, true);
        
        

	}

}

hibernate generate one table for the entity Cliente, one table for Societa and a join table Cliente_Societa with foreign keys.


Cliente(id,name)
Societa(id,name)
Societa_Cliente(Societa_id,cliente_id)

Comments

Popular posts from this blog

Spring cloud config

Quick Sort algorithm with Java and R

SAX xml parser and Java