A través de las anotaciones que proporciona JPA cuando usamos Hibernate, podemos gestionar las relaciones entre dos tablas como si de objetos se tratasen. Esto facilita el mapeo de atributos de base de datos con el modelo de objetos de la aplicación. Dependiendo de la lógica de negocio y cómo modelemos, se podrán crear relaciones unidireccionales o bidireccionales.
Relaciones
@OneToOne (bidireccional)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
EJEMPLO @OneToOne @Entity @Table(name = "pisos") public class Piso { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String direccion; @OneToOne(mappedBy = "piso", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private Persona persona; /* Getters and setters */ } -------------- @Entity @Table(name = "personas") public class Persona { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String nombre; @OneToOne(mappedBy = "piso", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private Persona persona; @JoinColumn(name = "id") @OneToOne(fetch = FetchType.LAZY) private Piso piso; /* Getters and setters */ } |
@OneToMany
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
EJEMPLO @OneToMany (bidireccional) @Entity @Table(name = "pisos") public class Piso { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String direccion; @OneToMany(mappedBy = "piso", cascade = CascadeType.ALL, orphanRemoval = true) private List<Persona> persona; /* Getters and setters */ } -------------- @Entity @Table(name = "personas") public class Persona { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String nombre; private Persona persona; @ManyToOne() @JoinColumn(name = "id") private Piso piso; /* Getters and setters */ } |
@ManyToMany (bidireccional)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
EJEMPLO @ManyToMany (bidireccional) @Entity @Table(name = "pisos") public class Piso { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String direccion; @ManyToMany(mappedBy = "pisos") private List<Persona> persona; /* Getters and setters */ } -------------- @Entity @Table(name = "persona") public class Persona { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String nombre; private Persona persona; @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }) @JoinTable( name = "tabla_pisos_personas", joinColumns = {@JoinColumn(name = "id")}, // id de pisos inverseJoinColumns = {@JoinColumn(name = "id")} // id de persona ) private List<Piso> pisos; /* Getters and setters */ } |