How to store a list in Hibernate

1

Here is the Container class with the PlazasBlock List that I want to store in hibernate

@Entity
@Table(name = "CONTENEDOR", uniqueConstraints = {
@UniqueConstraint(columnNames = "IdContenedor")})
public class Contenedor implements Serializable {
//Atributos de la clase Contenedor

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "IdContenedor", nullable = false)
private int idContenedor; // IdContenedor del espacio que lo diferencia de los demas.
@ManyToOne
@JoinColumn(name = "CedulaUsuario", nullable = false)
private Usuario usuario; // Quien adquiere la reserva
@Column(name = "Tipo", nullable = false, length = 100)
private String tipo; // Genero es el tipo de espacio que se crea(salas de cine, parqueaderos...)
@Column(name = "Nombre", length = 50)
private String nombre; // Nombre que le damos al espacio a crear
@Column(name = "Descripcion", length = 500)
private String descripcion; // Descripcion que tendra cada espacio creado.
@Column(name="NFilas")
private int nFilas; // numero de filas en el contenedor
@Column(name="NColumnas")
private int nColumnas; // numero de columnas en el contenedor 
@OneToMany(mappedBy = "contenedor", fetch = FetchType.EAGER)
private List<PlazasBlock> blockPlazas= new ArrayList();// Lista de objetos Lugar que tiene como nombre lugares.

/**
 * Constructor,se crea un objecto contenedor sin parametros
 *
 */



public Contenedor() {
}

public Contenedor(Usuario usuario, String tipo, String nombre, String descripcion, int nFilas, int nColumnas, List<PlazasBlock> blockPlazas) {
    this.usuario = usuario;
    this.tipo = tipo;
    this.nombre = nombre;
    this.descripcion = descripcion;
    this.nFilas= nFilas;
    this.nColumnas=nColumnas;
    this.getBlockPlazas().clear();
    this.getBlockPlazas().addAll(blockPlazas);
}

public int getIdContenedor() {
    return idContenedor;
}

public void setIdContenedor(int idContenedor) {
    this.idContenedor = idContenedor;
}

public Usuario getUsuario() {
    return usuario;
}

public void setUsuario(Usuario Usuario) {
    this.usuario = Usuario;
}

public String getTipo() {
    return tipo;
}

public void setTipo(String tipo) {
    this.tipo = tipo;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public String getDescripcion() {
    return descripcion;
}

public void setDescripcion(String descripcion) {
    this.descripcion = descripcion;
}

public int getnFilas() {
    return nFilas;
}

public void setnFilas(int nFilas) {
    this.nFilas = nFilas;
}

public int getnColumnas() {
    return nColumnas;
}

public void setnColumnas(int nColumnas) {
    this.nColumnas = nColumnas;
}

public List<PlazasBlock> getBlockPlazas() {
    return blockPlazas;
}

public void setBlockPlazas(List<PlazasBlock> blockPlazas) {
    this.getBlockPlazas().clear();
    this.getBlockPlazas().addAll(blockPlazas);

}
// Fin de los metodos GET Y SET de los atributos
}

Here's the PlazasBlock class

@Entity @Table (name="PLAZASBLOCK") @IdClass (value = PlazasBlockPK.class) public class PlazasBlock implements Serializable {     // Attributes of the Plaza class

@Id
@Column(name = "PosicionX")
public int x;
@Id
@Column(name = "PosicionY")
public int y;
@ManyToOne
@JoinColumn(name = "IdContenedor", nullable = false)
private Contenedor contenedor;

/**
 * Constructor,se crea un objeto Plaza sin parametros
 */
public PlazasBlock() {
    this.x = 0;
    this.y = 0;
}

public PlazasBlock(int x, int y) {
    this.x = x;
    this.y = y;
}

public boolean equals(PlazasBlock plaza) {

    return plaza.getX() == this.x && plaza.getY() == this.y;

}

// Metodos GET Y SET de los atributos
public Contenedor getContenedor() {
    return contenedor;
}

public void setContenedor(Contenedor contenedor) {
    this.contenedor = contenedor;
}

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

public int getY() {
    return y;
}

public void setY(int y) {
    this.y = y;
}
// Fin de los metodos GET y SET

}

The problem is that it keeps all the attributes of the User and Container classes, but what is in the List blockPlazas does not keep it for me?

private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {                                      

String cedulaUsuario=txtCc.getText();
String nombre=txtNombre.getText();
String apellido=txtApellido.getText();
String telefono=txtTel.getText();


String nombreC=txtTitulo.getText();
String tipo=txtTipo.getText();
String descripcion=txtAreaDescripcion.getText();
int nFilas=(Integer)SpinnerFila.getValue();
int nColumnas=(Integer)SpinnerColumna.getValue();
List<PlazasBlock> blockPlazas= this.plazasBlock;

Usuario usuario=new Usuario(cedulaUsuario,nombre,apellido,telefono);
Contenedor contenedor=new Contenedor(usuario, tipo, nombreC, descripcion, nFilas, nColumnas, blockPlazas);

Session session = NewHibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(usuario);    //<|--- Aqui guardamos el objeto en la base de datos.
session.save(contenedor); //<|--- Aqui guardamos el objeto en la base de datos.


session.flush();
session.getTransaction().commit();
NewHibernateUtil.shutdown();

JOptionPane.showMessageDialog(null,"Espacio creado exitosamente!!");
}      

I added the annotation: @OneToMany (mappedBy="container", fetch = FetchType.EAGER, cascade = {CascadeType.ALL},      orphanRemoval = true)     private List blockPlazas = new ArrayList ();

But I get this error: INFO: HHH000397: Using ASTQueryTranslatorFactory Hibernate: insert into USER (Surname, First Name, Phone, UserCode) values (?,?,?,?) Hibernate: insert into CONTAINER (Description, NColumns, NFils, Name, Type, UserCell) values (?,?,?,?,?,?) Hibernate: select squaresbloc_.IdContainer, squaresbloc_.PosicionX, plazasbloc_.PosicionY from PLAZASBLOCK plazasbloc_ where plazasbloc_.IdContenedor =? and plazasbloc_.PosicionX =? and plazasbloc_.PosicionY =? Hibernate: select squaresbloc_.IdContainer, squaresbloc_.PosicionX, plazasbloc_.PosicionY from PLAZASBLOCK plazasbloc_ where plazasbloc_.IdContenedor =? and plazasbloc_.PosicionX =? and plazasbloc_.PosicionY =? Hibernate: insert into PLAZASBLOCK (IdContainer, PositionX, PositionY) values (?,?,?) Oct 09, 2018 7:51:25 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN: SQL Error: 1048, SQLState: 23000 Oct 09, 2018 7:51:25 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: Column 'IdContainer' can not be null Oct 09, 2018 7:51:25 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release INFO: HHH000010: On release of batch it still contained JDBC statements Exception in thread "AWT-EventQueue-0" org.hibernate.exception.ConstraintViolationException: could not execute statement     at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert (SQLExceptionTypeDelegate.java:72)     at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert (StandardSQLExceptionConverter.java:49)

    
asked by Edwink 09.10.2018 в 07:43
source

1 answer

0

You are missing a detail in the entry:

@OneToMany(mappedBy = "contenedor",
     fetch = FetchType.EAGER,
     cascade = {CascadeType.ALL},
     orphanRemoval = true)
private List<PlazasBlock> blockPlazas= new ArrayList();

With these attributes you tell Hibernate that if there is a change in the list it is also reflected in the database, whether you delete or add elements.

    
answered by 09.10.2018 в 10:13