0

I'm new to JSF and Java EE. I'm trying to do my first webapp (Java EE+JSF+Hibernate).

I have "Partido" and "Equipo" classes. One Partido have two Equipo on it. If I want to delete a "Equipo" that already exists in "Partido"......Error...... constraint blablabla.....

I know what is this error but I dont know how I can handle it with JSF (for showing an error on the same web, or a popup message.

The problem is when I press the Remove buton from JFS view, do nothing and in Eclipse Im getting the exception...

This is the button :

And the code...

EquipoBean

package beans;

import java.sql.SQLException;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.hibernate.Hibernate;



import dao.DAOFactory;
import dao.utils.HibernateUtil;
import domain.Equipo;
import domain.Partido;



@ManagedBean
@SessionScoped
public class EquipoBean {

    private Equipo equipo;
    private List<Equipo> listaDeEquipos;
    private boolean dirty=false;
    private String selectedEquipo;


    private void crearEquipo(){
        equipo=new Equipo();
    }


    public Equipo getEquipo() {
        return equipo;
    }


    public void setEquipo(Equipo equipo) {
        this.equipo = equipo;
    }

    public List<Equipo> getListaDeEquipos() {
        if(listaDeEquipos==null || dirty==true){
            listaDeEquipos=DAOFactory.getEquipoDAO().findAll();
            dirty=false;
            selectedEquipo=null;
        }
        return listaDeEquipos;
    }

    public void setListaDeEquipos(List<Equipo> equipos) {
        this.listaDeEquipos = equipos;
    }


    public String getSelectedEquipo(){return selectedEquipo;    }
    public void setSelectedEquipo(String selectedEquipo){this.selectedEquipo = selectedEquipo;}



    public void guardar() {
        HibernateUtil.beginTransaction();
        DAOFactory.getEquipoDAO().save(equipo);
        HibernateUtil.endTransaction();
        dirty=true;
    }

    public void actualizar(){
        if(selectedEquipo==null)
            crearEquipo();
        else{
            equipo=DAOFactory.getEquipoDAO().findById(Integer.valueOf(selectedEquipo));
        }
    }

    public void eliminar(ActionEvent e){

        HibernateUtil.beginTransaction();
        Equipo p=DAOFactory.getEquipoDAO().findById(Integer.valueOf(selectedEquipo));
        DAOFactory.getEquipoDAO().remove(p);
        HibernateUtil.endTransaction();
        selectedEquipo=null;
        dirty=true;

    }


}

PartidoBean

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import dao.DAOFactory;
import dao.utils.HibernateUtil;
import domain.Partido;

@ManagedBean
@SessionScoped
public class PartidoBean {


    /**** AJAX LISTENERS ***********************************/

        private String jornada;
        public String getJornada() {return jornada;}
        public void setJornada(String jornada) {this.jornada = jornada;}

        private String equipo;
        public String getEquipo(){return equipo;}
        public void setEquipo(String equipo){this.equipo = equipo;}


        public void filtroJornada(){
            this.filtraPorJornada();
        }

        public void filtroEquipo(){
            this.filtraPorEquipo();
        }

        private void filtraPorJornada(){
            if(jornada.equals("Todas"))
                listaDePartidos=DAOFactory.getPartidoDAO().findAll();
            else
                listaDePartidos=DAOFactory.getPartidoDAO().findByJornada(jornada);
        }

        private void filtraPorEquipo(){
            if(equipo.trim().length()==0)
                listaDePartidos=DAOFactory.getPartidoDAO().findAll();
            else
                listaDePartidos=DAOFactory.getPartidoDAO().findBySimilarEquipo(equipo);
        }

    /**** AJAX LISTENERS ***********************************/

    public String guardaPartido(){
        String equipoLocal=partido.getEquipoLocal().getNombre();
        String equipoVisitante=partido.getEquipoVisitante().getNombre();

        if(!equipoLocal.equals(equipoVisitante)){
           guardar();
           return "listado";
        }
        else{
           return "error";
        }
    }

    private void guardar(){
           HibernateUtil.beginTransaction();
           DAOFactory.getPartidoDAO().save(partido);
           HibernateUtil.endTransaction();
           dirty=true;
    }

    public void eliminar(ActionEvent e){

        HibernateUtil.beginTransaction();
        Partido p=DAOFactory.getPartidoDAO().findById(Integer.valueOf(selectedPartido));
        DAOFactory.getPartidoDAO().remove(p);
        HibernateUtil.endTransaction();

        selectedPartido=null;
        dirty=true;
    }

    private String selectedPartido;
    public String getSelectedPartido(){return selectedPartido;  }
    public void setSelectedPartido(String selectedPartido){this.selectedPartido = selectedPartido;}


    public void actualizar(){
        if(selectedPartido==null)
            crearPartido();
        else{
            partido=DAOFactory.getPartidoDAO().findById(Integer.valueOf(selectedPartido));

        }
    }

    private void crearPartido(){
        partido=new Partido();
    }
    /*******************************************************************/



    private Partido partido;
    public Partido getPartido() {
        return partido;
    }
    public void setPartido(Partido partido) {
        this.partido = partido;
    }


    private List<Partido> listaDePartidos;
    private boolean dirty=false;
    public List<Partido> getListaDePartidos() {
        if(listaDePartidos==null || dirty==true){
            listaDePartidos=DAOFactory.getPartidoDAO().findAll();
            dirty=false;
            selectedPartido=null;
        }
        return listaDePartidos;
    }
    public void setListaDePartidos(List<Partido> partidos) {
        this.listaDePartidos = partidos;
    }


    private boolean porJugar;
    public boolean isPorJugar() {
        return porJugar;
    }
    public void setPorJugar(boolean porJugar) {
        this.porJugar = porJugar;
    }


}

EquipoDAOImpl

package dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import dao.utils.GenericHibernateDAO;
import domain.Equipo;

class EquipoDAOImpl extends GenericHibernateDAO implements EquipoDAO{

    public EquipoDAOImpl(Session s) {
        super(s);
    }

    @SuppressWarnings("unchecked")
    public Equipo findById(Integer id) {
        Equipo entity;
        entity = (Equipo) getSession().get(Equipo.class, id);
        return entity;
    }

    @SuppressWarnings("unchecked")
    public List<Equipo> findAll() {
        Query q = getSession().createQuery("From Equipo");
        return q.list();
    }

    @Override
    public void save(Equipo entity) {
        getSession().saveOrUpdate(entity);

    }

    @Override
    public void remove(Equipo entity){
        getSession().delete(entity);


    }

}

listEquipos.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui"
      template="layout.xhtml">


<ui:define name="cuerpo">      
<h:form prependId="false">
<h:panelGrid id="MainGrid" columns="1" columnClasses="columnGrid" styleClass="mainGrid">
            <p:dataTable paginator="true" rows="10" id="equipos"  value="#{equipoBean.listaDeEquipos}" var="equipo" columnClasses="columnTable columnTable1,columnTable columnTable2,columnTable columnTable3,columnTable columnTable4">
              <p:column>
                <f:facet name="header">
                    <h:outputText  value="#{msgs['list.idEquipo']}"/>
                </f:facet>
                <h:outputText value="#{equipo.idEquipo}" />
              </p:column>

              <p:column>
                <f:facet name="header">
                    <h:outputText  value="#{msgs['list.nombreEquipo']}"/>
                </f:facet>
                <h:outputText value="#{equipo.nombre}" >

                </h:outputText>
              </p:column>

              <p:column>
                <f:facet name="header">
                    <h:outputText  value="#{msgs['list.direccionEquipo']}"/>
                </f:facet>
                <h:outputText value="#{equipo.direccion}" />
              </p:column>

              <p:column >
                <f:facet name="header">
                    <h:outputText  value="#{msgs['equipo.operaciones']}"/>
                </f:facet>
               <h:panelGroup>
                    <p:commandButton value="#{msgs['equipo.eliminar']}" onclick="PF('confirmation').show();" >
                        <f:setPropertyActionListener value="#{equipo.idEquipo}" target="#{equipoBean.selectedEquipo}" />    
                    </p:commandButton>
                    <p:button value="#{msgs['equipo.editar']}" outcome="editar">
                        <f:param name="selectedEquipo" value="#{equipo.idEquipo}" />
                    </p:button>             
                </h:panelGroup>
          </p:column>


        </p:dataTable>
    </h:panelGrid>



        <h:panelGrid columns="2">
        <p:commandButton ajax="false" value="#{msgs['list.equipos']}" action="listado" />
        <p:commandButton ajax="false" value="#{msgs['equipo.nuevo']}" action="editar" />
      </h:panelGrid>

         <p:confirmDialog message="#{msgs['equipo.seguroBorrar']}"
                    showEffect="bounce" hideEffect="explode"  
                    severity="alert" widgetVar="confirmation">  

            <p:commandButton update="MainGrid" process="@this" value="#{msgs['lista.si']}" actionListener="#{equipoBean.eliminar}"  oncomplete="PF('confirmation').hide()"/>
            <p:commandButton value="#{msgs['lista.no']}" onclick="PF('confirmation').hide()" />   
     </p:confirmDialog>

</h:form>
</ui:define>
</ui:composition>

Stacktrace

ADVERTENCIA: /listEquipos.xhtml @65,164 actionListener="#{equipoBean.eliminar}": org.hibernate.exception.ConstraintViolationException: could not execute statement
javax.el.ELException: /listEquipos.xhtml @65,164 actionListener="#{equipoBean.eliminar}": org.hibernate.exception.ConstraintViolationException: could not execute statement
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: 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)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3400)
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3630)
    at org.hibernate.action.internal.EntityDeleteAction.execute(EntityDeleteAction.java:114)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
    at dao.utils.HibernateUtil.endTransaction(HibernateUtil.java:30)
    at beans.EquipoBean.eliminar(EquipoBean.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 32 more
Caused by: java.sql.SQLIntegrityConstraintViolationException: violación del restricción de integridad: sin acción para la clave foránea; SYS_FK_10097 table: JUGADORES
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
    ... 53 more

nov 21, 2014 3:36:30 AM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: 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)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3400)
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3630)
    at org.hibernate.action.internal.EntityDeleteAction.execute(EntityDeleteAction.java:114)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
    at dao.utils.HibernateUtil.endTransaction(HibernateUtil.java:30)
    at beans.EquipoBean.eliminar(EquipoBean.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.SQLIntegrityConstraintViolationException: violación del restricción de integridad: sin acción para la clave foránea; SYS_FK_10097 table: JUGADORES
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
    ... 53 more

Any help?

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Miguel Cabanes
  • 103
  • 2
  • 10
  • 1
    Did you have a look at this ---> http://stackoverflow.com/q/13892473/1055089 ? – Vrushank Nov 21 '14 at 06:19
  • After a long reading of many webs I think I have a problem with JSF and Ajax with handling errors. I tried to make another command button without AJAX and I can get the exception thought the webapp (visualiced in the web and eclipse ide). I will profundice more in this subject but if anyone has more info, will be appreciated :) – Miguel Cabanes Nov 21 '14 at 17:33

1 Answers1

0

Go to you "eliminar" method in your EquipoBean and catch the exception with a try-catch.

When catching an exception, create a FacesMessage like this:

FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("cannot remove"));

then add a "h:messages" tag on your page. After clicking the "eliminar" button, the message should appear in the messages section.