Java / PostgreSQL- CallableStatement.setBoolean null抛出NPE

时间:2016-08-15 14:33:26

标签: java postgresql

我有一个PostgreSQL函数update_renovation:

CREATE OR REPLACE FUNCTION update_renovation(
   p_county character varying, 
   p_municipality character varying, 
   p_district character varying, 
   p_neighbourhood character varying, 
   p_street character varying, 
   p_number character varying, 
   p_reported_by character varying, 
   p_is_renovated boolean) //<-- NOTE THIS boolean

RETURNS void AS
$BODY$
....

现在我从java这样调用这个函数

CallableStatement statement = con.prepareCall(" { call update_renovation( ?, ?, ?, ?, ?, ?, ?, ? ) } ");

        statement.setString(1, request.getAdr().getCounty());
        statement.setString(2, request.getAdr().getMunicipality());
        statement.setString(3, request.getAdr().getDistrict());
        statement.setString(4, request.getAdr().getNeighbourhood());
        statement.setString(5, request.getAdr().getStreet());
        statement.setString(6, request.getAdr().getNumber());
        statement.setString(7, request.getClientID());
        statement.setBoolean(8, request.isRenovated());  //<-- NOTE THIS boolean
        statement.execute();
        statement.close();

request.isRenovated()有时可能为null(它返回布尔值而不是布尔值)。

当发生这种情况时,java会在指定的行上抛出NPE。

我在setBoolean上读取了doc,它接受了布尔值(非布尔值),这可能是NPE的原因。

由于Postgre接受布尔值的NULL值,我的问题是如何在java服务器端将其设置为null?

谢谢!

1 个答案:

答案 0 :(得分:2)

如果isRenovated()返回null,则应致电PreparedStatement.setNull()

if (request.isRenovated() == null) {
    statement.setNull(8, Types.BOOLEAN);
} else {
    statement.setBoolean(8, request.isRenovated());
}

请注意,您只需使用采用原始参数的setXXX()方法执行此操作。您可以安全地将null传递给参考者。