Java – How to edit datatable’s rows (JAVA + Primefaces + JSF + MYSQL)

dialogjavajsf-2MySQLprimefaces

I have a datatable page (Java + JSF + PRIMEFACES + Oracle GlassFish Server 3.1.2.2 + MYSQL). When i designate rows in my page and i click Show button, then you can see in the pop-up window this:

enter image description here

when I'm trying to edit the rows i click Edit

enter image description here

The problem starts here, when i click check mark, then the row(s) are disappear:

enter image description here

I see in the server log:

ThreadName=Thread-2;|javax.faces.model.NoRowAvailableException
javax.faces.model.NoRowAvailableException
at javax.faces.model.ListDataModel.getRowData(ListDataModel.java:150)
at javax.faces.component.UIData.getRowData(UIData.java:371)
at org.primefaces.component.datatable.DataTable.queueEvent(DataTable.java:620)
at org.primefaces.component.behavior.ajax.AjaxBehaviorRenderer.decode(AjaxBehaviorRenderer.java:44)
at javax.faces.component.behavior.ClientBehaviorBase.decode(ClientBehaviorBase.java:132)
at org.primefaces.renderkit.CoreRenderer.decodeBehaviors(CoreRenderer.java:395)
at org.primefaces.component.datatable.DataTableRenderer.decode(DataTableRenderer.java:64)
at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:787)
at org.primefaces.component.api.UIData.processDecodes(UIData.java:232)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:506)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at org.primefaces.component.api.UIData.visitTree(UIData.java:675)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIForm.visitTree(UIForm.java:344)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252)
at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:57)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:931)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:724) |#]

Here it is My page:

<html 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"
      >

    <h:head>    
            <title>Teszt</title>        
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>                        
            <link rel="stylesheet" type="text/css" href="style.css"/>            
    </h:head>

    <ui:debug />
    <h:form id="form">
        <p:fieldset legend="Teszt:">
            <p:dataTable id="dataTableTeszt" value="#{TesztBean.values}" var="c" paginator="true" rows="25" editable="true" filteredValue="#{TesztBeanBean.filteredOsszesito}" scrollable="true" scrollWidth="1500" scrollHeight="550"
                        paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"  
                        paginatorPosition="bottom" rowsPerPageTemplate="5,10,15,20,30,40,50" 
                        selectionMode="multiple" selection="#{TesztBean.selectList}" rowKey="#{c.id}">

                        <p:column selectionMode="multiple" style="width:2%;text-align:center"/>

                        <p:column style="width: 130px; text-align: center" filterBy="#{c.id}" filterMatchMode="contains">
                            <f:facet name="header">ID:</f:facet>                                
                            <h:outputText value="#{c.id}" style="width: 130px; text-align: center"/>                                                
                        </p:column>


                        <p:column style="width: 130px; text-align: center" filterBy="#{c.name}" filterMatchMode="contains">
                            <f:facet name="header">Name:</f:facet>                                                                                                        
                            <h:outputText value="#{c.name}" style="width: 130px; text-align: center"/>                            
                        </p:column>

                        <p:column style="width: 130px; text-align: center" filterBy="#{c.age}" filterMatchMode="contains" >
                            <f:facet name="header">Age:</f:facet>                                                                                                        
                            <h:outputText value="#{c.age}" style="width: 130px; text-align: center"/>                            
                        </p:column>    


                        <p:column style="width: 230px; text-align: center" filterBy="#{c.kapcsolatfelvetel_megtortent}" filterMatchMode="contains" >
                            <f:facet name="header">Kapcsolatfelvétel megtörtént:</f:facet>                                                                                                        
                            <h:outputText value="#{c.kapcsolatfelvetel_megtortent}" style="width: 230px; text-align: center"/>                                
                        </p:column>               

                        <p:column style="width: 230px; text-align: center" filterBy="#{c.levelkuldesenek_datuma}" filterMatchMode="contains" >
                            <f:facet name="header">Levélküldés dátuma:</f:facet>                                                                                                        
                            <h:outputText value="#{c.levelkuldesenek_datuma}" style="width: 230px; text-align: center"/>                            
                        </p:column>

                        <p:column style="width: 230px; text-align: center" filterBy="#{c.kepzes_kezdete}" filterMatchMode="contains" >
                            <f:facet name="header">Képzés kezdete:</f:facet>
                            <h:outputText value="#{c.kepzes_kezdete}" style="width: 230px; text-align: center"/>                            
                        </p:column>

                        <p:column style="width: 230px; text-align: center" filterBy="#{c.kepzes_vege}" filterMatchMode="contains" >
                            <f:facet name="header">Képzés vege:</f:facet>
                            <h:outputText value="#{c.kepzes_vege}" style="width: 230px; text-align: center"/>                            
                        </p:column>

                        <p:column style="width: 1000px; text-align: center" filterBy="#{c.magyarazat}" filterMatchMode="contains">
                            <f:facet name="header">Megjegyzés:</f:facet>
                            <h:outputText value="#{c.magyarazat}" style="width: 1000px; text-align: center"/>                            
                        </p:column>   
                        <f:facet name="footer">                            
                            <p:commandButton id="addCategoryButton" value="Show" oncomplete="categoryDialog.show();" update=":form:dataTableTesztDialog :form:categoryDialog"/>
                        </f:facet>
        </p:dataTable>  
        </p:fieldset>

        <p:dialog id="categoryDialog" header="Category Detail" widgetVar="categoryDialog" closeOnEscape="true" resizable="false" style="width:1000px; height: 500px;" showEffect="explode" hideEffect="bounce">          
            <p:dataTable id="dataTableTesztDialog" value="#{TesztBean.selectList}" var="d" paginator="true" rows="25" editable="true">

                    <p:ajax event="rowEdit" listener="#{TesztBean.update(event)}"/>

                    <p:column style="width: 60px; text-align: center" headerText="Edit">
                        <p:rowEditor />
                    </p:column>

                    <p:column style="width: 130px; text-align: center">
                            <f:facet name="header">ID:</f:facet>                                                
                            <p:cellEditor>
                                <f:facet name="output">
                                    <h:outputText value="#{d.id}" style="width: 130px; text-align: center"/>
                                </f:facet>
                                <f:facet name="input">
                                    <p:inputText value="#{d.id}"/>
                                </f:facet>
                            </p:cellEditor>
                    </p:column>

                    <p:column style="width: 230px; text-align: center">
                        <f:facet name="header">Kapcsolatfelvétel megtörtént:</f:facet>                                                
                        <p:cellEditor>
                            <f:facet name="output">
                                <h:outputText value="#{d.kapcsolatfelvetel_megtortent}" style="width: 230px; text-align: center"/>
                            </f:facet>
                            <f:facet name="input">
                                <p:inputText value="#{d.kapcsolatfelvetel_megtortent}"/>
                            </f:facet>
                        </p:cellEditor>
                    </p:column>               

                        <p:column style="width: 230px; text-align: center">
                            <f:facet name="header">Levélküldés dátuma:</f:facet>                                                
                            <p:cellEditor>
                                <f:facet name="output">
                                    <h:outputText value="#{d.levelkuldesenek_datuma}" style="width: 230px; text-align: center"/>
                                </f:facet>
                                <f:facet name="input">
                                    <p:inputText value="#{d.levelkuldesenek_datuma}"/>
                                </f:facet>
                            </p:cellEditor>
                        </p:column>

                        <p:column style="width: 230px; text-align: center">
                            <f:facet name="header">Képzés kezdete:</f:facet>                                                
                            <p:cellEditor>
                                <f:facet name="output">
                                    <h:outputText value="#{d.kepzes_kezdete}" style="width: 230px; text-align: center"/>
                                </f:facet>
                                <f:facet name="input">
                                    <p:inputText value="#{d.kepzes_kezdete}"/>
                                </f:facet>
                            </p:cellEditor>
                        </p:column>

                        <p:column style="width: 230px; text-align: center">
                            <f:facet name="header">Képzés vege:</f:facet>                                                
                            <p:cellEditor>
                                <f:facet name="output">
                                    <h:outputText value="#{d.kepzes_vege}" style="width: 230px; text-align: center"/>
                                </f:facet>
                                <f:facet name="input">
                                    <p:inputText value="#{d.kepzes_vege}"/>
                                </f:facet>
                            </p:cellEditor>
                        </p:column>

                        <p:column style="width: 350px; text-align: center">
                            <f:facet name="header">Megjegyzés:</f:facet>                                                
                            <p:cellEditor>
                                <f:facet name="output">
                                    <h:outputText value="#{d.magyarazat}" style="width: 350px; text-align: center"/>
                                </f:facet>
                                <f:facet name="input">
                                    <p:inputText value="#{d.magyarazat}"/>
                                </f:facet>
                            </p:cellEditor>
                        </p:column>
                </p:dataTable>        
        </p:dialog>


    </h:form> 

</html>

Here it is my bean class:

import java.awt.event.ActionEvent;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import org.primefaces.event.RowEditEvent;
import org.primefaces.model.LazyDataModel;

@ManagedBean(name="tesztBean")
@SessionScoped
@ViewScoped

public class TesztBean{

    String URL = "jdbc:mysql://localhost:3306/osszesito?useUnicode=yes&characterEncoding=UTF-8";
    String USER = "User";        
    String PASSWORD = "Password";
    String DRIVER = "com.mysql.jdbc.Driver";

    private List<TesztSetGet> filteredOsszesito;
    private List<TesztSetGet> values;        
    private List<TesztSetGet> selectList;


    public List<TesztSetGet> getSelectList() {
        return selectList;
    }

    public void setSelectList(List<TesztSetGet> selectList) {
        this.selectList = selectList;
    }

    @PostConstruct
    public void init() {
        try {
            values = selectTesztTable();
        } catch (SQLException e) {

             e.printStackTrace();    
        }
    }


    public Connection getDBConnection() {

        Connection dbConnection = null;

        try {

            Class.forName(DRIVER);
            dbConnection= DriverManager.getConnection(URL, USER, PASSWORD);
            System.out.println("Connection completed.");

        } catch (SQLException e) { 

            System.out.println(e.getMessage()); 

        }catch(ClassNotFoundException cnfe){

           cnfe.printStackTrace();
           System.out.println(cnfe.getMessage());
           System.exit(-1);

       }

        return dbConnection; 
    }


    public List<TesztSetGet> selectTesztTable() throws SQLException{

        ResultSet rs = null;
        PreparedStatement pst = null;
        Connection con = getDBConnection();

        String stm = "select * from teszt order by age";

        List<TesztSetGet> records = new ArrayList<TesztSetGet>();


        try {

            pst = con.prepareStatement(stm);
            pst.execute();
            rs = pst.getResultSet();

         while(rs.next()){

            TesztSetGet objectMeghiv = new TesztSetGet();

            objectMeghiv.setId(rs.getInt(1));            
            objectMeghiv.setName(rs.getString(2)); 
            objectMeghiv.setAge(rs.getInt(3)); 
            objectMeghiv.setKapcsolatfelvetel_megtortent(rs.getString(4));            
            objectMeghiv.setLevelkuldesenek_datuma(rs.getString(5));
            objectMeghiv.setKepzes_kezdete(rs.getString(6));
            objectMeghiv.setKepzes_vege(rs.getString(7));
            objectMeghiv.setMagyarazat(rs.getString(8));                   
            records.add(objectMeghiv);

         }

         return records;


        }catch (SQLException e) {
            e.printStackTrace();         
        }catch (Exception e) {
            e.printStackTrace();         
        }finally{

            rs.close();
            pst.close();            
            con.close();

     }

      return records;

    }


    public List<TesztSetGet> getValues() { 

        return values; 

    }



    public void update(RowEditEvent event) {

        TesztSetGet edittedObject = (TesztSetGet) event.getObject();        

        Connection connection = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String sql = "update teszt set kapcsolatfelvetel_megtortent=?, levelkuldes_datuma=?, kepzes_kezdete=?, kepzes_vege=?, megjegyzes=?  where id=?";

        try{

            connection = getDBConnection();                                                                       
            pst = connection.prepareStatement(sql);



            pst.setString(1, edittedObject.getKapcsolatfelvetel_megtortent());
            pst.setString(2, edittedObject.getLevelkuldesenek_datuma());
            pst.setString(3, edittedObject.getKepzes_kezdete());
            pst.setString(4, edittedObject.getKepzes_vege());
            pst.setString(5, edittedObject.getMagyarazat());
            pst.setInt(6, edittedObject.getId());

            pst.executeUpdate();
            pst.close();
            connection.close();

        }catch(SQLException se){
            se.printStackTrace();
            se.getMessage();
         }catch(Exception e){
             e.printStackTrace();
             e.getMessage();
         }    


    }

    public List<TesztSetGet> getFilteredOsszesito() {
        return filteredOsszesito;
    }

    public void setFilteredOsszesito(List<TesztSetGet> filteredOsszesito) {
        this.filteredOsszesito = filteredOsszesito;
    }

}

Here it is my Set and Getter class:

public class TesztSetGet {

   private int id;    
   private String name;
   private int age;   
   private String kapcsolatfelvetel_megtortent;
   private String levelkuldesenek_datuma;
   private String kepzes_kezdete;
   private String kepzes_vege;
   private String magyarazat;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getKapcsolatfelvetel_megtortent() {
        return kapcsolatfelvetel_megtortent;
    }

    public void setKapcsolatfelvetel_megtortent(String kapcsolatfelvetel_megtortent) {
        this.kapcsolatfelvetel_megtortent = kapcsolatfelvetel_megtortent;
    }

    public String getLevelkuldesenek_datuma() {
        return levelkuldesenek_datuma;
    }

    public void setLevelkuldesenek_datuma(String levelkuldesenek_datuma) {
        this.levelkuldesenek_datuma = levelkuldesenek_datuma;
    }

    public String getKepzes_kezdete() {
        return kepzes_kezdete;
    }

    public void setKepzes_kezdete(String kepzes_kezdete) {
        this.kepzes_kezdete = kepzes_kezdete;
    }

    public String getKepzes_vege() {
        return kepzes_vege;
    }

    public void setKepzes_vege(String kepzes_vege) {
        this.kepzes_vege = kepzes_vege;
    }

    public String getMagyarazat() {
        return magyarazat;
    }

    public void setMagyarazat(String magyarazat) {
        this.magyarazat = magyarazat;
    }

}

How can I edit the rows properly?

Thank you very much,

Best Answer

Firstly, you have to know about kind of scopes:

  • Request.
  • View.
  • Session.
  • Application.

The scope is the time of life of your data, you must use only one, you have two scopes in your code:

@SessionScoped
@ViewScoped

I recommend you to use ViewScoped, but you think about how much time you want your data live, if you choose ViewScoped, your data would live while you don't change the view or the page, if you choose SessionScoped, your data would live while you don't logout.

Now, you have to update the list of your table. You have:

<p:dataTable id="dataTableTeszt" value="#{TesztBean.values}" var="c" paginator="true" rows="25" editable="true" filteredValue="#{TesztBeanBean.filteredOsszesito}" scrollable="true" scrollWidth="1500" scrollHeight="550"
                        paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"  
                        paginatorPosition="bottom" rowsPerPageTemplate="5,10,15,20,30,40,50" 
                        selectionMode="multiple" selection="#{TesztBean.selectList}" rowKey="#{c.id}">

The main list of your table is values value="#{TesztBean.values}", when you call to update method, you have to update your values list:

public void update(RowEditEvent event) {

        TesztSetGet edittedObject = (TesztSetGet) event.getObject();        

        Connection connection = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String sql = "update teszt set kapcsolatfelvetel_megtortent=?, levelkuldes_datuma=?, kepzes_kezdete=?, kepzes_vege=?, megjegyzes=?  where id=?";

        try{

            connection = getDBConnection();                                                                       
            pst = connection.prepareStatement(sql);



            pst.setString(1, edittedObject.getKapcsolatfelvetel_megtortent());
            pst.setString(2, edittedObject.getLevelkuldesenek_datuma());
            pst.setString(3, edittedObject.getKepzes_kezdete());
            pst.setString(4, edittedObject.getKepzes_vege());
            pst.setString(5, edittedObject.getMagyarazat());
            pst.setInt(6, edittedObject.getId());

            pst.executeUpdate();
            pst.close();
            connection.close();

            //UPDATE VALUES LIST WITH NEW DATA

        }catch(SQLException se){
            se.printStackTrace();
            se.getMessage();
         }catch(Exception e){
             e.printStackTrace();
             e.getMessage();
         }    


    }

I don't know how you can do it, but you can see the primefaces website, there are some samples about this, the idea is to update the main list of your table, values list in your case.

I hope this information helps you.

Good luck.

PS. If my english is bad, I am willing to receive comments. =P