0

I am trying to learn JSF and i have a problem with datatable. I get datas from database and add them to my list and try to show them in my page. It write datas 3 times. Why is it? Here is my code...

here is related part of bean..

    public  ArrayList<videos> getVideoss() {
    Connection con1 = null;
    PreparedStatement pst1 = null;
    ResultSet rs1 = null;

    String url1 = "jdbc:postgresql://localhost:5432/db";
    String user1 = "postgres";
    String password11 = "123";

    try {

        Class.forName("org.postgresql.Driver");
        con1 = DriverManager.getConnection(url1, user1, password11);
        pst1 = con1
                .prepareStatement("SELECT video_name FROM videos WHERE video_course = '"
                        + selectedCourse + "';");
        rs1 = pst1.executeQuery();

        while (rs1.next()) {
        videoss.add(new videos(rs1.getString(1)));

        }
        System.out.println(videoss.size());
        .....

xhtml file

   <h:dataTable value="#{videoSearch.videoss}" var="videos">
   <h:column>                   
   <f:facet name="header">Video Name</f:facet>                  
   #{videos.videoName}
   </h:column>
   </h:dataTable>

when i look the size of the list it goes like 6 , 12 , 18.. but it should be 6..

Thanks for your support..

mft
  • 319
  • 1
  • 5
  • 19

1 Answers1

1

As I commented, you are recreting the list every time the getter is called, so the list is growing because you are not clearing it anywhere. Here is a better way to do it :

// Will be called only one time
@PostConstruct
public init()
{
    Connection con1 = null;
    PreparedStatement pst1 = null;
    ResultSet rs1 = null;

    String url1 = "jdbc:postgresql://localhost:5432/Thesis";
    String user1 = "postgres";
    String password11 = "123";

    videoss = new ArrayList();

    try
    {
        Class.forName("org.postgresql.Driver");
        con1 = DriverManager.getConnection(url1, user1, password11);
        pst1 = con1.prepareStatement("SELECT video_name FROM videos WHERE video_course = '" + selectedCourse + "';");
        rs1 = pst1.executeQuery();

        while (rs1.next())
        {
            videoss.add(new videos(rs1.getString(1)));
        }

        System.out.println(videoss.size());

        //.....
     }
     catch(Excepption e)
     {
         e.printStackTrace();
     }
}

public ArrayList<videos> getVideoss()
{
    return videoss;
}
Alexandre Lavoie
  • 8,711
  • 3
  • 31
  • 72