一个非常奇怪的错误ClassCastException。 PreparedStatement的setInt方法

时间:2010-07-11 03:46:23

标签: java jsf jdbc

有谁可以告诉我为什么这种方法不起作用?

String strQuery = "Insert Into cust_subs (CustomerId,SubscriptionId) Values (?,?)";
PreparedStatement objPreparedStatement = Utils.getPreparedStatement(objConnection, strQuery);
objPreparedStatement.setInt(2, currentSubscriptions.get(0) );

其中currentSubscriptions是:

List<Integer> currentSubscriptions;

即使它是整数列表,我也会收到此错误: -

  

SEVERE:java.lang.ClassCastException:java.lang.String无法强制转换为java.lang.Integer

假设连接对象已存在。而且我非常确定currentSubscriptions不是null,否则我就不会有这个错误。如果不是像List那样使用硬编码:

objPreparedStatement.setInt(2,1);

有效。我甚至使用System.out.println打印了List的值,它非常好。它们只是整数。不知道为什么把它们视为字符串。我甚至在列表的项目上尝试了Integer.parseInt。它仍然给我同样的错误。这是我遇到的最有趣的错误之一。

提前致谢:)

编辑: -

至少这应该有效。但即使这样也行不通: -

  int intSubscriptionId = Integer.parseInt( currentSubscriptions.get(0).toString());

            objPreparedStatement.setInt(2, intSubscriptionId );

编辑2:

发布完整代码: -

package beans;

import entities.Customer;
import entities.Subscription;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import misc.Utils;

@ManagedBean
@ViewScoped
public class AddSubscriptionBean implements Serializable {

    private Customer customer;
    private List<Integer> currentSubscriptions;
    private List<Subscription> subscriptionList;

    public List<Subscription> getSubscriptionList() {
        return subscriptionList;
    }

    public void setSubscriptionList(List<Subscription> subscriptionList) {
        this.subscriptionList = subscriptionList;
    }

    public List<Integer> getCurrentSubscriptions() {
        return currentSubscriptions;
    }

    public void setCurrentSubscriptions(List<Integer> currentSubscriptions) {
        this.currentSubscriptions = currentSubscriptions;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    /** Creates a new instance of AddSubscriptionBean */
    public AddSubscriptionBean() throws IOException, SQLException {

        Connection objConnection = null;
        try {
            HttpServletRequest objHttpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            int intCustomerId = Integer.parseInt(objHttpServletRequest.getParameter("cid"));
            String strQuery = "Select * from customer Where CustomerID = " + intCustomerId;

            ResultSet objResultSet = Utils.executeResultSet(objConnection, strQuery);
            if (objResultSet.next()) {
                String strFirstName = objResultSet.getString("FirstName");
                String strLastName = objResultSet.getString("LastName");
                customer = new Customer(intCustomerId, strFirstName, strLastName);
            }

            currentSubscriptions = new ArrayList<Integer>();

            for (Subscription objSubscription : customer.getSubscriptionList()) {
                currentSubscriptions.add(objSubscription.getSubscriptionId());
            }


            subscriptionList = new ArrayList<Subscription>();
            strQuery = "Select * from subscription";
            objResultSet = Utils.executeResultSet(objConnection, strQuery);
            while (objResultSet.next()) {
                int intSubscriptionId = objResultSet.getInt("SubscriptionId");
                String strSubsriptionTitle = objResultSet.getString("Title");
                String strSubsriptionType = objResultSet.getString("Type");
                Subscription objSubscription = new Subscription(intSubscriptionId, strSubsriptionTitle, strSubsriptionType);
                subscriptionList.add(objSubscription);
            }


        } catch (Exception ex) {
            ex.printStackTrace();
            FacesContext.getCurrentInstance().getExternalContext().redirect("index.jsf");
        } finally {
            if (objConnection != null) {
                objConnection.close();
            }
        }
    }

    public void save() throws SQLException {

        Connection objConnection = null;
        Savepoint objSavepoint = null;
        try {
            objConnection = Utils.getConnection();
            objConnection.setAutoCommit(false);
            objSavepoint = objConnection.setSavepoint();
            String strQuery = "Delete From cust_subs Where CustomerId = " + customer.getCustomerId();

            if (!Utils.executeQuery(objConnection, strQuery)) {
                throw new Exception();
            }

            strQuery = "Insert Into cust_subs (CustomerId,SubscriptionId) Values (?,?)";


            int intCustomerId = customer.getCustomerId();
            PreparedStatement objPreparedStatement = Utils.getPreparedStatement(objConnection, strQuery);
            for (int intIndex = 0; intIndex < currentSubscriptions.size(); intIndex++) {
                objPreparedStatement.setInt(1, intCustomerId);
                int intSubscriptionId = Integer.parseInt( currentSubscriptions.get(0).toString());

                objPreparedStatement.setInt(2, intSubscriptionId );
                objPreparedStatement.addBatch();
            }

            objPreparedStatement.executeBatch();

            objConnection.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            if (objConnection != null) {
                objConnection.rollback(objSavepoint);
            }
        } finally {
            if (objConnection != null) {
                objConnection.close();
            }
        }
    }
}

这是我的JSF页面: -

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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:msc="http://mscit/jsf">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <center>
            <h:form>
            <h1>Add Subscription</h1>

            <b> Customer Name :</b> <h:outputText value="#{addSubscriptionBean.customer.firstName} #{addSubscriptionBean.customer.lastName}"/>

            <h:selectManyCheckbox value="#{addSubscriptionBean.currentSubscriptions}">

                <f:selectItems value="#{addSubscriptionBean.subscriptionList}" var="row" itemLabel="#{row.title}" itemValue="#{row.subscriptionId}" />

            </h:selectManyCheckbox>

            <h:commandButton value="Save" actionListener="#{addSubscriptionBean.save}"/>
            </h:form>
        </center>
    </h:body>
</html>

请查看JSF的h:selectManyCheckbox。 JSF在内部将我检查过的所有复选框传递给我的列表。我认为JSF正在将我的整数列表转换为字符串。

2 个答案:

答案 0 :(得分:6)

您需要指示h:selectManyCheckboxInteger指定为转换器,将值转换为javax.faces.Integer。 EL中的通用类型是未知的,它默认将参数视为String

<h:selectManyCheckbox converter="javax.faces.Integer">

不需要使用List<String>代替,这只会导致bean中出现更多弱类型的混乱。

答案 1 :(得分:3)

如果使用不安全的操作,可以将字符串放入List<Integer>

List<Integer> intList = new ArrayList<Integer>();
List list = intList;
list.add("1");

intListlist保持对同一列表的引用,该列表现在包含一个字符串。如您所见,在尝试从ClassCastException中提取元素时,您会获得intList

Java泛型使用隐藏转换工作,您可以打败类型检查。要测试它,请分配给List,然后打印每个元素的类:

List currentSubscriptionsUnsafe = currentSubscriptions;
for(Object o : currentSubscriptionsUnsafe)
{
  System.out.println(o.getClass());
}

编辑:我不熟悉JSF,但我认为您的猜测是正确的。一种解决方案是让currentSubscriptions到处都是List<String>(JSF似乎期待)。然后,get(0)将返回String,您可以将其解析为Integer。可能有一个更干净的方法,但这应该有效。