Issue
I want to insert the values of the products which are of type arrayList into the database but I'm getting this error "java.lang.String cannot be cast to model.Product"
. The problem is with the cast I did in servlet. this is its code:
String buyer = request.getParameter("buyer");
List<String> prodlist = Arrays.asList(request.getParameterValues("product"));
List<Product> prodmlist = (List<Product>) (List<?>) prodlist;
Bill bill = new Bill(buyer, prodmlist);
myDAO.add(bill);
and this is the method which will be populated
public static void add(Bill bill) {
Connection cnx;
try {
cnx = Connect.getConnection();
String req = "insert into bil values (?,?)";
PreparedStatement st = cnx.prepareStatement(req);
st.setString(1, bill.getBuyer());
for (Product prod : bill.getProduct()) {
st.setString(2, prod.getName());
st.addBatch(); // add the statement to the batch
}
st.executeUpdate();
cnx.commit();
}
Solution
In your code:
List<String> prodlist = Arrays.asList(request.getParameterValues("product"));
// Need to convert here...
List<Product> prodmlist = (List<Product>) (List<?>) prodlist;
You need to explicitly convert from List<String>
to List<Product>
. Do something along the lines of:
List<Product> products = new ArrayList<Product>();
for (String s: prodList){
Product p = new Product();
p.setName(s);
products.add(p);
}
Now, I am making the assumption you have a setter to set the name on Product. It may be you have a constructor you can pass the name to (and save a line of code).
Answered By - David Brossard