0

I'm making book store and I have a button "Cart" which open shopping cart and user can see everything that he added. The problem is every time I click on that button I'm executing a select query and adding that book/s in ArrayList. For example a user added 2 books in cart, so every time I click "Cart" button it will add those two books in ArrayList and display them(everything is good in db). This is how method looks like:

private static DataSource dataSource;
private static ArrayList<Article> articleList = new ArrayList<>();

public static void selectArticle() {
           
    try {
        InitialContext ctx = new InitialContext();
        dataSource = (DataSource) ctx.lookup("jdbc/NemkeDB");
        Connection conn = dataSource.getConnection();
        String selectArticle = "select * from article where cart_id="+CartDAO.getAutoIncKey();// this is cart id
        PreparedStatement ps = conn.prepareStatement(selectArticle);
        ResultSet rs = ps.executeQuery(selectArticle);        
        while (rs.next()) {               
            int articleId = rs.getInt("id");
            String  articleTitle = rs.getString("title");
            double  articlePrice = rs.getDouble("price");
            double  articlePriceSum = rs.getDouble("priceSum");
            Article article = new Article(articleId, articleTitle, articlePrice,  articlePriceSum);
            articleList.add(article);
        }
    } catch (Exception e) {
        System.err.println(e);
    }
}

How can I show Cart without adding items every time when user clicks on a button? I just to display how it is in my database.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
nemke nemke
  • 191
  • 1
  • 1
  • 9
  • I would favor the use of in-memory cache for keeping track of items in the cart instead of every time I add an item it will make a database request. – corneliouz Bett Jul 14 '20 at 12:34

1 Answers1

1

Just check if the article with id articleList is already in your list - if so, don't add it to the list.

slawciu
  • 775
  • 4
  • 15