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
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
from. Thank you for posting when you've got the opportunity, Guess I
will just book mark this site.
Also visit mmy webpage :: sort
lists online: https://www.gillmeister-software.com/
The clearneѕs on ʏour publish is simply nice and i
could think you're knowledgeable in this subject. Fine along with your permission let me to tɑke hold
of your feed to stay up to date with aρproaching post.
Thanks a million and please kеep up the rewarding work.
RSS