It happens to me that I have a mini program made in java in eclipse and for the part of the bbdd use hibernate, I will put here the author bean and the book bean, and the AUTHOR class. It turns out that when I sign up for an author with his 3 books, if the author puts the id 1 in his table, in the table of books the IDs of the books are 2, 3 and 4. That is, they share the self-incremented . why? and I have another doubt, hibernate creates an auxiliary table as if I were doing a many2many relationship and I am not making a lot of relationships with muhcos.
Main
public static void main(String[] args) {
// TODO Auto-generated method stub
AutorBO abo = new AutorBO();
String nombre = "fulanito";
String titulo = "face";
String titulo2 = "equilibrio";
String titulo3 = "premunicion";
abo.alta(nombre, titulo, titulo2, titulo3);
}
Author
@Entity
public class Autor {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)//Para generar números
autoincrementados
int id;
String nombre;
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER) //eager =
carga
ansiosa
List<Libro> libros = new ArrayList<>();
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public List<Libro> getLibros() {
return libros;
}
public void setLibros(List<Libro> libros) {
this.libros = libros;
}
}
Book
@Entity
public class Libro {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)//Para generar números
autoincrementados
private int id;
private String titulo;
@ManyToOne
Autor autor;
public Libro(String titulo, Autor autor) {
super();
this.titulo = titulo;
this.autor = autor;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public Autor getAutor() {
return autor;
}
public void setAutor(Autor autor) {
this.autor = autor;
}
}
AutorBO
public class AutorBO {
public void alta(String nombre, String titulo, String titulo2, String
titulo3) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Autor a = new Autor();
a.setNombre(nombre);
Libro libro1 = new Libro(titulo, a);
Libro libro2 = new Libro(titulo2, a);
Libro libro3 = new Libro(titulo3, a);
a.getLibros().add(libro1);
a.getLibros().add(libro2);
a.getLibros().add(libro3);
session.save(a);
transaction.commit();
session.close();
}
}