How to delete a child record when there ManyToOne relationship?

606 views Asked by At

Table grpUsuario

        @Id
        @Basic(optional = false)
        @NotNull
        @Column(name = "grupo")
        private Integer grupo;

        @Basic(optional = false)
        @NotNull
        @Size(min = 1, max = 64)
        @Column(name = "descripcion")
        private String descripcion;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "secLevel")
        private Collection<Menu> menuCollection;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "grupo", orphanRemoval = true)
        private Collection<Usuario> usuarioCollection;ç

Table Usuario

    @Id
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 64)
    @Column(name = "IdUsuario")
    private String idUsuario;

    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 64)
    @Column(name = "password")
    private String password;

    @Size(max = 16)
    @Column(name = "nombres")
    private String nombres;

    @Size(max = 24)
    @Column(name = "apellidos")
    private String apellidos;

    // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Correo electrónico no válido")//if the field contains email address consider using this annotation to enforce field validation
    @Size(max = 64)
    @Column(name = "email")
    private String email;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idUsuario")
    private Collection<Encuesta> encuestaCollection;

    @JoinColumn(name = "grupo", referencedColumnName = "grupo" )
    @ManyToOne(optional = false)
    private Grpusuario grupo;

Controller

String cod = request.getParameter("cod");
Usuario usuario= new Usuario(cod);
boolean resultado = usuario_servicio.delete(usuario);

Function to delete

 public boolean delete(Usuario usuario){
        Session session = HibernateUtil.openSession();  
        Transaction tx = null;        
        try {
            tx = session.getTransaction();
            tx.begin();
            session.delete(usuario);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }        
        return true;
    }

This is the code that I have but I did not delete the record. This same code I've tried to tables that have relationships and if it works that more should I do to work me to delete child records?

2

There are 2 answers

0
mabi On BEST ANSWER

As discussed in the comments: the entity needs to be in the persistence context for Hibernate to properly delete it. So the solution is to fetch it using Hibernate first.

Replace

session.delete(usuario);

with

session.delete(session.get(Usuario.class, usuario.getIdUsuario()));

Be careful: get() can return null values if the entity is no longer in the database, so you better check for that before passing the object to delete.

0
José María Barrientos On

You can update the registres and later deletes with SQL.