自定义SQL插入如何返回自增ID?
7 回复
以供参考
@Override
public Object invoke() {
Sql sql = Sqls.create(methodSignature.getSql()).setParams(this.params);
AtomicReference<Object> idGeneratedKey = new AtomicReference<>();
dao.run(conn -> {
PreparedStatement ps = conn.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
try {
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
if (ValueTypeUtil.isNumber(this.methodSignature.getReturnType())) {
idGeneratedKey.set(rs.getInt(1));
} else {
idGeneratedKey.set(rs.getString(1));
}
}
rs.close();
} finally {
Daos.safeClose(ps);
}
});
return idGeneratedKey.get();
}
完善后
@Override
public Object invoke() {
Sql sql = Sqls.create(methodSignature.getSql()).setParams(this.params);
if (this.methodSignature.getReturnType() == void.class) {
dao.execute(sql);
return sql.getUpdateCount();
} else {
NutSql daoStatement = new NutSql(methodSignature.getSql());
daoStatement.setExpert(dao.getJdbcExpert());
daoStatement.setParams(this.params);
String originalSql = daoStatement.toPreparedStatement();
ValueAdaptor[] adaptors = daoStatement.getAdaptors();
Object[][] paramMatrix = daoStatement.getParamMatrix();
AtomicReference<Object> idGeneratedKey = new AtomicReference<>();
dao.run(conn -> {
PreparedStatement preparedStatement = conn.prepareStatement(originalSql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = null;
try {
for (int i = 0; i < paramMatrix[0].length; i++) {
adaptors[i].set(preparedStatement, paramMatrix[0][i], i + 1);
}
preparedStatement.executeUpdate();
rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
if (ValueTypeUtil.isNumber(this.methodSignature.getReturnType())) {
idGeneratedKey.set(rs.getInt(1));
} else {
idGeneratedKey.set(rs.getString(1));
}
}
} finally {
Daos.safeClose(preparedStatement, rs);
}
});
return idGeneratedKey.get();
}
}
添加回复
请先登陆