我最近回到了Java,并且正在努力使以下方法起作用:

@Override
public T createEntity(T entity) throws SQLException{
    DatabaseMetaData dbMeta  = connection.getMetaData();
    boolean okay = dbMeta.supportsNamedParameters();
    if(okay) {
        System.out.println("Supports named arguments");
    } else {
        System.out.println("Does not support named arguments");
    }
    CallableStatement cstmt = connection.prepareCall("create_" + table.getName() + "(" + columns.stream().map( column -> "?").collect(Collectors.joining(","))  + ")");

    final ThrowingConsumer<DatabaseColumn> throwingConsumer = column -> {
       try {
        String alright = "herpderp";
        cstmt.setObject(column.getName(), entity.getClass().getDeclaredField(column.getName()).get(entity) /**, SQLType targetSqlType ?? */ );
           ParameterMetaData meta =   cstmt.getParameterMetaData();
       } catch(Exception e) {
           e.printStackTrace();
       }
    };
    columns.stream().forEach(throwingConsumer);

    cstmt.execute();
    return null;
}


电话:

cstmt.setObject(column.getName(), entity.getClass().getDeclaredField(column.getName()).get(entity) /**, SQLType targetSqlType ?? */ );


出现nullpointer异常失败,我检查了两个值都很好,但最终它只执行了null指针。准备好的语句看起来也很好。我正在尝试使用namedParameters,这就是我认为的罪魁祸首,我试图检查我的设置是否甚至与namedParameters兼容,结果发现DatabaseMetaData并不这么认为,在以下代码中:

DatabaseMetaData dbMeta  = connection.getMetaData();
boolean okay = dbMeta.supportsNamedParameters();
if(okay) {
    System.out.println("Supports named arguments");
} else {
    System.out.println("Does not support named arguments");
}


。以下是我的版本:

    compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.3'

    mysql: mysql  Ver 14.14 Distrib 5.7.13, for Linux (x86_64) using  EditLine wrapper


几乎是最新的。

如果我使用调试器运行它,则给出空指针的情况如下所示:

cstmt.setObject("email", "[email protected]");


callableStatement中的orginalSql字段如下所示:

create_account(?, ?, ?, ?, ?)


存储过程如下所示:

CREATE DEFINER=`root`@`localhost` PROCEDURE `create_account`(email VARCHAR(45), username VARCHAR (45), pw VARCHAR (45), guid VARCHAR(45), verified tinyint(4))
BEGIN
insert into account (`email`, `username`, `password`, `guid`, `verified`) values (email, username, pw, guid, verified);
END


谢谢

最佳答案

调用存储过程时,它像这样:

 CallableStatement cstmt = connection.prepareCall("{CALL create_" + table.getName() + "(" + columns.stream().map( column -> "?").collect(Collectors.joining(","))  + ")}");


如果没有CALL,那就不好了,只希望错误消息更有用,显然是个完整的脑筋:)

08-03 12:31